@mxalbert/context-mode 2.0.1 → 2.0.3
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/README.md +1 -1
- package/build/adapters/opencode/plugin.d.ts +60 -2
- package/build/adapters/opencode/plugin.js +89 -1
- package/build/adapters/opencode/v2.d.ts +11 -0
- package/build/db-base.d.ts +16 -0
- package/build/db-base.js +29 -3
- package/build/server.js +98 -46
- package/build/session/purge.js +2 -1
- package/build/store.d.ts +22 -3
- package/build/store.js +282 -73
- package/cli.bundle.mjs +165 -165
- package/configs/antigravity-cli/plugin.json +1 -1
- package/configs/copilot-cli/.github/plugin/plugin.json +1 -1
- package/hooks/core/routing.mjs +168 -5
- package/hooks/session-db.bundle.mjs +7 -7
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server.bundle.mjs +128 -128
package/cli.bundle.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function
|
|
4
|
-
${e.stack}`:"",p=o?` [${o}]`:"";console.error(`${
|
|
5
|
-
`))}function
|
|
6
|
-
`)}function
|
|
2
|
+
var iI=Object.create;var Qd=Object.defineProperty;var aI=Object.getOwnPropertyDescriptor;var cI=Object.getOwnPropertyNames;var uI=Object.getPrototypeOf,lI=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_e=(t,e)=>{for(var n in e)Qd(t,n,{get:e[n],enumerable:!0})},dI=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cI(e))!lI.call(t,o)&&o!==n&&Qd(t,o,{get:()=>e[o],enumerable:!(r=aI(e,o))||r.enumerable});return t};var Ri=(t,e,n)=>(n=t!=null?iI(uI(t)):{},dI(e||!t||!t.__esModule?Qd(n,"default",{value:t,enumerable:!0}):n,t));var op=L((sW,xx)=>{"use strict";var rp={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let n="";return t<0?n+=`\x1B[${-t}D`:t>0&&(n+=`\x1B[${t}C`),e<0?n+=`\x1B[${-e}A`:e>0&&(n+=`\x1B[${e}B`),n},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"},EI={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},TI={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 n=0;n<t;n++)e+=this.line+(n<t-1?rp.up():"");return t&&(e+=rp.left),e}};xx.exports={cursor:rp,scroll:EI,erase:TI,beep:"\x07"}});var $x=L((qW,lp)=>{var Ic=process||{},Ex=Ic.argv||[],Oc=Ic.env||{},XI=!(Oc.NO_COLOR||Ex.includes("--no-color"))&&(!!Oc.FORCE_COLOR||Ex.includes("--color")||Ic.platform==="win32"||(Ic.stdout||{}).isTTY&&Oc.TERM!=="dumb"||!!Oc.CI),YI=(t,e,n=t)=>r=>{let o=""+r,s=o.indexOf(e,t.length);return~s?t+QI(o,e,n,s)+e:t+o+e},QI=(t,e,n,r)=>{let o="",s=0;do o+=t.substring(s,r)+n,s=r+e.length,r=t.indexOf(e,s);while(~r);return o+t.substring(s)},Tx=(t=XI)=>{let e=t?YI:()=>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")}};lp.exports=Tx();lp.exports.createColors=Tx});function Ii(t,e){let n=process.execPath.replace(/\\/g,"/");if(ro(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");dp.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function We(t,e){if(ro(e?.platform))return Ii(t,e);let r=pp().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Ac(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 ro(t){return!!t&&eA.has(t)}var dp,eA,Nn=x(()=>{"use strict";as();dp=new Set(["node","bun","deno"]),eA=new Set(["opencode","kilo"])});var Nx={};_e(Nx,{buildCommand:()=>yp,detectRuntimes:()=>oo,getAvailableLanguages:()=>Di,getRuntimeSummary:()=>Ni,hasBunRuntime:()=>Sr,isAllowlistedShell:()=>Rx,resetHookRuntimeCache:()=>iA,resolveHookRuntime:()=>pp,resolveJavascriptRuntime:()=>Ax});import{execFileSync as hp,execSync as cs}from"node:child_process";import{existsSync as us}from"node:fs";function mp(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function Rx(t){return tA.test(mp(t))}function nA(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function rA(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Je(t){try{let e=Ai?`where ${t}`:`command -v ${t}`;return cs(e,{stdio:"pipe"}),!0}catch{return!1}}function fp(t){if(Ai)try{let n=cs(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Je(t))return!1;try{return Ai?cs(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):hp(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function gp(){if(Je("bun"))return!0;for(let t of Ox())if(us(t))return!0;return!1}function Cx(){for(let e of Ox())if(us(e))return e;if(Je("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ai?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Ox(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ai){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function Ix(){let t;try{t=cs("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of oA)if(us(r))return r;return e}}return null}function sA(t=Ix()){return t??(Je("sh")?"sh":Je("pwsh")?"pwsh":Je("powershell")?"powershell":"cmd.exe")}function en(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return cs(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return hp(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Ax(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Je,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return dp.has(o)&&us(n)?n:r("node")?"node":null}function oo(){let e=gp()?Cx():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Ix():null,s=n&&us(n)&&Rx(n)&&!(r&&nA(n))&&!(r&&o&&rA(n))?n:null;return{javascript:Ax(e),typescript:e||(Je("tsx")?"tsx":Je("ts-node")?"ts-node":null),python:fp("python3")?"python3":fp("python")?"python":fp("py")?"py":null,shell:s??(r?sA(o):Je("bash")?"bash":"sh"),ruby:Je("ruby")?"ruby":null,go:Je("go")?"go":null,rust:Je("rustc")?"rustc":null,php:Je("php")?"php":null,perl:Je("perl")?"perl":null,r:Je("Rscript")?"Rscript":Je("r")?"r":null,elixir:Je("elixir")?"elixir":null,csharp:Je("dotnet-script")?"dotnet-script":null}}function Sr(){return gp()}function iA(){Wt=null}function aA(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function cA(){return us(process.execPath)?{path:process.execPath,isBun:!1}:Je("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function pp(){if(Wt)return Wt;let t=cA();try{if(!gp())return Wt=t,Wt;let e=Cx(),n;try{if(process.platform==="win32"){let r=cs(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=hp(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Wt=t,Wt}return aA(n)?(Wt={path:e,isBun:!0},Wt):(Wt=t,Wt)}catch{return Wt=t,Wt}}function Ni(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${en(t.javascript)})${n?" \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} (${en(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${en(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${en(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${en(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${en(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${en(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${en(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${en(t.perl)})`),t.r&&e.push(` R: ${t.r} (${en(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${en(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${en(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
3
|
+
`)}function Di(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 yp(t,e,n){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(mp(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];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(mp(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var tA,Px,Ai,oA,Wt,as=x(()=>{"use strict";Nn();tA=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Px=/^bun(\.exe)?$/i;Ai=process.platform==="win32";oA=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Wt=null});function uA(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function lA(t){let e=Ac(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function Nc(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of uA(s)){let a=lA(i);a&&n.add(a)}return[...n]}var _p=x(()=>{"use strict";Nn()});var Dx,Mx=x(()=>{"use strict";Dx={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","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 Sp={};_e(Sp,{BunSQLiteAdapter:()=>Dc,DB_LOG_PREFIX:()=>Vx,NodeSQLiteAdapter:()=>Mc,SQLiteBase:()=>ji,applyWALPragmas:()=>so,cleanOrphanedWALFiles:()=>vr,closeDB:()=>ds,defaultDBPath:()=>xp,deleteDBFiles:()=>jc,errorMessage:()=>Li,extractErrorCode:()=>ps,getRecentDbErrorCountForTests:()=>yA,hasModernSqlite:()=>Ux,isSQLiteCorruptionError:()=>Lc,isTransientSqliteError:()=>Zx,loadDatabase:()=>Xe,logDbError:()=>ot,nodeSqliteHasFts5:()=>Hx,renameCorruptDB:()=>qx,resetDbErrorLogForTests:()=>gA,resolveMmapSizeFromEnv:()=>Fx,withRetry:()=>ze});import{createRequire as dA}from"node:module";import{existsSync as pA,unlinkSync as zx,renameSync as fA}from"node:fs";import{tmpdir as mA}from"node:os";import{join as hA}from"node:path";function Hx(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 Ux(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.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 Xe(){if(!ls){let t=dA(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ls=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new Dc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(Ux()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&Hx(e)?ls=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new Mc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:ls=t("better-sqlite3")}else ls=t("better-sqlite3")}return ls}function so(t,e=process.env){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");let n=Fx(e);if(n!==null)try{t.pragma(`mmap_size = ${n}`)}catch{}}function Fx(t=process.env){let e=t.CONTEXT_MODE_DB_MMAP_SIZE;if(e==null)return null;let n=String(e).trim();if(n==="")return null;let r=Number(n);return!Number.isFinite(r)||!Number.isInteger(r)||r<0?null:r}function vr(t){if(!pA(t))for(let e of["-wal","-shm"])try{zx(t+e)}catch{}}function jc(t){for(let e of["","-wal","-shm"])try{zx(t+e)}catch{}}function ds(t){try{t.close()}catch{}}function xp(t="context-mode"){return hA(mA(),`${t}-${process.pid}.db`)}function Bx(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?`${e} ${t.message}`:t.message}if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.code,n=t.message,r=[typeof e=="string"?e:"",typeof n=="string"?n:""].filter(Boolean);return r.length>0?r.join(" "):String(t)}return String(t)}function Zx(t){let e=Bx(t);return e.includes("SQLITE_BUSY")||e.includes("database is locked")||e.includes("SQLITE_IOERR")||/disk i\/o error/i.test(e)}function ze(t,e=[100,500,2e3]){let n;for(let s=0;s<=e.length;s++)try{return t()}catch(i){if(!Zx(i))throw i;if(n=i instanceof Error?i:new Error(Bx(i)),!(i instanceof Error)){let a=ps(i);a&&(n.code=a)}if(s<e.length){let a=e[s],c=Date.now();for(;Date.now()-c<a;);}}let r=new Error(`SQLITE_BUSY/SQLITE_IOERR: transient SQLite error after ${e.length} retries. Original error: ${n?.message}`),o=n?ps(n):"";throw o&&(r.code=o),r}function Lc(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 qx(t){let e=Date.now();for(let n of["","-wal","-shm"])try{fA(t+n,`${t}${n}.corrupt-${e}`)}catch{}}function ps(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?e:""}if(t!==null&&typeof t=="object"){let e=t.code;return typeof e=="string"?e:""}return""}function Li(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.message;if(typeof e=="string"&&e)return e}return String(t)}function ot(t,e,n,r=Date.now()){try{let o=ps(e),s=Li(e),i=n?` (${n})`:"",a=`${t}|${o}|${s}${i}`,c=Dn.get(a);if(c!==void 0&&r-c<jx)return;if(Dn.set(a,r),Dn.size>Lx){for(let[m,f]of Dn)r-f>=jx&&Dn.delete(m);for(;Dn.size>Lx;){let m=Dn.keys().next().value;if(m===void 0)break;Dn.delete(m)}}let u=process.env.OPENCODE_DEBUG,d=u!==void 0&&u!==""&&u!=="0"&&u!=="false"&&e instanceof Error&&e.stack?`
|
|
4
|
+
${e.stack}`:"",p=o?` [${o}]`:"";console.error(`${Vx} ${t}${p}: ${s}${i}${d}`)}catch{}}function gA(){Dn.clear()}function yA(){return Dn.size}var Dc,Mc,ls,Vx,jx,Lx,Dn,Mi,bp,ji,er=x(()=>{"use strict";Dc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},Mc=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},ls=null;Vx="[context-mode:db]",jx=3e4,Lx=256,Dn=new Map;Mi=Symbol.for("__context_mode_live_dbs_v3__"),bp=(()=>{let t=globalThis;return t[Mi]||(t[Mi]=new Set,process.on("exit",()=>{for(let e of t[Mi])ds(e);t[Mi].clear()})),t[Mi]})(),ji=class{#e;#t;constructor(e){let n=Xe();this.#e=e,vr(e);let r;try{r=new n(e,{timeout:3e4}),so(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Lc(s)){ot("SQLiteBase.open",o,e),qx(e),vr(e);try{r=new n(e,{timeout:3e4}),so(r)}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=r,bp.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){bp.delete(this.#t),ds(this.#t)}withRetry(e){return ze(e)}cleanup(){bp.delete(this.#t),ds(this.#t),jc(this.#e)}}});var sS={};_e(sS,{SessionDB:()=>nn,StorageDirectoryError:()=>tn,_resetWorktreeSuffixCacheForTests:()=>NA,applyMissingSessionEventsColumns:()=>wp,clearStorageDirectoryCheckCacheForTests:()=>PA,describeStorageDirectorySource:()=>Hi,ensureSessionEventsSchema:()=>Ep,ensureWritableStorageDir:()=>Tr,formatStorageDirectoryError:()=>gs,getWorktreeSuffix:()=>Ui,hashProjectDirCanonical:()=>st,hashProjectDirLegacy:()=>jn,normalizeWorktreePath:()=>wr,resolveContentStorageDir:()=>io,resolveContentStorePath:()=>kp,resolveDefaultSessionDir:()=>Fc,resolveSessionDbPath:()=>ys,resolveSessionPath:()=>Bc,resolveSessionStorageDir:()=>Er,resolveStatsStorageDir:()=>hs});import{createHash as zi}from"node:crypto";import{execFileSync as _A}from"node:child_process";import{accessSync as bA,constants as xA,existsSync as Uc,mkdirSync as SA,realpathSync as vA,renameSync as vp}from"node:fs";import{homedir as Yx}from"node:os";import{dirname as kA,isAbsolute as Qx,join as kr,resolve as ms}from"node:path";function Fc(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):kr(wA(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function wA(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?Kx(r.trim()):Kx(t,Yx())}function Kx(t,e){return t.startsWith("~")?ms(Yx(),t.replace(/^~[/\\]?/,"")):Qx(t)?ms(t):e?ms(e,t):ms(t)}function EA(t,e,n){return new tn(t,e,Mn,void 0,[`Invalid ${Mn} for context-mode ${t} directory: ${n}`,rS()].join(`
|
|
5
|
+
`))}function tS(t){let e=process.env[Mn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Mn,ignoredReason:"empty"};if(!Qx(n))throw EA(t,n,`${Mn} must be an absolute path.`);return{kind:"override",root:ms(n)}}function TA(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function nS(t,e){let n=tS(t);return n.kind!=="override"?null:{kind:t,path:kr(n.root,e),envVar:Mn,source:"override"}}function $A(t,e,n){return{kind:t,path:ms(e()),envVar:null,source:"default",...n}}function Er(t){let e=tS("session");return e.kind==="override"?{kind:"session",path:kr(e.root,eS),envVar:Mn,source:"override"}:$A("session",t,TA(e))}function io(t){let e=nS("content",Wx);if(e)return e;let n=Er(t);return{kind:"content",path:kr(kA(n.path),Wx),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function hs(t){let e=nS("stats",eS);if(e)return e;let n=Er(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function gs(t){return t.message}function Hi(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function PA(){Hc.clear()}function Tr(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Hc.get(e);if(n instanceof tn)throw n;if(n===t.path)return n;try{return SA(t.path,{recursive:!0}),bA(t.path,xA.W_OK),Hc.set(e,t.path),t.path}catch(r){let o=new tn(t.kind,OA(r)??t.path,Mn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Hc.set(e,o),o}}function RA(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,CA(n),rS()].filter(Boolean).join(`
|
|
6
|
+
`)}function CA(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function rS(){return`Set ${Mn} to a writable absolute path.`}function OA(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function wr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function Gx(t){let e=t;try{e=vA.native(t)}catch{}let n=wr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function oS(t,e){return _A("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function IA(t){let e=oS(t,["rev-parse","--show-toplevel"]);return e.length>0?wr(e):null}function AA(t){let e=oS(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?wr(e):null}function Ui(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(fs&&fs.projectDir===t&&fs.envSuffix===e)return fs.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=IA(t),o=AA(t);if(r&&o){let s=Gx(r),i=Gx(o);s!==i&&(n=`__${zi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return fs={projectDir:t,envSuffix:e,suffix:n},n}function NA(){fs=void 0}function jn(t){return zi("sha256").update(wr(t)).digest("hex").slice(0,16)}function st(t){let e=wr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return zi("sha256").update(n).digest("hex").slice(0,16)}function kp(t){let{projectDir:e,contentDir:n}=t,r=st(e),o=kr(n,`${r}.db`);if(Uc(o))return o;let s=jn(e);if(s===r)return o;let i=kr(n,`${s}.db`);if(Uc(i))try{vp(i,o);for(let a of["-wal","-shm"])try{vp(i+a,o+a)}catch{}}catch{}return o}function ys(t){return Bc({...t,ext:".db"})}function Bc(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??Ui(e),s=st(e),i=kr(n,`${s}${o}${r}`);if(Uc(i))return i;let a=jn(e);if(a===s)return i;let c=kr(n,`${a}${o}${r}`);if(Uc(c))try{vp(c,i)}catch{}return i}function zc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function wp(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of DA)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function Ep(t,e){let n=null;try{n=new e(t),wp(n)}catch(r){ot("ensureSessionEventsSchema",r,t)}finally{try{n?.close()}catch{}}}var Mn,eS,Wx,tn,Hc,fs,Jx,Xx,F,DA,nn,rn=x(()=>{"use strict";er();Mn="CONTEXT_MODE_DIR",eS="sessions",Wx="content",tn=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Mn,o,s,i={}){super(s??RA(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},Hc=new Map;Jx=1e3,Xx=5;F={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",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},DA=[["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"]];nn=class extends ji{constructor(e){super(e?.dbPath??xp("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=(this.db.pragma("table_xinfo(session_events)")??[]).find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch(e){ot("SessionDB.initSchema.dataHashMigration",e,this.dbPath)}this.db.exec(`
|
|
7
7
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
8
8
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
9
9
|
session_id TEXT NOT NULL,
|
|
@@ -53,7 +53,7 @@ ${e.stack}`:"",p=o?` [${o}]`:"";console.error(`${Zx} ${t}${p}: ${s}${i}${d}`)}ca
|
|
|
53
53
|
);
|
|
54
54
|
|
|
55
55
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
56
|
-
`);try{
|
|
56
|
+
`);try{wp(this.db)}catch(e){ot("SessionDB.initSchema.migrateColumns",e,this.dbPath)}try{(this.db.pragma("table_xinfo(session_meta)")??[]).some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch(e){ot("SessionDB.initSchema.usageCursorMigration",e,this.dbPath)}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(F.insertEvent,`INSERT INTO session_events (
|
|
57
57
|
session_id, type, category, priority, data,
|
|
58
58
|
project_dir, attribution_source, attribution_confidence,
|
|
59
59
|
bytes_avoided, bytes_returned,
|
|
@@ -142,51 +142,51 @@ ${e.stack}`:"",p=o?` [${o}]`:"";console.error(`${Zx} ${t}${p}: ${s}${i}${d}`)}ca
|
|
|
142
142
|
FROM tool_calls WHERE session_id = ?`),e(F.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
143
143
|
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(F.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
144
144
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
145
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=
|
|
145
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=zi("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=zc(s?.bytesAvoided),p=zc(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(F.checkDuplicate).get(e,Xx,n.type,i))return;this.stmt(F.getEventCount).get(e).cnt>=Jx&&this.stmt(F.evictLowestPriority).run(e),this.stmt(F.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,p,r,i),this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=zi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],p=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),m=p===""?"":wr(p),f=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=zc(y?.bytesAvoided),b=zc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:f,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(F.getEventCount).get(e).cnt;for(let u of i)this.stmt(F.checkDuplicate).get(e,Xx,u.event.type,u.dataHash)||(c>=Jx?this.stmt(F.evictLowestPriority).run(e):c++,this.stmt(F.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,r,u.dataHash));this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(F.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(F.getEventsByType).all(e,o,r):s!==void 0?this.stmt(F.getEventsByPriority).all(e,s,r):this.stmt(F.getEvents).all(e,r)}getEventCount(e){return this.stmt(F.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(F.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(F.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(n){return ot("SessionDB.getSessionProjectDir",n,this.dbPath),""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(F.searchEvents).all(r,s,s,i,i,n)}catch(s){return ot("SessionDB.searchEvents",s,this.dbPath),[]}}getSessionIdsForProject(e){try{let n=wr(e);return this.db.prepare(`SELECT DISTINCT session_id
|
|
146
146
|
FROM session_events
|
|
147
|
-
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch(n){return
|
|
148
|
-
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,
|
|
149
|
-
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function
|
|
150
|
-
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[be.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[be.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(
|
|
151
|
-
`,"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}`}}});function
|
|
147
|
+
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch(n){return ot("SessionDB.getSessionIdsForProject",n,this.dbPath),[]}}ensureSession(e,n){this.stmt(F.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(F.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(F.getSessionRollup).get(e),r=this.stmt(F.getMaxFileEdits).get(e),o=this.stmt(F.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(F.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(F.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(F.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(F.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(F.getResume).get(e)??null}markResumeConsumed(e){this.stmt(F.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(F.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.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(e){return ot("SessionDB.getLatestSessionId",e,this.dbPath),null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(F.incrementToolCall).run(e,n,o)}catch(s){ot("SessionDB.incrementToolCall",s,this.dbPath)}}getToolCallStats(e){try{let n=this.stmt(F.getToolCallTotals).get(e),r=this.stmt(F.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch(n){return ot("SessionDB.getToolCallStats",n,this.dbPath),{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(F.deleteEvents).run(e),this.stmt(F.deleteResume).run(e),this.stmt(F.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(F.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.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 _s,resolve as iS}from"node:path";import{accessSync as MA,copyFileSync as jA,constants as LA,mkdirSync as zA}from"node:fs";import{homedir as Tp}from"node:os";function bt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?iS(Tp(),e.replace(/^~[/\\]?/,"")):iS(e)}var ve,lt=x(()=>{"use strict";rn();ve=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=bt(),n=e?_s(e,"context-mode","sessions"):_s(Tp(),...this.sessionDirSegments,"context-mode","sessions");return zA(n,{recursive:!0}),n}getConfigDir(e){return _s(Tp(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=bt(),r=n?_s(n,"context-mode","memory"):_s(this.getConfigDir(),"memory");return e?_s(r,st(e)):r}backupSettings(){let e=this.getSettingsPath();try{MA(e,LA.R_OK);let n=e+".bak";return jA(e,n),n}catch{return null}}}});var bs,$p=x(()=>{"use strict";lt();bs=class extends ve{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Pp}from"node:fs";import{join as Rp}from"node:path";async function HA(){if(xs)return xs;if(Ss)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 n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return xs=r,xs}catch(r){e=r}return Ss=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return Ss=t instanceof Error?t.message:String(t),null}}function UA(t){let e=[];return Pp(Rp(t,"start.mjs"))||e.push("start.mjs"),!Pp(Rp(t,"server.bundle.mjs"))&&!Pp(Rp(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function aS(t){if(xs){let e=xs.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(Ss){let e=UA(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${Ss}); the MCP server cannot start. Reinstall: npm install -g @mxalbert/context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${Ss}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var xs,Ss,cS=x(()=>{"use strict";xs=null,Ss=null;HA()});function Fi(t,e){let n=ao[e],r=Op(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function Op(t,e){if(e){let n=ao[t];return We(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Ip(t){let e=Ac(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function dS(t){let e=Object.values(ao);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var on,FA,Cp,uS,BA,S3,ao,lS,v3,pS=x(()=>{"use strict";Nn();on={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},FA="mcp__",Cp=["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",FA],uS=Cp.join("|"),BA=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],S3=BA.join("|"),ao={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},lS=[on.PRE_TOOL_USE,on.SESSION_START],v3=[on.POST_TOOL_USE,on.PRE_COMPACT,on.USER_PROMPT_SUBMIT,on.STOP]});var Np={};_e(Np,{ClaudeCodeAdapter:()=>Ap});import{readFileSync as Zc,writeFileSync as fS,existsSync as mS,readdirSync as ZA,chmodSync as qA,accessSync as VA,mkdirSync as WA,constants as KA}from"node:fs";import{resolve as qc,join as $r}from"node:path";import{homedir as hS}from"node:os";var Ap,Dp=x(()=>{"use strict";$p();lt();Pr();cS();Nn();pS();Ap=class extends bs{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 Ze()}getSessionDir(){let e=bt(),n=e?$r(e,"context-mode","sessions"):$r(this.getConfigDir(),"context-mode","sessions");return WA(n,{recursive:!0}),n}getSettingsPath(){return $r(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=We(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Cp].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=Zc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){fS(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
148
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,on.PRE_TOOL_USE);n.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,on.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(ao).map(([o,s])=>{let i=$r(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>mS(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>aS(e)};return[...n,r]}readPluginHooks(e){let n=[$r(e,"hooks","hooks.json"),$r(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=Zc(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Fi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Fi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=$r(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Zc(n,"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(),Ze(),qc(hS(),".claude"),qc(hS(),".config","claude")]));for(let n of e){let r=qc(n,"plugins","cache","context-mode","context-mode");try{let s=ZA(r).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 n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(m=>{let f=m;if(!dS(f))return!0;let h=f.hooks??[];return h.every(y=>!y.command||!Ip(y.command))?!0:h.every(y=>{let _=y.command?Ip(y.command):null;return _?mS(_):!0})}),p=l.length-d.length;p>0&&(r[u]=d,o.push(`Removed ${p} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&lS.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(ao),d=p=>p!=null&&(l.some(m=>p.includes(m))||p.includes("context-mode hook"));for(let p of Object.keys(r)){let m=r[p];if(!Array.isArray(m))continue;let f=0;for(let g of m){let y=g,_=y.hooks??[],b=_.length;y.hooks=_.filter(S=>!d(S.command)),f+=b-y.hooks.length}let h=m.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(f>0||h.length!==m.length)&&(r[p]=h,f>0&&o.push(`Removed ${f} duplicate ${p} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[on.PRE_TOOL_USE,on.SESSION_START];for(let u of c){let l=Op(u,e);if(u===on.PRE_TOOL_USE){let d={matcher:uS,hooks:[{type:"command",command:l}]},p=r.PreToolUse;if(p&&Array.isArray(p)){let m=p.findIndex(f=>Fi(f,u));m>=0?(p[m]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=p}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},p=r[u];if(p&&Array.isArray(p)){let m=p.findIndex(f=>Fi(f,u));m>=0?(p[m]=d,o.push(`Updated existing ${u} hook entry`)):(p.push(d),o.push(`Added ${u} hook entry`)),r[u]=p}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(ao)){let o=qc(e,"hooks",r);try{VA(o,KA.R_OK),qA(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=$r(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Zc(r,"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=n,a.lastUpdated=new Date().toISOString();fS(r,JSON.stringify(o,null,2)+`
|
|
149
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Rr(t,e){let n=Vc[t];return e&&n?We(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var be,gS,Vc,N3,D3,yS=x(()=>{"use strict";Nn();be={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},gS="mcp__(?!.*context-mode)",Vc={[be.BEFORE_AGENT]:"beforeagent.mjs",[be.BEFORE_TOOL]:"beforetool.mjs",[be.AFTER_TOOL]:"aftertool.mjs",[be.AFTER_MODEL]:"aftermodel.mjs",[be.PRE_COMPRESS]:"precompress.mjs",[be.SESSION_START]:"sessionstart.mjs"},N3=[be.BEFORE_TOOL,be.SESSION_START],D3=[be.AFTER_TOOL,be.AFTER_MODEL,be.PRE_COMPRESS]});var xS={};_e(xS,{GeminiCLIAdapter:()=>jp});import{readFileSync as Mp,writeFileSync as _S,mkdirSync as GA,accessSync as JA,chmodSync as XA,existsSync as YA,constants as QA}from"node:fs";import{resolve as Bi,join as bS}from"node:path";import{homedir as Wc}from"node:os";var jp,SS=x(()=>{"use strict";lt();yS();jp=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Bi(Wc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[be.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Rr(be.BEFORE_AGENT,e)}]}],[be.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|${gS}`,hooks:[{type:"command",command:Rr(be.BEFORE_TOOL,e)}]}],[be.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Rr(be.AFTER_TOOL,e)}]}],[be.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:Rr(be.AFTER_MODEL,e)}]}],[be.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Rr(be.PRE_COMPRESS,e)}]}],[be.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Rr(be.SESSION_START,e)}]}]}}readSettings(){try{let e=Mp(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Bi(Wc(),".gemini");GA(n,{recursive:!0}),_S(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
150
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[be.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[be.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(Vc).map(([n,r])=>{let o=bS(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>YA(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 n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).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=Bi(Wc(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(Mp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:be.BEFORE_AGENT},{name:be.BEFORE_TOOL},{name:be.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Rr(i.name,e)}]},u=r[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(m=>m.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`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=bS(e,"hooks","gemini-cli");for(let o of Object.values(Vc)){let s=Bi(r,o);try{JA(s,QA.R_OK),XA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Bi(Wc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Mp(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),_S(r,JSON.stringify(o,null,2)+`
|
|
151
|
+
`,"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}`}}});function vS(){return["packages",`${Kt}@latest`,"node_modules",Kt]}var Kt,eN,it,Kc,Zi=x(()=>{"use strict";Kt="@mxalbert/context-mode",eN="context-mode",it=`${eN}@${Kt}`,Kc=`https://registry.npmjs.org/${encodeURIComponent(Kt)}/latest`});function qi(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
|
|
152
152
|
`;)c++;c<t.length&&(e+=`
|
|
153
153
|
`);continue}if(!n&&u==="/"&&l==="*"){o=!0,c++;continue}e+=u}let s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){s+=u,a=!1;continue}if(u==="\\"){s+=u,a=i;continue}if(u==='"'){i=!i,s+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
|
|
154
|
-
`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function tr(t){for(let e of[t,
|
|
155
|
-
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)||Array.isArray(r.plugins)?n.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"}):n.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(r)&&(
|
|
156
|
-
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=rr(
|
|
157
|
-
`):null}function
|
|
154
|
+
`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function tr(t){for(let e of[t,qi(t)])try{return JSON.parse(e)}catch{}}var Vi=x(()=>{"use strict"});var co,Z3,q3,kS=x(()=>{"use strict";co={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},Z3=[co.BEFORE,co.AFTER],q3=[co.COMPACTING]});var PS={};_e(PS,{OpenCodeAdapter:()=>Lp,getPluginGlobalState:()=>cN,normalizeProjectKey:()=>TS,peekConfirmedNativeTools:()=>$S});import{readFileSync as wS,writeFileSync as tN,mkdirSync as nN,copyFileSync as rN,accessSync as oN,existsSync as sN,constants as iN,realpathSync as aN}from"node:fs";import{resolve as Dt,join as nr}from"node:path";import{homedir as Cr}from"node:os";function Wi(t){return Array.isArray(t)&&t.some(e=>typeof e=="string"&&e.includes("context-mode"))}function cN(){let t=globalThis;return t[Gc]||(t[Gc]={activations:new Map,loggedOnce:new Set,errorDedupe:new Map}),t[Gc]}function TS(t){let e;try{e=aN(t)}catch{e=Dt(t)}return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase():e}function $S(t){let n=globalThis[Gc];if(!n)return;let r=n.activations.get(TS(t));return r?r.nativeToolsConfirmed===!0:!1}function ES(t){let e=$S(process.cwd());return e!==void 0?e:Wi(t.plugin)}var Gc,Lp,RS=x(()=>{"use strict";lt();Zi();Vi();kS();Gc="__contextModePluginState";Lp=class extends ve{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities;platform;constructor(e="opencode",n){super([".config",e]),this.platform=e;let r=n?.sessionContextDegraded!==!0,o=n?.preCompactDegraded!==!0;this.capabilities={preToolUse:!0,postToolUse:!0,preCompact:o,sessionStart:r,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:r}}markCapabilityDegraded(e){e==="sessionStart"?this.capabilities.sessionStart=!1:e==="canInjectSessionContext"?this.capabilities.canInjectSessionContext=!1:this.capabilities.preCompact=!1}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Dt(`${this.platform}.jsonc`);return sN(e)?e:Dt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Dt("kilo.jsonc"),Dt("kilo.json"),Dt(".kilo","kilo.jsonc"),Dt(".kilo","kilo.json"),Dt(".kilocode","kilo.jsonc"),Dt(".kilocode","kilo.json"),nr(Cr(),".config","kilo","kilo.jsonc"),nr(Cr(),".config","kilo","kilo.json")]:[Dt("opencode.jsonc"),Dt("opencode.json"),Dt(".opencode","opencode.jsonc"),Dt(".opencode","opencode.json"),nr(Cr(),".config","opencode","opencode.jsonc"),nr(Cr(),".config","opencode","opencode.json")]}getSessionDir(){let e=bt(),n=e?nr(e,"context-mode","sessions"):nr(this.getConfigDir(),"context-mode","sessions");return nN(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||nr(Cr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||nr(Cr(),".config"),nr(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[co.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:Kt}]}],[co.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:Kt}]}],[co.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:Kt}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(Cr()))),r=null,o;for(let s of e)try{let i=wS(s,"utf-8"),a=s.endsWith(".jsonc")?qi(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){tN(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
155
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)||Array.isArray(r.plugins)?n.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"}):n.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(r)&&(ES(r)?n.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)"}):n.push({check:"Legacy MCP registration",status:"pass",message:"mcp.context-mode retained as tool fallback: v2 plugin native tool registration unconfirmed"})),this.capabilities.sessionStart?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}):n.push({check:"SessionStart hook",status:"warn",message:"SessionStart surrogate unavailable: session-context hook not confirmed on this host (v2 degraded) \u2014 resume snapshot injection inactive"}),n}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=Dt(Cr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(wS(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=Array.isArray(n.plugin),s=Array.isArray(n.plugins);if(o){let c=[...n.plugin];Wi(c)?r.push("context-mode already in plugin array"):(c.push(Kt),r.push("Added context-mode to plugin array")),n.plugin=c}if(s){let c=[...n.plugins];Wi(c)?r.push("context-mode already in plugins array"):(c.push(Kt),r.push("Added context-mode to plugins array")),n.plugins=c}!o&&!s&&(n.plugin=[Kt],r.push("Added context-mode to plugin array"));let i=ES(n),a=n.mcp;if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a;Object.prototype.hasOwnProperty.call(c,"context-mode")&&(i?(delete c["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")):r.push("Kept legacy context-mode MCP block (v2 native tool registration unconfirmed)")),Object.keys(c).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{oN(this.settingsPath,iN.R_OK);let n=this.settingsPath+".bak";return rN(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){return Wi(e.plugin)||Wi(e.plugins)}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var uo,eK,tK,CS=x(()=>{"use strict";uo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},eK=[uo.TOOL_CALL_BEFORE,uo.TOOL_CALL_AFTER],tK=[uo.COMMAND_NEW]});var OS={};_e(OS,{OpenClawAdapter:()=>Fp});import{readFileSync as zp,writeFileSync as uN,copyFileSync as lN,accessSync as dN,constants as pN}from"node:fs";import{resolve as rr,join as Hp}from"node:path";import{homedir as Up}from"node:os";var Fp,IS=x(()=>{"use strict";lt();CS();Fp=class extends ve{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 n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return rr("openclaw.json")}getConfigDir(e){return rr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Hp(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[uo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[uo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[uo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[rr("openclaw.json"),rr(".openclaw","openclaw.json"),Hp(Up(),".openclaw","openclaw.json")];for(let n of e)try{let r=zp(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=rr("openclaw.json");uN(n,JSON.stringify(e,null,2)+`
|
|
156
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=rr(Up(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(zp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=rr("node_modules","context-mode","package.json"),n=JSON.parse(zp(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[rr("openclaw.json"),rr(".openclaw","openclaw.json"),Hp(Up(),".openclaw","openclaw.json")];for(let n of e)try{dN(n,pN.R_OK);let r=n+".bak";return lN(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}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 AS}from"node:os";import{resolve as Bp}from"node:path";function NS(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Bp(AS(),t.replace(/^~[/\\]?/,"")):Bp(t):Bp(AS(),".codex")}var DS=x(()=>{"use strict"});var BS={};_e(BS,{CodexAdapter:()=>Vp,parseCodexContextModePluginRoot:()=>Xc,probeCodexCliVersion:()=>US});import{execFileSync as HS}from"node:child_process";import{existsSync as fN,readFileSync as vs,writeFileSync as MS,accessSync as mN,copyFileSync as hN,constants as gN,mkdirSync as Zp}from"node:fs";import{resolve as Jc,dirname as qp,join as or}from"node:path";import{fileURLToPath as yN}from"node:url";function US(t=HS){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function Xc(t){for(let e of t.split(/\r?\n/)){let n=e.match(new RegExp(`^\\s*${it}\\s+installed,\\s+enabled\\s+\\S+\\s+(.+?)\\s*$`));if(n?.[1])return n[1].trim()}return null}function Yc(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
|
|
157
|
+
`):null}function FS(t){let e=Yc(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function xN(t){let e=Yc(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function jS(t){let e=Yc(t,`plugins."${it}"`);return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function LS(t){return Yc(t,"mcp_servers.context-mode")!==null}function SN(t){if(FS(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
158
158
|
`)?`\r
|
|
159
159
|
`:`
|
|
160
160
|
`,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
|
|
161
|
-
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function
|
|
161
|
+
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function zS(t,e){let n=t.includes(`\r
|
|
162
162
|
`)?`\r
|
|
163
163
|
`:`
|
|
164
|
-
`,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){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(n),removed:s}}function bN(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var hN,lo,gN,Fp,Bp=x(()=>{"use strict";at();Ui();tn();NS();hN="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__",lo={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"},gN={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 ve{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??zS}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 AS()}getSettingsPath(){return or(this.getConfigDir(),"config.toml")}getSessionDir(){let e=gt(),n=e?or(e,"context-mode","sessions"):or(this.getConfigDir(),"context-mode","sessions");return Hp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=gt(),r=n?or(n,"context-mode","memories"):or(this.getConfigDir(),"memories");return e?or(r,rt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:hN,hooks:[{type:"command",command:lo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:lo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:lo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:lo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:lo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:lo.Stop}]}]}}readSettings(){try{return{_raw_toml:vs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=HS(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=vs(this.getSettingsPath(),"utf-8"),s=!0;let m=US(o),f=!m&&yN(o);n.push({check:"Codex hooks feature flag",status:m?"pass":"fail",message:m?`[features].hooks enabled in ${this.getSettingsPath()}`:f?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...m?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:`${ot} is enabled, but \`codex plugin list\` did not report its runtime root`,fix:`Restart Codex or verify \`codex plugin list\` shows ${ot} installed and enabled`}),c&&!u){let m=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${or(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&jS(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:`[mcp_servers.context-mode] is still registered while ${ot} 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 l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let m=Object.keys(i).map(f=>({check:`${f} hook`,status:"pass",message:`${f} hook provided by ${ot} plugin`}));return n.concat(m)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by ${ot} plugin`})):Object.entries(i).map(([m,f])=>{let h=l.config.hooks?.[m],g=f[0],y=Array.isArray(h)&&h.some(b=>this.isExpectedHookEntry(m,b,g)),_=m==="PreCompact"?"warn":"fail";return{check:`${m} hook`,status:y?"pass":_,message:y?`${m} hook configured in ${this.getHooksPath()}`:m==="PreCompact"?`${m} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${m} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let m of Object.keys(i)){let f=l.config.hooks?.[m];if(!Array.isArray(f))continue;let h=f.filter(g=>this.isManagedContextModeEntry(m,g)).length;h>1?p.push({check:`${m} duplicates`,status:"warn",message:`${h} context-mode entries found for ${m} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&p.push({check:`${m} plugin duplicate`,status:"warn",message:`${m} 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 n.concat(d,p)}checkPluginRegistration(){try{let e=vs(this.getSettingsPath(),"utf-8"),n=MS(e),r=jS(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:`${ot} plugin is enabled, but standalone [mcp_servers.context-mode] is also configured`,fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:`${ot} plugin enabled`}:r?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=vs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let f=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${f}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let f of Object.keys(l))this.removeManagedHookEntries(u,f,r);else for(let[f,h]of Object.entries(l))this.upsertManagedHookEntry(u,f,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=_N(s).text,m=p!==s;if(a){let f=LS(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));f.removed.length>0&&(p=f.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(p,u);h.removed.length>0&&(p=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(p!==s){let f=p.includes(`\r
|
|
164
|
+
`,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){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(n),removed:s}}function vN(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var _N,lo,bN,Vp,Wp=x(()=>{"use strict";lt();Zi();rn();DS();_N="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__",lo={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"},bN={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"]};Vp=class extends ve{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??HS}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 NS()}getSettingsPath(){return or(this.getConfigDir(),"config.toml")}getSessionDir(){let e=bt(),n=e?or(e,"context-mode","sessions"):or(this.getConfigDir(),"context-mode","sessions");return Zp(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=bt(),r=n?or(n,"context-mode","memories"):or(this.getConfigDir(),"memories");return e?or(r,st(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:_N,hooks:[{type:"command",command:lo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:lo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:lo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:lo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:lo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:lo.Stop}]}]}}readSettings(){try{return{_raw_toml:vs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=US(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=vs(this.getSettingsPath(),"utf-8"),s=!0;let m=FS(o),f=!m&&xN(o);n.push({check:"Codex hooks feature flag",status:m?"pass":"fail",message:m?`[features].hooks enabled in ${this.getSettingsPath()}`:f?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...m?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:`${it} is enabled, but \`codex plugin list\` did not report its runtime root`,fix:`Restart Codex or verify \`codex plugin list\` shows ${it} installed and enabled`}),c&&!u){let m=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${or(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&LS(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:`[mcp_servers.context-mode] is still registered while ${it} 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 l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let m=Object.keys(i).map(f=>({check:`${f} hook`,status:"pass",message:`${f} hook provided by ${it} plugin`}));return n.concat(m)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by ${it} plugin`})):Object.entries(i).map(([m,f])=>{let h=l.config.hooks?.[m],g=f[0],y=Array.isArray(h)&&h.some(b=>this.isExpectedHookEntry(m,b,g)),_=m==="PreCompact"?"warn":"fail";return{check:`${m} hook`,status:y?"pass":_,message:y?`${m} hook configured in ${this.getHooksPath()}`:m==="PreCompact"?`${m} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${m} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),p=[];for(let m of Object.keys(i)){let f=l.config.hooks?.[m];if(!Array.isArray(f))continue;let h=f.filter(g=>this.isManagedContextModeEntry(m,g)).length;h>1?p.push({check:`${m} duplicates`,status:"warn",message:`${h} context-mode entries found for ${m} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&p.push({check:`${m} plugin duplicate`,status:"warn",message:`${m} 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 n.concat(d,p)}checkPluginRegistration(){try{let e=vs(this.getSettingsPath(),"utf-8"),n=jS(e),r=LS(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:`${it} plugin is enabled, but standalone [mcp_servers.context-mode] is also configured`,fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:`${it} plugin enabled`}:r?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=vs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let f=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${f}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let f of Object.keys(l))this.removeManagedHookEntries(u,f,r);else for(let[f,h]of Object.entries(l))this.upsertManagedHookEntry(u,f,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let p=SN(s).text,m=p!==s;if(a){let f=zS(p,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));f.removed.length>0&&(p=f.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(p,u);h.removed.length>0&&(p=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(p!==s){let f=p.includes(`\r
|
|
165
165
|
`)?`\r
|
|
166
166
|
`:`
|
|
167
167
|
`,h=p.endsWith(`
|
|
168
|
-
`)?p:`${p}${f}`;
|
|
168
|
+
`)?p:`${p}${f}`;Zp(qp(o),{recursive:!0}),MS(o,h,"utf-8"),m&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{mN(n,gN.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Jc(qp(yN(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return vs(e,"utf-8")}catch{return`# context-mode
|
|
169
169
|
|
|
170
|
-
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 or(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return
|
|
171
|
-
`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return
|
|
172
|
-
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=EN(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Jc(r,o);try{vN(s,wN.R_OK),kN(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function ZS(t,e){if(!Zp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var rn,Zp,_K,bK,qS=x(()=>{"use strict";rn={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Zp={[rn.PRE_TOOL_USE]:"pretooluse.mjs",[rn.POST_TOOL_USE]:"posttooluse.mjs",[rn.PRE_COMPACT]:"precompact.mjs",[rn.SESSION_START]:"sessionstart.mjs"},_K=[rn.PRE_TOOL_USE,rn.SESSION_START],bK=[rn.POST_TOOL_USE,rn.PRE_COMPACT]});var WS={};_e(WS,{VSCodeCopilotAdapter:()=>Wp});import{readFileSync as qp,mkdirSync as VS,accessSync as TN,existsSync as $N,constants as PN}from"node:fs";import{resolve as ks,join as qi}from"node:path";import{homedir as Vp}from"node:os";var Wp,KS=x(()=>{"use strict";Xc();at();qS();Wp=class extends Ir{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:rn,HOOK_SCRIPTS:Zp,buildHookCommand:ZS};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=gt();if(e){let s=qi(e,"context-mode","sessions");return VS(s,{recursive:!0}),s}let n=ks(".github","context-mode","sessions"),r=qi(Vp(),".vscode","context-mode","sessions"),o=$N(ks(".github"))?n:r;return VS(o,{recursive:!0}),o}getConfigDir(e){return ks(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=ks(".github","hooks");try{TN(r,PN.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=ks(r,"context-mode.json");try{let s=qp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[rn.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[rn.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=ks(".vscode","mcp.json"),n=qp(e,"utf-8"),o=JSON.parse(n).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=[qi(Vp(),".vscode","extensions"),qi(Vp(),".vscode-insiders","extensions")];for(let n of e)try{let r=qp(qi(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 GS(t,e){if(!Kp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var on,Kp,$K,PK,JS=x(()=>{"use strict";on={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Kp={[on.PRE_TOOL_USE]:"pretooluse.mjs",[on.POST_TOOL_USE]:"posttooluse.mjs",[on.PRE_COMPACT]:"precompact.mjs",[on.SESSION_START]:"sessionstart.mjs"},$K=[on.PRE_TOOL_USE,on.SESSION_START],PK=[on.POST_TOOL_USE,on.PRE_COMPACT]});var XS={};_e(XS,{JetBrainsCopilotAdapter:()=>Gp});import{readFileSync as RN}from"node:fs";import{resolve as CN}from"node:path";var Gp,YS=x(()=>{"use strict";Xc();JS();Gp=class extends Ir{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:on,HOOK_SCRIPTS:Kp,buildHookCommand:GS};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 CN(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=RN(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[on.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[on.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function QS(t,e){let n=Jp[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var kt,Jp,DK,MK,ev=x(()=>{"use strict";kt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Jp={[kt.PRE_TOOL_USE]:"pretooluse.mjs",[kt.POST_TOOL_USE]:"posttooluse.mjs",[kt.PRE_COMPACT]:"precompact.mjs",[kt.SESSION_START]:"sessionstart.mjs",[kt.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[kt.STOP]:"stop.mjs"},DK=[kt.PRE_TOOL_USE,kt.SESSION_START],MK=[kt.POST_TOOL_USE,kt.PRE_COMPACT,kt.USER_PROMPT_SUBMIT,kt.STOP]});var iv={};_e(iv,{CopilotCliAdapter:()=>Yp,copilotCliHome:()=>Qc,copilotCliMcpConfigPath:()=>Yc});import{existsSync as tv,mkdirSync as nv,readFileSync as Xp,writeFileSync as ON}from"node:fs";import{homedir as rv}from"node:os";import{dirname as IN,join as ws,resolve as sv}from"node:path";function ov(){return process.env[AN]==="1"}function NN(t){return sv(t,"configs","copilot-cli","hooks.json")}function DN(t){return tr(Xp(t,"utf-8"))??{}}function MN(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Qc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?ws(rv(),t.replace(/^~[/\\]?/,"")):sv(t):ws(rv(),".copilot")}function Yc(){return ws(Qc(),"mcp-config.json")}var AN,Yp,av=x(()=>{"use strict";Xc();at();Bi();ev();AN="CONTEXT_MODE_COPILOT_PLUGIN";Yp=class extends Ir{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:kt,HOOK_SCRIPTS:Jp,buildHookCommand:QS};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return ws(Qc(),"hooks","context-mode.json")}getConfigDir(e){return Qc()}getSessionDir(){let e=gt(),n=e?ws(e,"context-mode","sessions"):ws(this.getConfigDir(),"context-mode","sessions");return nv(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();nv(IN(n),{recursive:!0}),ON(n,JSON.stringify(e,null,2)+`
|
|
173
|
-
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=
|
|
174
|
-
`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of
|
|
170
|
+
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 or(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return hN(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(vs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();Zp(qp(n),{recursive:!0}),MS(n,JSON.stringify(e,null,2)+`
|
|
171
|
+
`,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return fN(or(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&jS(n),s=Jc(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Xc(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Jc(e))===this.normalizeCommand(Jc(n))}pruneStaleUserHookTrustState(e,n){let r=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 zS(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=vN(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(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let f=n[p]?.[d];return!f||!Array.isArray(f.hooks)||!f.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(lo[e]??""),s=bN[e]??[];return r.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 ZS,writeFileSync as kN,mkdirSync as wN,accessSync as EN,chmodSync as TN,constants as $N}from"node:fs";import{resolve as Qc,join as PN}from"node:path";var Or,eu=x(()=>{"use strict";lt();Or=class extends ve{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 Qc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=ZS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=ZS(Qc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();wN(Qc(".github","hooks"),{recursive:!0}),kN(n,JSON.stringify(e,null,2)+`
|
|
172
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=PN(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Qc(r,o);try{EN(s,$N.R_OK),TN(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function qS(t,e){if(!Kp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var sn,Kp,kK,wK,VS=x(()=>{"use strict";sn={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Kp={[sn.PRE_TOOL_USE]:"pretooluse.mjs",[sn.POST_TOOL_USE]:"posttooluse.mjs",[sn.PRE_COMPACT]:"precompact.mjs",[sn.SESSION_START]:"sessionstart.mjs"},kK=[sn.PRE_TOOL_USE,sn.SESSION_START],wK=[sn.POST_TOOL_USE,sn.PRE_COMPACT]});var KS={};_e(KS,{VSCodeCopilotAdapter:()=>Xp});import{readFileSync as Gp,mkdirSync as WS,accessSync as RN,existsSync as CN,constants as ON}from"node:fs";import{resolve as ks,join as Ki}from"node:path";import{homedir as Jp}from"node:os";var Xp,GS=x(()=>{"use strict";eu();lt();VS();Xp=class extends Or{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:sn,HOOK_SCRIPTS:Kp,buildHookCommand:qS};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=bt();if(e){let s=Ki(e,"context-mode","sessions");return WS(s,{recursive:!0}),s}let n=ks(".github","context-mode","sessions"),r=Ki(Jp(),".vscode","context-mode","sessions"),o=CN(ks(".github"))?n:r;return WS(o,{recursive:!0}),o}getConfigDir(e){return ks(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=ks(".github","hooks");try{RN(r,ON.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=ks(r,"context-mode.json");try{let s=Gp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[sn.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[sn.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=ks(".vscode","mcp.json"),n=Gp(e,"utf-8"),o=JSON.parse(n).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=[Ki(Jp(),".vscode","extensions"),Ki(Jp(),".vscode-insiders","extensions")];for(let n of e)try{let r=Gp(Ki(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 JS(t,e){if(!Yp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var an,Yp,IK,AK,XS=x(()=>{"use strict";an={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Yp={[an.PRE_TOOL_USE]:"pretooluse.mjs",[an.POST_TOOL_USE]:"posttooluse.mjs",[an.PRE_COMPACT]:"precompact.mjs",[an.SESSION_START]:"sessionstart.mjs"},IK=[an.PRE_TOOL_USE,an.SESSION_START],AK=[an.POST_TOOL_USE,an.PRE_COMPACT]});var YS={};_e(YS,{JetBrainsCopilotAdapter:()=>Qp});import{readFileSync as IN}from"node:fs";import{resolve as AN}from"node:path";var Qp,QS=x(()=>{"use strict";eu();XS();Qp=class extends Or{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:an,HOOK_SCRIPTS:Yp,buildHookCommand:JS};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 AN(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=IN(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[an.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[an.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function ev(t,e){let n=ef[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var $t,ef,HK,UK,tv=x(()=>{"use strict";$t={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},ef={[$t.PRE_TOOL_USE]:"pretooluse.mjs",[$t.POST_TOOL_USE]:"posttooluse.mjs",[$t.PRE_COMPACT]:"precompact.mjs",[$t.SESSION_START]:"sessionstart.mjs",[$t.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[$t.STOP]:"stop.mjs"},HK=[$t.PRE_TOOL_USE,$t.SESSION_START],UK=[$t.POST_TOOL_USE,$t.PRE_COMPACT,$t.USER_PROMPT_SUBMIT,$t.STOP]});var av={};_e(av,{CopilotCliAdapter:()=>nf,copilotCliHome:()=>nu,copilotCliMcpConfigPath:()=>tu});import{existsSync as nv,mkdirSync as rv,readFileSync as tf,writeFileSync as NN}from"node:fs";import{homedir as ov}from"node:os";import{dirname as DN,join as ws,resolve as iv}from"node:path";function sv(){return process.env[MN]==="1"}function jN(t){return iv(t,"configs","copilot-cli","hooks.json")}function LN(t){return tr(tf(t,"utf-8"))??{}}function zN(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function nu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?ws(ov(),t.replace(/^~[/\\]?/,"")):iv(t):ws(ov(),".copilot")}function tu(){return ws(nu(),"mcp-config.json")}var MN,nf,cv=x(()=>{"use strict";eu();lt();Vi();tv();MN="CONTEXT_MODE_COPILOT_PLUGIN";nf=class extends Or{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:$t,HOOK_SCRIPTS:ef,buildHookCommand:ev};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return ws(nu(),"hooks","context-mode.json")}getConfigDir(e){return nu()}getSessionDir(){let e=bt(),n=e?ws(e,"context-mode","sessions"):ws(this.getConfigDir(),"context-mode","sessions");return rv(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();rv(DN(n),{recursive:!0}),NN(n,JSON.stringify(e,null,2)+`
|
|
173
|
+
`,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=tf(this.getSettingsPath(),"utf-8");return tr(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=sv(),o=r?jN(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=LN(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values($t)){let l=zN(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(sv())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=tf(tu(),"utf-8");return"context-mode"in((tr(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${tu()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return nv(tu())||nv(this.getSettingsPath())?"standalone":"not installed"}}});function Gi(t,e){let n=rf[e],r=cn(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function cn(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ke,rf,HN,UN,of,uv,lv,dv=x(()=>{"use strict";ke={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},rf={[ke.PRE_TOOL_USE]:"pretooluse.mjs",[ke.POST_TOOL_USE]:"posttooluse.mjs",[ke.SESSION_START]:"sessionstart.mjs",[ke.STOP]:"stop.mjs",[ke.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},HN="MCP:(?!ctx_)",UN=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",HN],of=UN.join("|"),uv=[ke.PRE_TOOL_USE],lv=[ke.POST_TOOL_USE]});var gv={};_e(gv,{CursorAdapter:()=>sf});import{readFileSync as ru,writeFileSync as FN,mkdirSync as BN,accessSync as pv,chmodSync as ZN,constants as fv,existsSync as mv,readdirSync as qN}from"node:fs";import{execSync as VN}from"node:child_process";import{resolve as po,join as fo}from"node:path";import{homedir as ou}from"node:os";var hv,sf,yv=x(()=>{"use strict";lt();Pr();dv();hv="/Library/Application Support/Cursor/hooks.json",sf=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return po(".cursor","hooks.json")}getConfigDir(e){return po(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ke.PRE_TOOL_USE]:[{type:"command",command:cn(ke.PRE_TOOL_USE),matcher:of,loop_limit:null,failClosed:!1}],[ke.POST_TOOL_USE]:[{type:"command",command:cn(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ke.SESSION_START]:[{type:"command",command:cn(ke.SESSION_START),loop_limit:null,failClosed:!1}],[ke.STOP]:[{type:"command",command:cn(ke.STOP),loop_limit:null,failClosed:!1}],[ke.AFTER_AGENT_RESPONSE]:[{type:"command",command:cn(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=ru(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();BN(po(".cursor"),{recursive:!0}),FN(n,JSON.stringify(e,null,2)+`
|
|
174
|
+
`,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of uv){let a=s[i],c=Array.isArray(a)&&a.some(u=>Gi(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of lv){let a=s[i],c=Array.isArray(a)&&a.some(u=>Gi(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}mv(hv)&&n.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()&&n.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&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Gi(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.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"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[fo(ou(),".cursor","plugins","local"),fo(ou(),".cursor","plugins","cache")],n=[];for(let r of e){try{pv(r,fv.F_OK)}catch{continue}let o=[];try{o=qN(r)}catch{continue}for(let s of o){let i=fo(r,s,".cursor-plugin","plugin.json");try{let a=ru(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[po(".cursor","mcp.json"),fo(ou(),".cursor","mcp.json")];for(let r of e)try{let o=ru(r,"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 ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return VN("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ke.PRE_TOOL_USE,{type:"command",command:cn(ke.PRE_TOOL_USE),matcher:of,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.POST_TOOL_USE,{type:"command",command:cn(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.SESSION_START,{type:"command",command:cn(ke.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.STOP,{type:"command",command:cn(ke.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.AFTER_AGENT_RESPONSE,{type:"command",command:cn(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=fo(e,"hooks","cursor");for(let o of Object.values(rf)){let s=po(r,o);try{pv(s,fv.R_OK),ZN(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),fo(ou(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(hv),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 n=ru(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[po(".claude","settings.json"),po(".claude","settings.local.json"),fo(Ze(),"settings.json")].some(n=>mv(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Gi(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var bv={};_e(bv,{AntigravityAdapter:()=>Ji});import{readFileSync as su,writeFileSync as WN,mkdirSync as KN}from"node:fs";import{resolve as iu,dirname as _v}from"node:path";import{fileURLToPath as GN}from"node:url";import{homedir as af}from"node:os";var Ji,cf=x(()=>{"use strict";lt();Ji=class extends ve{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 iu(af(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return iu(af(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=su(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();KN(_v(n),{recursive:!0}),WN(n,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=su(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=iu(af(),".gemini","extensions","context-mode","package.json");return JSON.parse(su(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=iu(_v(GN(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return su(e,"utf-8")}catch{return`# context-mode
|
|
175
175
|
|
|
176
|
-
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
|
|
177
|
-
`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=
|
|
176
|
+
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 Pv={};_e(Pv,{AntigravityCliAdapter:()=>mf,antigravityCliConfigDir:()=>Tv,antigravityCliHooksPath:()=>lf,antigravityCliMcpConfigPath:()=>Ev,antigravityCliPluginDir:()=>uu});import{mkdirSync as JN,readFileSync as au,writeFileSync as XN}from"node:fs";import{dirname as YN,resolve as mo}from"node:path";import{homedir as cu}from"node:os";function Ev(){return mo(cu(),".gemini","config","mcp_config.json")}function Tv(){return mo(cu(),".gemini","antigravity-cli")}function lf(){return mo(cu(),".gemini","config","hooks.json")}function uu(){return mo(cu(),".gemini","config","plugins","context-mode")}function QN(){return mo(uu(),"mcp_config.json")}function eD(){return mo(uu(),"hooks.json")}function xv(t){for(let e of t)try{if("context-mode"in((tr(au(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function Ln(t){return t&&typeof t=="object"?t:{}}function Sv(t){let e=Ln(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function vv(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function $v(t,e){let n=Ln(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>Ln(o).command===e)}function kv(t,e){return JSON.stringify(t).includes(e)}function tD(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function wv(t,e){return Array.isArray(t)&&t.some(n=>$v(n,e))}function nD(t){return Array.isArray(t)&&t.some(e=>{let n=Ln(e);return tD(n.matcher)&&$v(e,df)})}function rD(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(tr(au(n,"utf-8"))??{}).hooks??{},s=nD(o.PreToolUse),i=wv(o.PostToolUse,pf),a=wv(o.Stop,ff);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function sD(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function uf(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!kv(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!kv(a,r)),n],!0)}var df,oD,pf,ff,mf,Rv=x(()=>{"use strict";cf();Vi();df="context-mode hook antigravity-cli pretooluse",oD="run_command|view_file|grep_search|web_fetch|read_url_content",pf="context-mode hook antigravity-cli posttooluse",ff="context-mode hook antigravity-cli stop";mf=class extends Ji{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return Ev()}getConfigDir(e){return Tv()}parsePreToolUseInput(e){let n=Ln(e),r=Ln(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:Ln(r.args),sessionId:vv(n),projectDir:Sv(n),raw:e}}parsePostToolUseInput(e){let n=Ln(e),r=Ln(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:Ln(r.args),toolOutput:o,isError:o.length>0,sessionId:vv(n),projectDir:Sv(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:sD(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=xv([QN(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=tr(au(mo(uu(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return xv([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=lf(),o={};try{o=tr(au(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:oD,hooks:[{type:"command",command:df}]},a={matcher:"",hooks:[{type:"command",command:pf}]},c={matcher:"",hooks:[{type:"command",command:ff}]},u=uf(s,"PreToolUse",i,df),l=uf(s,"PostToolUse",a,pf),d=uf(s,"Stop",c,ff);return(u||l||d)&&(o.hooks=s,JN(YN(r),{recursive:!0}),XN(r,JSON.stringify(o,null,2)+`
|
|
177
|
+
`,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=rD([eD(),lf()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function lu(t,e){let n=Cv[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function Es(t,e){let n=Cv[t];return e&&n?We(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var He,Cv,iD,aD,hf,hG,gG,Ov=x(()=>{"use strict";Nn();He={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Cv={[He.PRE_TOOL_USE]:"pretooluse.mjs",[He.POST_TOOL_USE]:"posttooluse.mjs",[He.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[He.AGENT_SPAWN]:"agentspawn.mjs"},iD="@(?!context-mode/)",aD=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",iD],hf=aD.join("|"),hG=[He.PRE_TOOL_USE,He.AGENT_SPAWN],gG=[He.POST_TOOL_USE,He.USER_PROMPT_SUBMIT]});var Dv={};_e(Dv,{KiroAdapter:()=>gf});import{readFileSync as Ts,writeFileSync as Iv,mkdirSync as Av}from"node:fs";import{resolve as ho,dirname as Nv}from"node:path";import{fileURLToPath as cD}from"node:url";import{homedir as du}from"node:os";var gf,Mv=x(()=>{"use strict";lt();Ov();gf=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.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 ho(du(),".kiro","settings","mcp.json")}getConfigDir(e){return ho(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[He.PRE_TOOL_USE]:[{matcher:hf,hooks:[{type:"command",command:Es(He.PRE_TOOL_USE,e)}]}],[He.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Es(He.POST_TOOL_USE,e)}]}],[He.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Es(He.AGENT_SPAWN,e)}]}],[He.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Es(He.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Ts(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();Av(Nv(n),{recursive:!0}),Iv(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=ho(du(),".kiro","agents","default.json");try{let s=JSON.parse(Ts(r,"utf-8")).hooks??{};for(let i of[He.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>lu(u,i));n.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=>lu(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=Ts(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=ho(du(),".kiro","extensions","context-mode","package.json");return JSON.parse(Ts(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=ho(du(),".kiro","agents"),o=ho(r,"default.json");try{Av(r,{recursive:!0});let s={};try{s=JSON.parse(Ts(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[He.PRE_TOOL_USE,hf],[He.POST_TOOL_USE,"*"],[He.AGENT_SPAWN,"*"],[He.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>lu(d,c))||(l.push({matcher:u,command:Es(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,Iv(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=ho(Nv(cD(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Ts(e,"utf-8")}catch{return`# context-mode
|
|
178
178
|
|
|
179
|
-
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
|
|
179
|
+
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 zv={};_e(zv,{ZedAdapter:()=>_f});import{readFileSync as yf,writeFileSync as uD,mkdirSync as lD}from"node:fs";import{resolve as jv,dirname as Lv}from"node:path";import{fileURLToPath as dD}from"node:url";import{homedir as pD}from"node:os";var _f,Hv=x(()=>{"use strict";lt();_f=class extends ve{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 jv(pD(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=yf(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();lD(Lv(n),{recursive:!0}),uD(n,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=yf(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{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,n){}getRoutingInstructions(){let e=jv(Lv(dD(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return yf(e,"utf-8")}catch{return`# context-mode
|
|
180
180
|
|
|
181
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
181
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var bf,Uv=x(()=>{"use strict";bf="mcp__(?!.*context-mode)"});var Zv={};_e(Zv,{QwenCodeAdapter:()=>xf});import{readFileSync as fD,writeFileSync as mD,existsSync as hD}from"node:fs";import{resolve as Fv,join as gD}from"node:path";import{homedir as Bv}from"node:os";var xf,qv=x(()=>{"use strict";$p();Uv();Nn();xf=class extends bs{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 Fv(Bv(),".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",bf].join("|"),hooks:[{type:"command",command:We(`${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:We(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:We(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=fD(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){mD(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.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 n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.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 n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(f=>f.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(f.command))?p.every(f=>{if(!f.command)return!0;let h=f.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=f.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?hD(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[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",bf].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:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:We(`${e}/hooks/${a}`)}]},l=r[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(f=>f.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:Fv(gD(Bv(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Vv={};_e(Vv,{OMPAdapter:()=>kf});import{readFileSync as Sf,writeFileSync as yD,mkdirSync as _D}from"node:fs";import{resolve as vf,dirname as bD}from"node:path";import{homedir as xD}from"node:os";var kf,Wv=x(()=>{"use strict";lt();kf=class extends ve{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??vf(xD(),".omp","agent")}getSettingsPath(){return vf(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Sf(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();_D(bD(n),{recursive:!0}),yD(n,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=Sf(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=vf(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Sf(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
182
182
|
|
|
183
|
-
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
|
|
183
|
+
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 Kv={};_e(Kv,{PiAdapter:()=>$f});import{readFileSync as wf,writeFileSync as SD,mkdirSync as vD}from"node:fs";import{resolve as Ef,dirname as kD}from"node:path";import{homedir as Tf}from"node:os";var $f,Gv=x(()=>{"use strict";lt();$f=class extends ve{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 Ef(Tf(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=wf(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();vD(kD(n),{recursive:!0}),SD(n,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=Ef(Tf(),".pi","extensions","context-mode","package.json");try{return JSON.parse(wf(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=Ef(Tf(),".pi","extensions","context-mode","package.json");return JSON.parse(wf(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
|
|
184
184
|
|
|
185
|
-
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
|
|
186
|
-
`)}function
|
|
185
|
+
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 Jv}from"node:os";import{resolve as Pf,join as KG}from"node:path";function Xv(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Pf(Jv(),t.replace(/^~[/\\]?/,"")):Pf(t):Pf(Jv(),".kimi-code")}var Yv=x(()=>{"use strict"});var rk={};_e(rk,{KimiAdapter:()=>Cf,probeKimiCliVersion:()=>nk});import{execFileSync as wD}from"node:child_process";import{readFileSync as Xi,writeFileSync as ED,accessSync as TD,copyFileSync as $D,constants as PD,mkdirSync as Qv}from"node:fs";import{resolve as RD,dirname as ek,join as go}from"node:path";import{fileURLToPath as CD}from"node:url";function nk(t=wD){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function tk(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)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?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function AD(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(`
|
|
186
|
+
`)}function Rf(t){return t.command.includes("context-mode hook kimi")}function ND(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var OD,Ir,ID,Cf,ok=x(()=>{"use strict";lt();rn();Yv();OD="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Ir={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"},ID={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"]};Cf=class extends ve{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Xv()}getSettingsPath(){return go(this.getConfigDir(),"config.toml")}getMcpPath(){return go(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=bt(),n=e?go(e,"context-mode","sessions"):go(this.getConfigDir(),"context-mode","sessions");return Qv(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=bt(),r=n?go(n,"context-mode","memory"):go(this.getConfigDir(),"memory");return e?go(r,st(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:OD,hooks:[{type:"command",command:Ir.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Ir.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ir.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:Ir.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ir.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ir.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Ir.Stop}]}]}}readSettings(){try{return{_raw_toml:Xi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=nk();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=Xi(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=tk(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";n.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&&Rf(u)).length;c>1&&n.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 n}checkPluginRegistration(){try{let e=Xi(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&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 n=[],r=this.generateHookConfig(""),o="";try{o=Xi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=tk(o),i=s.filter(l=>!Rf(l)),a=[];for(let[l,d]of Object.entries(r)){let p=ND(l,d[0]);p&&a.push(p)}let c=s.some(Rf),u=this.rebuildToml(o,i,a);return u!==o&&(Qv(ek(this.getSettingsPath()),{recursive:!0}),ED(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{TD(n,PD.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=RD(ek(CD(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Xi(e,"utf-8")}catch{return`# context-mode
|
|
187
187
|
|
|
188
|
-
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,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return
|
|
189
|
-
`)}}});var Pf={};_e(Pf,{PLATFORM_ENV_VARS:()=>$s,__resetClaudeCodePluginCacheForTests:()=>ND,__seedClaudeCodePluginCacheMissForTests:()=>DD,detectPlatform:()=>et,foreignIdentificationEnv:()=>zD,foreignWorkspaceEnv:()=>LD,getAdapter:()=>Ji,getEnvVarNames:()=>jD,getSessionDirSegments:()=>Gi,workspaceEnvVarsFor:()=>$f});import{existsSync as Qe,readFileSync as ID}from"node:fs";import{resolve as He}from"node:path";import{homedir as ok}from"node:os";function AD(){if(yo!==null)return yo!=="miss"&&yo.hasCM;try{let t=He(ok(),".claude","plugins","installed_plugins.json"),e=ID(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return yo={hasCM:o},o}catch{return yo="miss",!1}}function ND(){yo=null}function DD(){yo="miss"}function jD(t){return($s.get(t)??[]).map(e=>e.name)}function $f(t){return($s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function LD(t){let e=new Set;for(let[n,r]of $s)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function zD(t){let e=new Set;for(let[n,r]of $s)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Gi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];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 et(t){if(t?.name){let s=Ax[t.name];if(s)return{platform:s,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of $s)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&AD()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=ok(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?He(n,s.replace(/^~[/\\]?/,"")):He(s):He(n,".copilot")})(),o=Qe(He(r,"mcp-config.json"))||Qe(He(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Qe(He(n,".local","bin","agy"))||Qe(He(n,".gemini","antigravity-cli"))||Qe(He(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Qe(He(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Qe(He(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Qe(He(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Qe(He(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Qe(He(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Qe(He(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Qe(He(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Qe(He(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Qe(He(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Qe(He(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Qe(He(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Qe(He(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Qe(He(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Qe(He(n,".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 Ji(t){let e=t??et().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Op(),Cp));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(xS(),bS));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(PS(),$S));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(OS(),CS));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Bp(),FS));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(KS(),WS));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(YS(),XS));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(av(),iv));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(gv(),hv));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(rf(),_v));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(Pv(),$v));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(Dv(),Nv));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(zv(),Lv));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(Zv(),Bv));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(Vv(),qv));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(Kv(),Wv));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(rk(),nk));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Op(),Cp));return new n}}}var yo,MD,$s,_o=x(()=>{"use strict";Nx();yo=null;MD=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]]],$s=new Map(MD)});import{resolve as Xi}from"node:path";import{homedir as Rf}from"node:os";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Xi(Rf(),e.replace(/^~[/\\]?/,"")):Xi(e):Xi(Rf(),".claude")}function HD(t=process.env){return Xi(Be(t),"settings.json")}function Cf(t=process.env){let e=[],n=et();if(n.platform!=="claude-code"){let o=Gi(n.platform);o&&o.length>0&&e.push(Xi(Rf(),...o,"settings.json"))}let r=HD(t);return e.includes(r)||e.push(r),e}var Rr=x(()=>{"use strict";_o()});import{readdirSync as UD,statSync as FD,lstatSync as BD,realpathSync as sk,existsSync as ZD,readFileSync as qD}from"node:fs";import{join as ak,extname as VD,relative as ck,sep as WD,resolve as KD}from"node:path";function QD(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function ik(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=QD(r);if(o.test(t)||o.test(n))return!0}return!1}function eM(t){let e=ak(t,".gitignore");if(!ZD(e))return[];try{return qD(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function tM(t,e){return ck(t,e).split(WD).join("/")}function uk(t,e={}){let{include:n,exclude:r,maxDepth:o=XD,maxFiles:s=YD,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=sk(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:JD).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...GD,...r??[],...a?eM(u):[]],p=n??[],m=[],f=new Set([u]),h=0,g=!1;function y(_,b){if(g||b>o)return;let S;try{S=UD(_,{withFileTypes:!0})}catch{return}for(let T of S){if(g)return;let D=ak(_,T.name),v=tM(u,D);if(ik(v,d))continue;let $=T.isDirectory(),P=T.isFile(),A=!1;try{A=BD(D).isSymbolicLink()}catch{continue}if(A){if(!c)continue;let C;try{C=sk(D)}catch{continue}let z=ck(u,C);if((z.startsWith("..")||KD(z)===C)&&z.startsWith("..")||f.has(C))continue;f.add(C);try{let B=FD(C);$=B.isDirectory(),P=B.isFile()}catch{continue}}if($){y(D,b+1);continue}if(!P)continue;let R=VD(D).toLowerCase();if(l.includes(R)&&!(p.length>0&&!ik(v,p))){if(h++,m.length>=s){g=!0;return}m.push(D)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var GD,JD,XD,YD,lk=x(()=>{"use strict";GD=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],JD=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],XD=5,YD=200});import{readFileSync as dk,readdirSync as yk,unlinkSync as If,existsSync as Of,statSync as lu,openSync as pk,fstatSync as fk,closeSync as mk}from"node:fs";import{createHash as hk}from"node:crypto";import{tmpdir as _k}from"node:os";import{join as Af}from"node:path";function bk(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function nM(t,e="AND"){let n=bk(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!Ps.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function rM(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=bk(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!Ps.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function oM(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function sM(t){return t<=4?1:t<=12?2:3}function Nf(){let t=_k(),e=0;try{let n=yk(t);for(let r of n){let o=r.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=Af(t,r);for(let a of["","-wal","-shm"])try{If(i+a)}catch{}e++}}}catch{}return e}function Df(t,e){let n=0;try{if(!Of(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=yk(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Af(t,s),c=lu(i).mtimeMs<r;if(!c){let u=i+"-wal";if(Of(u))try{let l=lu(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{If(i+u)}catch{}n++}}catch{}}catch{}return n}function lM(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function dM(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=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+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(r++,u++)}}return r}function pM(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var Ps,uu,iM,aM,cM,gk,uM,Rs,Mf=x(()=>{"use strict";er();lk();Ps=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"]);uu=4096,iM=3,aM=200,cM=5e3,gk=80,uM=.5;Rs=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#b;#x;#S;#v;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=Je();this.#t=e??Af(_k(),`context-mode-${process.pid}.db`),kr(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),vr(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Mc(s)){Dc(this.#t),kr(this.#t);try{r=new n(this.#t,{timeout:3e4}),vr(r)}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=r,this.#B(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{If(this.#t+e)}catch{}}#B(){this.#e.exec(`
|
|
188
|
+
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,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return $D(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(Ir[e]??"").replace(/\\/g,"/"),s=ID[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){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=[...n,...r];if(a.length>0)for(let c of a)s.push(AD(c)),s.push("");return s.join(`
|
|
189
|
+
`)}}});var If={};_e(If,{PLATFORM_ENV_VARS:()=>$s,__resetClaudeCodePluginCacheForTests:()=>jD,__seedClaudeCodePluginCacheMissForTests:()=>LD,detectPlatform:()=>tt,foreignIdentificationEnv:()=>FD,foreignWorkspaceEnv:()=>UD,getAdapter:()=>Qi,getEnvVarNames:()=>HD,getSessionDirSegments:()=>Yi,workspaceEnvVarsFor:()=>Of});import{existsSync as et,readFileSync as DD}from"node:fs";import{resolve as Ue}from"node:path";import{homedir as sk}from"node:os";function MD(){if(yo!==null)return yo!=="miss"&&yo.hasCM;try{let t=Ue(sk(),".claude","plugins","installed_plugins.json"),e=DD(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return yo={hasCM:o},o}catch{return yo="miss",!1}}function jD(){yo=null}function LD(){yo="miss"}function HD(t){return($s.get(t)??[]).map(e=>e.name)}function Of(t){return($s.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function UD(t){let e=new Set;for(let[n,r]of $s)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function FD(t){let e=new Set;for(let[n,r]of $s)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Yi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];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 tt(t){if(t?.name){let s=Dx[t.name];if(s)return{platform:s,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of $s)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&MD()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=sk(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Ue(n,s.replace(/^~[/\\]?/,"")):Ue(s):Ue(n,".copilot")})(),o=et(Ue(r,"mcp-config.json"))||et(Ue(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:et(Ue(n,".local","bin","agy"))||et(Ue(n,".gemini","antigravity-cli"))||et(Ue(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:et(Ue(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:et(Ue(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:et(Ue(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:et(Ue(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:et(Ue(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:et(Ue(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:et(Ue(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:et(Ue(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:et(Ue(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:et(Ue(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:et(Ue(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:et(Ue(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:et(Ue(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:et(Ue(n,".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 Qi(t){let e=t??tt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Dp(),Np));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(SS(),xS));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(RS(),PS));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(IS(),OS));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Wp(),BS));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(GS(),KS));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(QS(),YS));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(cv(),av));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(yv(),gv));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(cf(),bv));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(Rv(),Pv));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(Mv(),Dv));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(Hv(),zv));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(qv(),Zv));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(Wv(),Vv));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(Gv(),Kv));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(ok(),rk));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Dp(),Np));return new n}}}var yo,zD,$s,_o=x(()=>{"use strict";Mx();yo=null;zD=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]]],$s=new Map(zD)});import{resolve as ea}from"node:path";import{homedir as Af}from"node:os";function Ze(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?ea(Af(),e.replace(/^~[/\\]?/,"")):ea(e):ea(Af(),".claude")}function BD(t=process.env){return ea(Ze(t),"settings.json")}function Nf(t=process.env){let e=[],n=tt();if(n.platform!=="claude-code"){let o=Yi(n.platform);o&&o.length>0&&e.push(ea(Af(),...o,"settings.json"))}let r=BD(t);return e.includes(r)||e.push(r),e}var Pr=x(()=>{"use strict";_o()});import{readdirSync as ZD,statSync as qD,lstatSync as VD,realpathSync as ik,existsSync as WD,readFileSync as KD}from"node:fs";import{join as ck,extname as GD,relative as uk,sep as JD,resolve as XD}from"node:path";function nM(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function ak(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=nM(r);if(o.test(t)||o.test(n))return!0}return!1}function rM(t){let e=ck(t,".gitignore");if(!WD(e))return[];try{return KD(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function oM(t,e){return uk(t,e).split(JD).join("/")}function lk(t,e={}){let{include:n,exclude:r,maxDepth:o=eM,maxFiles:s=tM,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=ik(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:QD).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...YD,...r??[],...a?rM(u):[]],p=n??[],m=[],f=new Set([u]),h=0,g=!1;function y(_,b){if(g||b>o)return;let S;try{S=ZD(_,{withFileTypes:!0})}catch{return}for(let T of S){if(g)return;let D=ck(_,T.name),v=oM(u,D);if(ak(v,d))continue;let $=T.isDirectory(),P=T.isFile(),A=!1;try{A=VD(D).isSymbolicLink()}catch{continue}if(A){if(!c)continue;let C;try{C=ik(D)}catch{continue}let z=uk(u,C);if((z.startsWith("..")||XD(z)===C)&&z.startsWith("..")||f.has(C))continue;f.add(C);try{let B=qD(C);$=B.isDirectory(),P=B.isFile()}catch{continue}}if($){y(D,b+1);continue}if(!P)continue;let R=GD(D).toLowerCase();if(l.includes(R)&&!(p.length>0&&!ak(v,p))){if(h++,m.length>=s){g=!0;return}m.push(D)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var YD,QD,eM,tM,dk=x(()=>{"use strict";YD=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],QD=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],eM=5,tM=200});import{readFileSync as pk,readdirSync as _k,unlinkSync as Df,existsSync as bk,statSync as fu,openSync as fk,fstatSync as mk,closeSync as hk}from"node:fs";import{createHash as gk}from"node:crypto";import{tmpdir as xk}from"node:os";import{join as Mf}from"node:path";function Sk(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function sM(t,e="AND"){let n=Sk(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!Ps.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function iM(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=Sk(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!Ps.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function aM(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function cM(t){return t<=4?1:t<=12?2:3}function jf(){let t=xk(),e=0;try{let n=_k(t);for(let r of n){let o=r.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=Mf(t,r);for(let a of["","-wal","-shm"])try{Df(i+a)}catch{}e++}}}catch{}return e}function vk(t,e){let n=0;try{if(!bk(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=_k(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Mf(t,s),a=fu(i).mtimeMs;try{let c=fu(i+"-wal");c.size>0&&c.mtimeMs>a&&(a=c.mtimeMs)}catch{}if(a<r){for(let c of["","-wal","-shm"])try{Df(i+c)}catch{}n++}}catch{}}catch{}return n}function fM(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function mM(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=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+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(r++,u++)}}return r}function hM(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}function wk(t){try{return typeof t=="object"&&t!==null&&t[kk]===!0}catch{return!1}}function at(t,e,n,r){if(wk(e))return e;ot(t,e,n);let o=Li(e),s=ps(e),i=s?` (${s})`:"",a=new Error(`${gM} ${t} failed on ${n}: ${r??o}${i}`);return s&&(a.code=s),Object.defineProperty(a,kk,{value:!0,enumerable:!1}),a}var Ps,pu,uM,lM,dM,yk,pM,gM,kk,Rs,Lf=x(()=>{"use strict";er();dk();Ps=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"]);pu=4096,uM=3,lM=200,dM=5e3,yk=80,pM=.5;gM="[context-mode:store]",kk=Symbol.for("__context_mode_db_error_logged__");Rs=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#b;#x;#S;#v;#k;#w;#E;#T;#$;#P;#R;#C;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=Xe();this.#t=e??Mf(xk(),`context-mode-${process.pid}.db`),vr(this.#t);let r=()=>{let s=new n(this.#t,{timeout:3e4});return so(s),s},o;try{o=ze(r)}catch(s){let i=s instanceof Error?s.message:String(s);if(Lc(i)){ot("store.open",s,this.#t),jc(this.#t),vr(this.#t);try{o=ze(r)}catch(a){throw at("store.open",a,this.#t,`Failed to create fresh DB after deleting corrupt file: ${Li(a)}`)}}else throw at("store.open",s,this.#t)}this.#e=o;try{this.#B(),this.#Z()}catch(s){throw at("store.initSchema",s,this.#t)}}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Df(this.#t+e)}catch{}}#B(){this.#e.exec(`
|
|
190
190
|
CREATE TABLE IF NOT EXISTS sources (
|
|
191
191
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
192
192
|
label TEXT NOT NULL,
|
|
@@ -438,7 +438,7 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
438
438
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
439
439
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
440
440
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
441
|
-
`),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=
|
|
441
|
+
`),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let p=fk(r,"r");try{if(!mk(p).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=pk(p,"utf-8")}finally{hk(p)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?gk("sha256").update(a).digest("hex"):void 0;try{return ze(()=>this.#d(u,c,a,l,d,s))}catch(p){throw at("store.index",p,this.#t)}}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=lk(n,i),c=0,u=0,l=0,d=0;for(let p of a.files){if(s&&s(p)){l++;continue}try{let m=r?`${r}:${p}`:p,f=this.index({path:p,source:m,attribution:o});c++,u+=f.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:r??n}}indexPlainText(e,n,r=20,o,s=pu){if(!e||e.trim().length===0)try{return ze(()=>this.#d([],n,"",void 0,void 0,o))}catch(a){throw at("store.indexPlainText",a,this.#t)}let i=this.#J(e,r,s);try{return ze(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}catch(a){throw at("store.indexPlainText",a,this.#t)}}indexJSON(e,n,r=pu,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];if(this.#F(s,[],i,r),i.length===0)return this.indexPlainText(e,n,void 0,o,r);try{return ze(()=>this.#d(i,n,e,void 0,void 0,o))}catch(a){throw at("store.indexJSON",a,this.#t)}}#d(e,n,r,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(n),this.#l.run(n),this.#m.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let p=this.#s.run(n,e.length,a,o??null,s??null),m=Number(p.lastInsertRowid),f=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,m,g,null,c,u,f),this.#c.run(h.title,h.content,m,g,null,c,u,f)}return m})();return r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=sM(e,o),c,u;r&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#v,u=[a,s,n]):(c=this.#h,u=[a,n]);try{return ze(()=>this.#L(c.all(...u)))}catch(l){throw at("store.search",l,this.#t)}}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=iM(e,o);if(!a)return[];let c,u;r&&s?(c=i==="exact"?this.#$:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#b,u=[a,this.#p(r,i),n]):s?(c=this.#E,u=[a,s,n]):(c=this.#_,u=[a,n]);try{return ze(()=>this.#L(c.all(...u)))}catch(l){throw at("store.searchTrigram",l,this.#t)}}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=cM(n.length),o;try{o=ze(()=>this.#S.all(n.length-r,n.length+r))}catch(u){throw at("store.fuzzyCorrect",u,this.#t)}let s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=aM(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?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(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,m]of c.entries()){let f=d(m),h=l.get(f);h?h.score+=1/(60+p+1):l.set(f,{result:m,score:1/(60+p+1)})}for(let[p,m]of u.entries()){let f=d(m),h=l.get(f);h?h.score+=1/(60+p+1):l.set(f,{result:m,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,m)=>m.score-p.score).slice(0,n).map(({result:p,score:m})=>({...p,rank:-m}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!Ps.has(i)),s=o.length>0?o:r;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(m=>a.includes(m)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let m=i.content.toLowerCase(),f=s.map(h=>fM(m,h));if(!f.some(h=>h.length===0)){d=1/(1+hM(f)/Math.max(m.length,1));let g=mM(f,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,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!Ps.has(h)),p=d.join(" "),f=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(f!==p){let h=this.#z(f,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),f).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e;try{e=ze(()=>this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all())}catch(n){throw at("store.refreshStaleSources",n,this.#t)}for(let n of e)try{if(!bk(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=fu(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=fk(n.file_path,"r"),i;try{if(!mk(s).isFile())continue;i=pk(s,"utf-8")}finally{hk(s)}if(gk("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch(r){wk(r)||ot("store.refreshStaleSources",r,this.#t)}}getSourceMeta(e){let n;try{n=ze(()=>this.#A.get(e))}catch(r){throw at("store.getSourceMeta",r,this.#t)}return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){try{return ze(()=>this.#P.all())}catch(e){throw at("store.listSources",e,this.#t)}}getIndexState(){let e;try{e=ze(()=>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())}catch(n){throw at("store.getIndexState",n,this.#t)}return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){let n;try{n=ze(()=>this.#R.all(e))}catch(r){throw at("store.getChunksBySource",r,this.#t)}return n.map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r;try{r=ze(()=>this.#C.get(e))}catch(d){throw at("store.getDistinctiveTerms",d,this.#t)}if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=()=>{let d=new Map;for(let p of this.#O.iterate(e)){let m=new Set(p.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!Ps.has(f)));for(let f of m)d.set(f,(d.get(f)??0)+1)}return d},c;try{c=ze(a)}catch(d){throw at("store.getDistinctiveTerms",d,this.#t)}return Array.from(c.entries()).filter(([,d])=>d>=s&&d<=i).map(([d,p])=>{let m=Math.log(o/p),f=Math.min(d.length/20,.5),h=/[_]/.test(d),g=d.length>=12,y=h?1.5:g?.8:0;return{word:d,score:m+f+y}}).sort((d,p)=>p.score-d.score).slice(0,n).map(d=>d.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){let n=this.#e.transaction(r=>(this.#N.run(r),this.#D.run(r),this.#M.run(r)));try{return ze(()=>n(e)).changes}catch(r){throw at("store.cleanupStaleSources",r,this.#t)}}getDBSizeBytes(){try{return fu(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch(e){ot("store.optimizeFTS",e,this.#t)}}close(){this.#U(),ds(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Ps.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=pu){let r=[],o=e.split(`
|
|
442
442
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
443
443
|
`).trim();if(l.length===0)return;let d=this.#ee(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.push({title:d,content:l,hasCode:p}),i=[];return}let m=l.split(/\n\n+/),f=[],h=1,g=()=>{if(f.length===0)return;let y=f.join(`
|
|
444
444
|
|
|
@@ -446,20 +446,20 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
446
446
|
|
|
447
447
|
`);Buffer.byteLength(_)>n&&f.length>1&&(f.pop(),g(),f=[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 m=d[1].length,f=d[2].trim();for(;s.length>0&&s[s.length-1].level>=m;)s.pop();s.push({level:m,text:f}),a=f,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let m=p[1],f=[l];for(u++;u<o.length;){if(f.push(o[u]),o[u].startsWith(m)&&o[u].trim()===m){u++;break}u++}i.push(...f);continue}i.push(l),u++}return c(),r}#G(e,n){if(Buffer.byteLength(e)<=n)return e;let r="",o=0;for(let s of e){let i=Buffer.byteLength(s);if(o+i>n)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#f(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(`
|
|
448
448
|
`),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let p=this.#G(l,r);if(p.length<l.length){let f=p.lastIndexOf(" "),h=p.lastIndexOf(`
|
|
449
|
-
`),g=Math.max(f,h);g>p.length*
|
|
449
|
+
`),g=Math.max(f,h);g>p.length*pM&&(p=p.slice(0,g))}let m=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:m,content:p}),l=l.slice(p.length),d++,i++}continue}let u=s.length>0?s.join(`
|
|
450
450
|
`)+`
|
|
451
|
-
`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=
|
|
452
|
-
`)[0].slice(0,
|
|
451
|
+
`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=pu){let o=e.split(/\n\s*\n/);if(o.length>=uM&&o.length<=lM&&o.every(u=>Buffer.byteLength(u)<dM))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let p=d.split(`
|
|
452
|
+
`)[0].slice(0,yk)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:p,content:d}]:this.#f(d.split(`
|
|
453
453
|
`),p,r)});let s=e.split(`
|
|
454
|
-
`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#f(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,p=Math.min(u+l.length,s.length),m=l[0]?.trim().slice(0,
|
|
455
|
-
`);if(Buffer.byteLength(f)<=r)i.push({title:m||`Lines ${d}-${p}`,content:f});else{let h=this.#f(l,m||`Lines ${d}-${p}`,r);i.push(...h)}}return i}#F(e,n,r,o){let s=n.length>0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.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)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as
|
|
456
|
-
`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function
|
|
457
|
-
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function
|
|
458
|
-
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function
|
|
459
|
-
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function
|
|
460
|
-
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function HM({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!sr(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=Cs(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}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=wt(n),c=a+So,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 m=p.replace(/\\/g,"/");if(!m.startsWith(i+"/"))continue;let f=m.slice(i.length+1),h=f.indexOf("/");if(h<0)continue;let g=f.slice(h+1),y=wt(n,g);y!==a&&!(y+So).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{Qi(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 pu({pluginCacheRoot:t,pluginKey:e}){let n=[];if(!t||!e)return{removed:n,skipped:"missing-args"};let r=wt(t);if(!sr(r))return{removed:n,skipped:"no-cache-root"};let o=Bf(e);if(!o)return{removed:n,skipped:"bad-plugin-key"};let s=o.id,i=o.pkg;if(!s||!i)return{removed:n,skipped:"bad-plugin-key"};let a=wt(r,s,i),c=r+So;if(!a.startsWith(c))return{removed:n,skipped:"outside-cache-root"};if(!sr(a))return{removed:n,skipped:"no-plugin-dir"};let u=[];try{u=AM(a)}catch{return{removed:n,skipped:"readdir-failed"}}for(let l of u){let d=wt(a,l);if(!d.startsWith(a+So))continue;try{if(!DM(d).isDirectory())continue}catch{continue}let p=wt(d,".mcp.json");if(sr(p))try{NM(p),n.push(p)}catch{}}return{removed:n}}var Ck,Ok,MM,Yi,Zf=x(()=>{"use strict";Ck="@mxalbert/context-mode",Ok="context-mode",MM=`${Ok}@${Ck}`;Yi="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,qf,H,zn,ea=x(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qf||(qf={}));H=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zn=t=>{switch(typeof t){case"undefined":return H.undefined;case"string":return H.string;case"number":return Number.isNaN(t)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(t)?H.array:t===null?H.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?H.promise:typeof Map<"u"&&t instanceof Map?H.map:typeof Set<"u"&&t instanceof Set?H.set:typeof Date<"u"&&t instanceof Date?H.date:H.object;default:return H.unknown}}});var I,BM,Nt,fu=x(()=>{ea();I=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"]),BM=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Nt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}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=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Nt.create=t=>new Nt(t)});var ZM,ir,Vf=x(()=>{fu();ea();ZM=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===H.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},ir=ZM});function qM(t){Nk=t}function Os(){return Nk}var Nk,mu=x(()=>{Vf();Nk=ir});function M(t,e){let n=Os(),r=ta({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ir?void 0:ir].filter(o=>!!o)});t.common.issues.push(r)}var ta,VM,ct,G,vo,yt,hu,gu,Dr,Is,Wf=x(()=>{mu();Vf();ta=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},VM=[];ct=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),vo=t=>({status:"dirty",value:t}),yt=t=>({status:"valid",value:t}),hu=t=>t.status==="aborted",gu=t=>t.status==="dirty",Dr=t=>t.status==="valid",Is=t=>typeof Promise<"u"&&t instanceof Promise});var Dk=x(()=>{});var Z,Mk=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Z||(Z={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function Hk(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function uj(t){return new RegExp(`^${Hk(t)}$`)}function Uk(t){let e=`${zk}T${Hk(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function lj(t,e){return!!((e==="v4"||!e)&&nj.test(t)||(e==="v6"||!e)&&oj.test(t))}function dj(t,e){if(!YM.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function pj(t,e){return!!((e==="v4"||!e)&&rj.test(t)||(e==="v6"||!e)&&sj.test(t))}function fj(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function As(t){if(t instanceof Mt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Dt.create(As(r))}return new Mt({...t._def,shape:()=>e})}else return t instanceof ur?new ur({...t._def,type:As(t.element)}):t instanceof Dt?Dt.create(As(t.unwrap())):t instanceof Un?Un.create(As(t.unwrap())):t instanceof Hn?Hn.create(t.items.map(e=>As(e))):t}function Gf(t,e){let n=zn(t),r=zn(e);if(t===e)return{valid:!0,data:t};if(n===H.object&&r===H.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=Gf(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===H.array&&r===H.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=Gf(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===H.date&&r===H.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Fk(t,e){return new Ao({values:t,typeName:N.ZodEnum,...te(e)})}function Lk(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Bk(t,e={},n){return t?jr.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Lk(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Lk(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):jr.create()}var an,jk,re,WM,KM,GM,JM,XM,YM,QM,ej,tj,Kf,nj,rj,oj,sj,ij,aj,zk,cj,Mr,ko,wo,Eo,To,Ns,$o,Po,jr,cr,bn,Ds,ur,Mt,Ro,ar,yu,Co,Hn,_u,Ms,js,bu,Oo,Io,Ao,No,Lr,cn,Dt,Un,Do,Mo,Ls,mj,na,ra,jo,hj,N,gj,Zk,qk,yj,_j,Vk,bj,xj,Sj,vj,kj,wj,Ej,Tj,$j,Jf,Pj,Rj,Cj,Oj,Ij,Aj,Nj,Dj,Mj,jj,Lj,zj,Hj,Uj,Fj,Bj,Zj,qj,Vj,Wj,Kj,Gj,Jj,Xj,Wk=x(()=>{fu();mu();Mk();Wf();ea();an=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},jk=(t,e)=>{if(Dr(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 n=new Nt(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return zn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:zn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ct,ctx:{common:e.parent.common,data:e.data,parsedType:zn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Is(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)},o=this._parseSync({data:e,path:r.path,parent:r});return jk(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Dr(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Dr(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Is(o)?o:Promise.resolve(o));return jk(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new cn({schema:this,typeName:N.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:n=>this["~validate"](n)}}optional(){return Dt.create(this,this._def)}nullable(){return Un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ur.create(this)}promise(){return Lr.create(this,this._def)}or(e){return Ro.create([this,e],this._def)}and(e){return Co.create(this,e,this._def)}transform(e){return new cn({...te(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Do({...te(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new na({typeName:N.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Mo({...te(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ra.create(this,e)}readonly(){return jo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},WM=/^c[^\s-]{8,}$/i,KM=/^[0-9a-z]+$/,GM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,JM=/^[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,XM=/^[a-z0-9_-]{21}$/i,YM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QM=/^[-+]?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)?)??$/,ej=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",nj=/^(?:(?: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])$/,rj=/^(?:(?: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])$/,oj=/^(([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]))$/,sj=/^(([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])$/,ij=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zk="((\\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])))",cj=new RegExp(`^${zk}$`);Mr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.string,received:s.parsedType}),G}let r=new ct,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.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?M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")ej.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"email",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Kf||(Kf=new RegExp(tj,"u")),Kf.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"emoji",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")JM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"uuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")XM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"nanoid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")WM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")KM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid2",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")GM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ulid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),M(o,{validation:"url",code:I.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"regex",code:I.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.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),M(o,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Uk(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?cj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?uj(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?QM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"duration",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?lj(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ip",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?dj(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"jwt",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?pj(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cidr",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?ij.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?aj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64url",code:I.invalid_string,message:s.message}),r.dirty()):ce.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:I.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Z.errToObj(n)})}nonempty(e){return this.min(1,Z.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Mr.create=t=>new Mr({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...te(t)});ko=class t extends re{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)!==H.number){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.number,received:s.parsedType}),G}let r,o=new ct;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?fj(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.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,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};ko.create=t=>new ko({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...te(t)});wo=class t extends re{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)!==H.bigint)return this._getInvalidInput(e);let r,o=new ct;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:H.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,Z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.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:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};wo.create=t=>new wo({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...te(t)});Eo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.boolean,received:r.parsedType}),G}return yt(e.data)}};Eo.create=t=>new Eo({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...te(t)});To=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_date}),G}let r=new ct,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Z.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};To.create=t=>new To({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...te(t)});Ns=class extends re{_parse(e){if(this._getType(e)!==H.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.symbol,received:r.parsedType}),G}return yt(e.data)}};Ns.create=t=>new Ns({typeName:N.ZodSymbol,...te(t)});$o=class extends re{_parse(e){if(this._getType(e)!==H.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.undefined,received:r.parsedType}),G}return yt(e.data)}};$o.create=t=>new $o({typeName:N.ZodUndefined,...te(t)});Po=class extends re{_parse(e){if(this._getType(e)!==H.null){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.null,received:r.parsedType}),G}return yt(e.data)}};Po.create=t=>new Po({typeName:N.ZodNull,...te(t)});jr=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return yt(e.data)}};jr.create=t=>new jr({typeName:N.ZodAny,...te(t)});cr=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return yt(e.data)}};cr.create=t=>new cr({typeName:N.ZodUnknown,...te(t)});bn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:H.never,received:n.parsedType}),G}};bn.create=t=>new bn({typeName:N.ZodNever,...te(t)});Ds=class extends re{_parse(e){if(this._getType(e)!==H.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.void,received:r.parsedType}),G}return yt(e.data)}};Ds.create=t=>new Ds({typeName:N.ZodVoid,...te(t)});ur=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==H.array)return M(n,{code:I.invalid_type,expected:H.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(M(n,{code:i?I.too_big:I.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}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(M(n,{code:I.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(M(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new an(n,i,n.path,a)))).then(i=>ct.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new an(n,i,n.path,a)));return ct.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Z.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Z.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Z.toString(n)}})}nonempty(e){return this.min(1,e)}};ur.create=(t,e)=>new ur({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...te(e)});Mt=class t extends re{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(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==H.object){let u=this._getOrReturnCtx(e);return M(u,{code:I.invalid_type,expected:H.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof bn&&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 an(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof bn){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&&(M(o,{code:I.unrecognized_keys,keys:a}),r.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 an(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=>ct.mergeObjectSync(r,u)):ct.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:Z.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:N.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return As(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Dt;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Fk(ce.objectKeys(this.shape))}};Mt.create=(t,e)=>new Mt({shape:()=>t,unknownKeys:"strip",catchall:bn.create(),typeName:N.ZodObject,...te(e)});Mt.strictCreate=(t,e)=>new Mt({shape:()=>t,unknownKeys:"strict",catchall:bn.create(),typeName:N.ZodObject,...te(e)});Mt.lazycreate=(t,e)=>new Mt({shape:t,unknownKeys:"strip",catchall:bn.create(),typeName:N.ZodObject,...te(e)});Ro=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Nt(a.ctx.common.issues));return M(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Nt(c));return M(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};Ro.create=(t,e)=>new Ro({options:t,typeName:N.ZodUnion,...te(e)});ar=t=>t instanceof Oo?ar(t.schema):t instanceof cn?ar(t.innerType()):t instanceof Io?[t.value]:t instanceof Ao?t.options:t instanceof No?ce.objectValues(t.enum):t instanceof Do?ar(t._def.innerType):t instanceof $o?[void 0]:t instanceof Po?[null]:t instanceof Dt?[void 0,...ar(t.unwrap())]:t instanceof Un?[null,...ar(t.unwrap())]:t instanceof na||t instanceof jo?ar(t.unwrap()):t instanceof Mo?ar(t._def.innerType):[],yu=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.object)return M(n,{code:I.invalid_type,expected:H.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=ar(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:N.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};Co=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(hu(s)||hu(i))return G;let a=Gf(s.value,i.value);return a.valid?((gu(s)||gu(i))&&n.dirty(),{status:n.value,value:a.data}):(M(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Co.create=(t,e,n)=>new Co({left:t,right:e,typeName:N.ZodIntersection,...te(n)});Hn=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.array)return M(r,{code:I.invalid_type,expected:H.array,received:r.parsedType}),G;if(r.data.length<this._def.items.length)return M(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new an(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ct.mergeArray(n,i)):ct.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Hn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Hn({items:t,typeName:N.ZodTuple,rest:null,...te(e)})};_u=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.object)return M(r,{code:I.invalid_type,expected:H.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new an(r,a,r.path,a)),value:i._parse(new an(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ct.mergeObjectAsync(n,o):ct.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:N.ZodRecord,...te(r)}):new t({keyType:Mr.create(),valueType:e,typeName:N.ZodRecord,...te(n)})}},Ms=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.map)return M(r,{code:I.invalid_type,expected:H.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new an(r,a,r.path,[u,"key"])),value:s._parse(new an(r,c,r.path,[u,"value"]))}));if(r.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Ms.create=(t,e,n)=>new Ms({valueType:e,keyType:t,typeName:N.ZodMap,...te(n)});js=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.set)return M(r,{code:I.invalid_type,expected:H.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(M(r,{code:I.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(M(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new an(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:Z.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};js.create=(t,e)=>new js({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...te(e)});bu=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.function)return M(n,{code:I.invalid_type,expected:H.function,received:n.parsedType}),G;function r(a,c){return ta({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),ir].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return ta({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),ir].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Lr){let a=this;return yt(async function(...c){let u=new Nt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(r(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return yt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Nt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Nt([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:Hn.create(e).rest(cr.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,n,r){return new t({args:e||Hn.create([]).rest(cr.create()),returns:n||cr.create(),typeName:N.ZodFunction,...te(r)})}},Oo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Oo.create=(t,e)=>new Oo({getter:t,typeName:N.ZodLazy,...te(e)});Io=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};Io.create=(t,e)=>new Io({value:t,typeName:N.ZodLiteral,...te(e)});Ao=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return yt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Ao.create=Fk;No=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==H.string&&r.parsedType!==H.number){let o=ce.objectValues(n);return M(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return M(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return yt(e.data)}get enum(){return this._def.values}};No.create=(t,e)=>new No({values:t,typeName:N.ZodNativeEnum,...te(e)});Lr=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.promise&&n.common.async===!1)return M(n,{code:I.invalid_type,expected:H.promise,received:n.parsedType}),G;let r=n.parsedType===H.promise?n.data:Promise.resolve(n.data);return yt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Lr.create=(t,e)=>new Lr({type:t,typeName:N.ZodPromise,...te(e)});cn=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{M(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?vo(c.value):n.value==="dirty"?vo(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?vo(a.value):n.value==="dirty"?vo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Dr(i))return G;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Dr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};cn.create=(t,e,n)=>new cn({schema:t,typeName:N.ZodEffects,effect:e,...te(n)});cn.createWithPreprocess=(t,e,n)=>new cn({schema:e,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...te(n)});Dt=class extends re{_parse(e){return this._getType(e)===H.undefined?yt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:N.ZodOptional,...te(e)});Un=class extends re{_parse(e){return this._getType(e)===H.null?yt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Un.create=(t,e)=>new Un({innerType:t,typeName:N.ZodNullable,...te(e)});Do=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===H.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Do.create=(t,e)=>new Do({innerType:t,typeName:N.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Mo=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Is(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Nt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Nt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Mo.create=(t,e)=>new Mo({innerType:t,typeName:N.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Ls=class extends re{_parse(e){if(this._getType(e)!==H.nan){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Ls.create=t=>new Ls({typeName:N.ZodNaN,...te(t)});mj=Symbol("zod_brand"),na=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ra=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),vo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:N.ZodPipeline})}},jo=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Dr(o)&&(o.value=Object.freeze(o.value)),o);return Is(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};jo.create=(t,e)=>new jo({innerType:t,typeName:N.ZodReadonly,...te(e)});hj={object:Mt.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"})(N||(N={}));gj=(t,e={message:`Input not instance of ${t.name}`})=>Bk(n=>n instanceof t,e),Zk=Mr.create,qk=ko.create,yj=Ls.create,_j=wo.create,Vk=Eo.create,bj=To.create,xj=Ns.create,Sj=$o.create,vj=Po.create,kj=jr.create,wj=cr.create,Ej=bn.create,Tj=Ds.create,$j=ur.create,Jf=Mt.create,Pj=Mt.strictCreate,Rj=Ro.create,Cj=yu.create,Oj=Co.create,Ij=Hn.create,Aj=_u.create,Nj=Ms.create,Dj=js.create,Mj=bu.create,jj=Oo.create,Lj=Io.create,zj=Ao.create,Hj=No.create,Uj=Lr.create,Fj=cn.create,Bj=Dt.create,Zj=Un.create,qj=cn.createWithPreprocess,Vj=ra.create,Wj=()=>Zk().optional(),Kj=()=>qk().optional(),Gj=()=>Vk().optional(),Jj={string:(t=>Mr.create({...t,coerce:!0})),number:(t=>ko.create({...t,coerce:!0})),boolean:(t=>Eo.create({...t,coerce:!0})),bigint:(t=>wo.create({...t,coerce:!0})),date:(t=>To.create({...t,coerce:!0}))},Xj=G});var j={};_e(j,{BRAND:()=>mj,DIRTY:()=>vo,EMPTY_PATH:()=>VM,INVALID:()=>G,NEVER:()=>Xj,OK:()=>yt,ParseStatus:()=>ct,Schema:()=>re,ZodAny:()=>jr,ZodArray:()=>ur,ZodBigInt:()=>wo,ZodBoolean:()=>Eo,ZodBranded:()=>na,ZodCatch:()=>Mo,ZodDate:()=>To,ZodDefault:()=>Do,ZodDiscriminatedUnion:()=>yu,ZodEffects:()=>cn,ZodEnum:()=>Ao,ZodError:()=>Nt,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>bu,ZodIntersection:()=>Co,ZodIssueCode:()=>I,ZodLazy:()=>Oo,ZodLiteral:()=>Io,ZodMap:()=>Ms,ZodNaN:()=>Ls,ZodNativeEnum:()=>No,ZodNever:()=>bn,ZodNull:()=>Po,ZodNullable:()=>Un,ZodNumber:()=>ko,ZodObject:()=>Mt,ZodOptional:()=>Dt,ZodParsedType:()=>H,ZodPipeline:()=>ra,ZodPromise:()=>Lr,ZodReadonly:()=>jo,ZodRecord:()=>_u,ZodSchema:()=>re,ZodSet:()=>js,ZodString:()=>Mr,ZodSymbol:()=>Ns,ZodTransformer:()=>cn,ZodTuple:()=>Hn,ZodType:()=>re,ZodUndefined:()=>$o,ZodUnion:()=>Ro,ZodUnknown:()=>cr,ZodVoid:()=>Ds,addIssueToContext:()=>M,any:()=>kj,array:()=>$j,bigint:()=>_j,boolean:()=>Vk,coerce:()=>Jj,custom:()=>Bk,date:()=>bj,datetimeRegex:()=>Uk,defaultErrorMap:()=>ir,discriminatedUnion:()=>Cj,effect:()=>Fj,enum:()=>zj,function:()=>Mj,getErrorMap:()=>Os,getParsedType:()=>zn,instanceof:()=>gj,intersection:()=>Oj,isAborted:()=>hu,isAsync:()=>Is,isDirty:()=>gu,isValid:()=>Dr,late:()=>hj,lazy:()=>jj,literal:()=>Lj,makeIssue:()=>ta,map:()=>Nj,nan:()=>yj,nativeEnum:()=>Hj,never:()=>Ej,null:()=>vj,nullable:()=>Zj,number:()=>qk,object:()=>Jf,objectUtil:()=>qf,oboolean:()=>Gj,onumber:()=>Kj,optional:()=>Bj,ostring:()=>Wj,pipeline:()=>Vj,preprocess:()=>qj,promise:()=>Uj,quotelessJson:()=>BM,record:()=>Aj,set:()=>Dj,setErrorMap:()=>qM,strictObject:()=>Pj,string:()=>Zk,symbol:()=>xj,transformer:()=>Fj,tuple:()=>Ij,undefined:()=>Sj,union:()=>Rj,unknown:()=>wj,util:()=>ce,void:()=>Tj});var xu=x(()=>{mu();Wf();Dk();ea();Wk();fu()});var oa=x(()=>{xu()});function E(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Wt(t){return t&&Object.assign(Su,t),Su}var Qj,lr,Su,zs=x(()=>{Qj=Object.freeze({status:"aborted"});lr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Su={}});var ue={};_e(ue,{BIGINT_FORMAT_RANGES:()=>Gk,Class:()=>Yf,NUMBER_FORMAT_RANGES:()=>sm,aborted:()=>zo,allowsEval:()=>nm,assert:()=>o1,assertEqual:()=>e1,assertIs:()=>n1,assertNever:()=>r1,assertNotEqual:()=>t1,assignProp:()=>tm,cached:()=>aa,captureStackTrace:()=>ku,cleanEnum:()=>y1,cleanRegex:()=>ua,clone:()=>Kt,createTransparentProxy:()=>l1,defineLazy:()=>$e,esc:()=>Lo,escapeRegex:()=>zr,extend:()=>f1,finalizeIssue:()=>xn,floatSafeRemainder:()=>em,getElementAtPath:()=>s1,getEnumValues:()=>ia,getLengthableOrigin:()=>la,getParsedType:()=>u1,getSizableOrigin:()=>Jk,isObject:()=>Hs,isPlainObject:()=>Us,issue:()=>im,joinValues:()=>vu,jsonStringifyReplacer:()=>Qf,merge:()=>m1,normalizeParams:()=>J,nullish:()=>ca,numKeys:()=>c1,omit:()=>p1,optionalKeys:()=>om,partial:()=>h1,pick:()=>d1,prefixIssues:()=>Fn,primitiveTypes:()=>Kk,promiseAllObject:()=>i1,propertyKeyTypes:()=>rm,randomString:()=>a1,required:()=>g1,stringifyPrimitive:()=>wu,unwrapMessage:()=>sa});function e1(t){return t}function t1(t){return t}function n1(t){}function r1(t){throw new Error}function o1(t){}function ia(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function vu(t,e="|"){return t.map(n=>wu(n)).join(e)}function Qf(t,e){return typeof e=="bigint"?e.toString():e}function aa(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ca(t){return t==null}function ua(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function em(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function $e(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function tm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function s1(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function i1(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function a1(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Lo(t){return JSON.stringify(t)}function Hs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Us(t){if(Hs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Hs(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function c1(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function zr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kt(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function l1(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function wu(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function om(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function d1(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Kt(t,{...t._zod.def,shape:n,checks:[]})}function p1(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Kt(t,{...t._zod.def,shape:n,checks:[]})}function f1(t,e){if(!Us(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return tm(this,"shape",r),r},checks:[]};return Kt(t,n)}function m1(t,e){return Kt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return tm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function h1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Kt(e,{...e._zod.def,shape:o,checks:[]})}function g1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Kt(e,{...e._zod.def,shape:o,checks:[]})}function zo(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Fn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function sa(t){return typeof t=="string"?t:t?.message}function xn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=sa(t.inst?._zod.def?.error?.(t))??sa(e?.error?.(t))??sa(n.customError?.(t))??sa(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Jk(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function la(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function im(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function y1(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ku,nm,u1,rm,Kk,sm,Gk,Yf,Bn=x(()=>{ku=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};nm=aa(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});u1=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}`)}},rm=new Set(["string","number","symbol"]),Kk=new Set(["string","number","bigint","boolean","symbol","undefined"]);sm={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]},Gk={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Yf=class{constructor(...e){}}});function am(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function cm(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var Xk,Eu,da,um=x(()=>{zs();Bn();Xk=(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,Qf,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Eu=E("$ZodError",Xk),da=E("$ZodError",Xk,{Parent:Error})});var lm,dm,pm,fm,mm,Ho,hm,Uo,gm=x(()=>{zs();um();Bn();lm=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new lr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xn(c,s,Wt())));throw ku(a,o?.callee),a}return i.value},dm=lm(da),pm=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xn(c,s,Wt())));throw ku(a,o?.callee),a}return i.value},fm=pm(da),mm=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new lr;return s.issues.length?{success:!1,error:new(t??Eu)(s.issues.map(i=>xn(i,o,Wt())))}:{success:!0,data:s.value}},Ho=mm(da),hm=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>xn(i,o,Wt())))}:{success:!0,data:s.value}},Uo=hm(da)});function aw(){return new RegExp(b1,"u")}function yw(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 _w(t){return new RegExp(`^${yw(t)}$`)}function bw(t){let e=yw({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${hw}T(?:${r})$`)}var Yk,Qk,ew,tw,nw,rw,ow,sw,ym,iw,b1,cw,uw,lw,dw,pw,_m,fw,mw,hw,gw,xw,Sw,vw,kw,ww,Ew,Tw,$u=x(()=>{Yk=/^[cC][^\s-]{8,}$/,Qk=/^[0-9a-z]+$/,ew=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tw=/^[0-9a-vA-V]{20}$/,nw=/^[A-Za-z0-9]{27}$/,rw=/^[a-zA-Z0-9_-]{21}$/,ow=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sw=/^([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})$/,ym=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)$/,iw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,b1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";cw=/^(?:(?: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])$/,uw=/^(([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})$/,lw=/^((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])$/,dw=/^(([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])$/,pw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_m=/^[A-Za-z0-9_-]*$/,fw=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,mw=/^\+(?:[0-9]){6,14}[0-9]$/,hw="(?:(?:\\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])))",gw=new RegExp(`^${hw}$`);xw=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Sw=/^\d+$/,vw=/^-?\d+(?:\.\d+)?/i,kw=/true|false/i,ww=/null/i,Ew=/^[^A-Z]*$/,Tw=/^[^a-z]*$/});var ut,$w,bm,xm,Pw,Rw,Cw,Ow,Iw,pa,Aw,Nw,Dw,Mw,jw,Lw,zw,Pu=x(()=>{zs();$u();Bn();ut=E("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),$w={number:"number",bigint:"bigint",object:"date"},bm=E("$ZodCheckLessThan",(t,e)=>{ut.init(t,e);let n=$w[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xm=E("$ZodCheckGreaterThan",(t,e)=>{ut.init(t,e);let n=$w[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Pw=E("$ZodCheckMultipleOf",(t,e)=>{ut.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):em(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Rw=E("$ZodCheckNumberFormat",(t,e)=>{ut.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=sm[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Sw)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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})}}),Cw=E("$ZodCheckMaxLength",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ca(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=la(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ow=E("$ZodCheckMinLength",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ca(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=la(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Iw=E("$ZodCheckLengthEquals",(t,e)=>{var n;ut.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!ca(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=la(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),pa=E("$ZodCheckStringFormat",(t,e)=>{var n,r;ut.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),Aw=E("$ZodCheckRegex",(t,e)=>{pa.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Nw=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ew),pa.init(t,e)}),Dw=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Tw),pa.init(t,e)}),Mw=E("$ZodCheckIncludes",(t,e)=>{ut.init(t,e);let n=zr(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),jw=E("$ZodCheckStartsWith",(t,e)=>{ut.init(t,e);let n=new RegExp(`^${zr(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Lw=E("$ZodCheckEndsWith",(t,e)=>{ut.init(t,e);let n=new RegExp(`.*${zr(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),zw=E("$ZodCheckOverwrite",(t,e)=>{ut.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var Ru,Sm=x(()=>{Ru=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 r=e.split(`
|
|
454
|
+
`);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#f(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,p=Math.min(u+l.length,s.length),m=l[0]?.trim().slice(0,yk),f=l.join(`
|
|
455
|
+
`);if(Buffer.byteLength(f)<=r)i.push({title:m||`Lines ${d}-${p}`,content:f});else{let h=this.#f(l,m||`Lines ${d}-${p}`,r);i.push(...h)}}return i}#F(e,n,r,o){let s=n.length>0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.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)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}}});import{readFileSync as Tk,realpathSync as Hf}from"node:fs";import{relative as yM,resolve as bo,sep as _M}from"node:path";function $k(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function bM(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function xM(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Ek(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function SM(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=xM(o),a=Ek(s);n=`^${i}(\\s${a})?$`}else n=`^${Ek(t)}$`;return new RegExp(n,e?"i":"")}function vM(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function kM(t,e,n=!1){for(let r of e){let o=$k(r);if(o&&SM(o,n).test(t))return r}return null}function Pk(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function wM(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=Pk(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
|
|
456
|
+
`||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function Rk(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=Pk(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...Rk(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),p=t.slice(d,c);e.push(p)}}}return e}function Ck(t){let e=[],n=wM(t);for(let r of n){e.push(r);for(let o of Rk(r))e.push(...Ck(o))}return e}function zf(t){let e;try{e=Tk(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&$k(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function Uf(t,e){let n=[];if(t){let o=bo(t,".claude","settings.local.json"),s=zf(o);s&&n.push(s);let i=bo(t,".claude","settings.json"),a=zf(i);a&&n.push(a)}let r=e!==void 0?[e]:Nf();for(let o of r){let s=zf(o);s&&n.push(s)}return n}function xo(t,e,n){return Ff(t,"deny",e,n)}function Ff(t,e,n,r){let o=[],s=a=>{let c;try{c=Tk(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let p of l){if(typeof p!="string")continue;let m=bM(p);m&&m.tool===t&&d.push(m.glob)}return d};if(n){let a=s(bo(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(bo(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:Nf();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function Bf(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=Ck(t);for(let o of r)for(let s of e){let i=kM(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Ar(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=bo(r,t);s.add(o(i));try{s.add(o(Hf(i)))}catch{}}for(let i of e)for(let a of i){let c=vM(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function EM(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=bo(e),o=bo(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=yM(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+_M)||TM(l))};if(!s(r,o))return!1;try{let i=Hf(r),a=Hf(o);if(!s(i,a))return!1}catch{}return!0}function TM(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function Ok(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return EM(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&Ar(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}function PM(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Ik(t,e){let n=$M[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...PM(t)),r}var $M,Zf=x(()=>{"use strict";Pr();$M={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 jk={};_e(jk,{PACKAGE_NAME:()=>Dk,PLUGIN_ID:()=>Mk,PLUGIN_KEY:()=>HM,healClaudeJsonMcpArgs:()=>ZM,healInstalledPlugins:()=>UM,healMcpJsonArgs:()=>BM,healPluginJsonMcpServers:()=>mu,healSettingsEnabledPlugins:()=>FM,sweepStaleMcpJson:()=>hu});import{existsSync as sr,readFileSync as Cs,writeFileSync as na,readdirSync as jM,unlinkSync as LM,statSync as zM}from"node:fs";import{resolve as Pt,sep as So}from"node:path";function qf(t){let e=t.indexOf("@");return e<=0?null:{id:t.slice(0,e),pkg:t.slice(e+1)}}function UM({registryPath:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!sr(t))return{healed:[],skipped:"no-registry"};let r;try{r=Cs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(r)}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[n]||[];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=Pt(u),d=Pt(e)+So;if(!l.startsWith(d))continue;let p=Pt(u,".claude-plugin","plugin.json");if(!sr(p))continue;let m=null;try{let f=JSON.parse(Cs(p,"utf-8"));f&&typeof f.version=="string"&&f.version&&(m=f.version)}catch{continue}m&&(a=m,c.version!==m&&(c.version=m,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[n];(c==null||c===!1||c==="")&&(o.enabledPlugins[n]=!0,i.push("enabled-plugins"))}if(i.length>0)try{na(t,JSON.stringify(o,null,2)+`
|
|
457
|
+
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function FM({settingsPath:t,pluginKey:e}){if(!t||!sr(t))return{healed:[],skipped:"no-settings"};let n;try{n=Cs(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let r;try{r=JSON.parse(n)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!r.enabledPlugins||typeof r.enabledPlugins!="object"||Array.isArray(r.enabledPlugins))&&(r.enabledPlugins={});let s=r.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(r.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{na(t,JSON.stringify(r,null,2)+`
|
|
458
|
+
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function mu({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=Pt(t),o=Pt(e)+So;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=Pt(t,".claude-plugin","plugin.json");if(!sr(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=Cs(s,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=qf(n)?.id??n.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,m=p.map(h=>typeof h!="string"||h===ta?h:/[/\\]start\.mjs$/.test(h)?ta:h);if(m.some((h,g)=>h!==p[g])){l.args=m,d.push("plugin-json-args");try{na(s,JSON.stringify(a,null,2)+`
|
|
459
|
+
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function BM({pluginRoot:t,pluginCacheRoot:e,pluginKey:n}){if(!t||!e||!n)return{healed:[],skipped:"missing-args"};let r=Pt(t),o=Pt(e)+So;if(!r.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=Pt(t,".mcp.json");if(!sr(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=Cs(s,"utf-8")}catch(h){return{healed:[],error:`read-failed: ${h&&h.message||h}`}}let a;try{a=JSON.parse(i)}catch(h){return{healed:[],error:`parse-failed: ${h&&h.message||h}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=qf(n)?.id??n.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,m=p.map(h=>typeof h!="string"||h===ta?h:h==="./start.mjs"||h==="start.mjs"||/[/\\]start\.mjs$/.test(h)?ta:h);if(m.some((h,g)=>h!==p[g])){l.args=m,d.push("mcp-json-args");try{na(s,JSON.stringify(a,null,2)+`
|
|
460
|
+
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:d}}function ZM({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:n}){if(!t||!sr(t))return{healed:[],skipped:"no-claude-json"};let r;try{r=Cs(t,"utf-8")}catch(l){return{healed:[],error:`read-failed: ${l&&l.message||l}`}}let o;try{o=JSON.parse(r)}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=Pt(n),c=a+So,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 m=p.replace(/\\/g,"/");if(!m.startsWith(i+"/"))continue;let f=m.slice(i.length+1),h=f.indexOf("/");if(h<0)continue;let g=f.slice(h+1),y=Pt(n,g);y!==a&&!(y+So).startsWith(c)||y!==p&&(l.args[d]=y,u=!0)}if(!u)return{healed:[]};try{na(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 hu({pluginCacheRoot:t,pluginKey:e}){let n=[];if(!t||!e)return{removed:n,skipped:"missing-args"};let r=Pt(t);if(!sr(r))return{removed:n,skipped:"no-cache-root"};let o=qf(e);if(!o)return{removed:n,skipped:"bad-plugin-key"};let s=o.id,i=o.pkg;if(!s||!i)return{removed:n,skipped:"bad-plugin-key"};let a=Pt(r,s,i),c=r+So;if(!a.startsWith(c))return{removed:n,skipped:"outside-cache-root"};if(!sr(a))return{removed:n,skipped:"no-plugin-dir"};let u=[];try{u=jM(a)}catch{return{removed:n,skipped:"readdir-failed"}}for(let l of u){let d=Pt(a,l);if(!d.startsWith(a+So))continue;try{if(!zM(d).isDirectory())continue}catch{continue}let p=Pt(d,".mcp.json");if(sr(p))try{LM(p),n.push(p)}catch{}}return{removed:n}}var Dk,Mk,HM,ta,Vf=x(()=>{"use strict";Dk="@mxalbert/context-mode",Mk="context-mode",HM=`${Mk}@${Dk}`;ta="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,Wf,H,zn,ra=x(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Wf||(Wf={}));H=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),zn=t=>{switch(typeof t){case"undefined":return H.undefined;case"string":return H.string;case"number":return Number.isNaN(t)?H.nan:H.number;case"boolean":return H.boolean;case"function":return H.function;case"bigint":return H.bigint;case"symbol":return H.symbol;case"object":return Array.isArray(t)?H.array:t===null?H.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?H.promise:typeof Map<"u"&&t instanceof Map?H.map:typeof Set<"u"&&t instanceof Set?H.set:typeof Date<"u"&&t instanceof Date?H.date:H.object;default:return H.unknown}}});var I,WM,Mt,gu=x(()=>{ra();I=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"]),WM=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Mt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}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=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Mt.create=t=>new Mt(t)});var KM,ir,Kf=x(()=>{gu();ra();KM=(t,e)=>{let n;switch(t.code){case I.invalid_type:t.received===H.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case I.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case I.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=e.defaultError,ce.assertNever(t)}return{message:n}},ir=KM});function GM(t){zk=t}function Os(){return zk}var zk,yu=x(()=>{Kf();zk=ir});function M(t,e){let n=Os(),r=oa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ir?void 0:ir].filter(o=>!!o)});t.common.issues.push(r)}var oa,JM,dt,G,vo,xt,_u,bu,Nr,Is,Gf=x(()=>{yu();Kf();oa=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},JM=[];dt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return G;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return G;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},G=Object.freeze({status:"aborted"}),vo=t=>({status:"dirty",value:t}),xt=t=>({status:"valid",value:t}),_u=t=>t.status==="aborted",bu=t=>t.status==="dirty",Nr=t=>t.status==="valid",Is=t=>typeof Promise<"u"&&t instanceof Promise});var Hk=x(()=>{});var Z,Uk=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Z||(Z={}))});function te(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}function qk(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function fj(t){return new RegExp(`^${qk(t)}$`)}function Vk(t){let e=`${Zk}T${qk(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function mj(t,e){return!!((e==="v4"||!e)&&ij.test(t)||(e==="v6"||!e)&&cj.test(t))}function hj(t,e){if(!nj.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function gj(t,e){return!!((e==="v4"||!e)&&aj.test(t)||(e==="v6"||!e)&&uj.test(t))}function yj(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function As(t){if(t instanceof Lt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=jt.create(As(r))}return new Lt({...t._def,shape:()=>e})}else return t instanceof ur?new ur({...t._def,type:As(t.element)}):t instanceof jt?jt.create(As(t.unwrap())):t instanceof Un?Un.create(As(t.unwrap())):t instanceof Hn?Hn.create(t.items.map(e=>As(e))):t}function Xf(t,e){let n=zn(t),r=zn(e);if(t===e)return{valid:!0,data:t};if(n===H.object&&r===H.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=Xf(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===H.array&&r===H.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=Xf(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===H.date&&r===H.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Wk(t,e){return new Ao({values:t,typeName:N.ZodEnum,...te(e)})}function Bk(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Kk(t,e={},n){return t?Mr.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Bk(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Bk(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Mr.create()}var un,Fk,re,XM,YM,QM,ej,tj,nj,rj,oj,sj,Jf,ij,aj,cj,uj,lj,dj,Zk,pj,Dr,ko,wo,Eo,To,Ns,$o,Po,Mr,cr,xn,Ds,ur,Lt,Ro,ar,xu,Co,Hn,Su,Ms,js,vu,Oo,Io,Ao,No,jr,ln,jt,Un,Do,Mo,Ls,_j,sa,ia,jo,bj,N,xj,Gk,Jk,Sj,vj,Xk,kj,wj,Ej,Tj,$j,Pj,Rj,Cj,Oj,Yf,Ij,Aj,Nj,Dj,Mj,jj,Lj,zj,Hj,Uj,Fj,Bj,Zj,qj,Vj,Wj,Kj,Gj,Jj,Xj,Yj,Qj,e1,t1,Yk=x(()=>{gu();yu();Uk();Gf();ra();un=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},Fk=(t,e)=>{if(Nr(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 n=new Mt(t.common.issues);return this._error=n,this._error}}};re=class{get description(){return this._def.description}_getType(e){return zn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:zn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new dt,ctx:{common:e.parent.common,data:e.data,parsedType:zn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Is(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Fk(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Nr(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Nr(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zn(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Is(o)?o:Promise.resolve(o));return Fk(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:I.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new ln({schema:this,typeName:N.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:n=>this["~validate"](n)}}optional(){return jt.create(this,this._def)}nullable(){return Un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ur.create(this)}promise(){return jr.create(this,this._def)}or(e){return Ro.create([this,e],this._def)}and(e){return Co.create(this,e,this._def)}transform(e){return new ln({...te(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Do({...te(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new sa({typeName:N.ZodBranded,type:this,...te(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Mo({...te(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ia.create(this,e)}readonly(){return jo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},XM=/^c[^\s-]{8,}$/i,YM=/^[0-9a-z]+$/,QM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ej=/^[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,tj=/^[a-z0-9_-]{21}$/i,nj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rj=/^[-+]?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)?)??$/,oj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ij=/^(?:(?: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])$/,aj=/^(?:(?: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])$/,cj=/^(([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]))$/,uj=/^(([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])$/,lj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zk="((\\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])))",pj=new RegExp(`^${Zk}$`);Dr=class t extends re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==H.string){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.string,received:s.parsedType}),G}let r=new dt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.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?M(o,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&M(o,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")oj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"email",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Jf||(Jf=new RegExp(sj,"u")),Jf.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"emoji",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ej.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"uuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")tj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"nanoid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")XM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")YM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cuid2",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")QM.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ulid",code:I.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),M(o,{validation:"url",code:I.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"regex",code:I.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.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),M(o,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Vk(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?pj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?fj(s).test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{code:I.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?rj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"duration",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?mj(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"ip",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?hj(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"jwt",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?gj(e.data,s.version)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"cidr",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?lj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64",code:I.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?dj.test(e.data)||(o=this._getOrReturnCtx(e,o),M(o,{validation:"base64url",code:I.invalid_string,message:s.message}),r.dirty()):ce.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:I.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Z.errToObj(n)})}nonempty(e){return this.min(1,Z.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Dr.create=t=>new Dr({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...te(t)});ko=class t extends re{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)!==H.number){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.number,received:s.parsedType}),G}let r,o=new dt;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?yj(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.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,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};ko.create=t=>new ko({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...te(t)});wo=class t extends re{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)!==H.bigint)return this._getInvalidInput(e);let r,o=new dt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.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)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),M(r,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:H.bigint,received:n.parsedType}),G}gte(e,n){return this.setLimit("min",e,!0,Z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Z.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Z.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:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};wo.create=t=>new wo({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...te(t)});Eo=class extends re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.boolean,received:r.parsedType}),G}return xt(e.data)}};Eo.create=t=>new Eo({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...te(t)});To=class t extends re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==H.date){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_type,expected:H.date,received:s.parsedType}),G}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return M(s,{code:I.invalid_date}),G}let r=new dt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),M(o,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Z.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};To.create=t=>new To({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...te(t)});Ns=class extends re{_parse(e){if(this._getType(e)!==H.symbol){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.symbol,received:r.parsedType}),G}return xt(e.data)}};Ns.create=t=>new Ns({typeName:N.ZodSymbol,...te(t)});$o=class extends re{_parse(e){if(this._getType(e)!==H.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.undefined,received:r.parsedType}),G}return xt(e.data)}};$o.create=t=>new $o({typeName:N.ZodUndefined,...te(t)});Po=class extends re{_parse(e){if(this._getType(e)!==H.null){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.null,received:r.parsedType}),G}return xt(e.data)}};Po.create=t=>new Po({typeName:N.ZodNull,...te(t)});Mr=class extends re{constructor(){super(...arguments),this._any=!0}_parse(e){return xt(e.data)}};Mr.create=t=>new Mr({typeName:N.ZodAny,...te(t)});cr=class extends re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xt(e.data)}};cr.create=t=>new cr({typeName:N.ZodUnknown,...te(t)});xn=class extends re{_parse(e){let n=this._getOrReturnCtx(e);return M(n,{code:I.invalid_type,expected:H.never,received:n.parsedType}),G}};xn.create=t=>new xn({typeName:N.ZodNever,...te(t)});Ds=class extends re{_parse(e){if(this._getType(e)!==H.undefined){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.void,received:r.parsedType}),G}return xt(e.data)}};Ds.create=t=>new Ds({typeName:N.ZodVoid,...te(t)});ur=class t extends re{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==H.array)return M(n,{code:I.invalid_type,expected:H.array,received:n.parsedType}),G;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(M(n,{code:i?I.too_big:I.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}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(M(n,{code:I.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(M(n,{code:I.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new un(n,i,n.path,a)))).then(i=>dt.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new un(n,i,n.path,a)));return dt.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Z.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Z.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Z.toString(n)}})}nonempty(e){return this.min(1,e)}};ur.create=(t,e)=>new ur({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...te(e)});Lt=class t extends re{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(),n=ce.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==H.object){let u=this._getOrReturnCtx(e);return M(u,{code:I.invalid_type,expected:H.object,received:u.parsedType}),G}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof xn&&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 un(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof xn){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&&(M(o,{code:I.unrecognized_keys,keys:a}),r.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 un(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=>dt.mergeObjectSync(r,u)):dt.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:Z.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:N.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of ce.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of ce.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return As(this)}partial(e){let n={};for(let r of ce.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of ce.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof jt;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Wk(ce.objectKeys(this.shape))}};Lt.create=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strip",catchall:xn.create(),typeName:N.ZodObject,...te(e)});Lt.strictCreate=(t,e)=>new Lt({shape:()=>t,unknownKeys:"strict",catchall:xn.create(),typeName:N.ZodObject,...te(e)});Lt.lazycreate=(t,e)=>new Lt({shape:t,unknownKeys:"strip",catchall:xn.create(),typeName:N.ZodObject,...te(e)});Ro=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Mt(a.ctx.common.issues));return M(n,{code:I.invalid_union,unionErrors:i}),G}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Mt(c));return M(n,{code:I.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};Ro.create=(t,e)=>new Ro({options:t,typeName:N.ZodUnion,...te(e)});ar=t=>t instanceof Oo?ar(t.schema):t instanceof ln?ar(t.innerType()):t instanceof Io?[t.value]:t instanceof Ao?t.options:t instanceof No?ce.objectValues(t.enum):t instanceof Do?ar(t._def.innerType):t instanceof $o?[void 0]:t instanceof Po?[null]:t instanceof jt?[void 0,...ar(t.unwrap())]:t instanceof Un?[null,...ar(t.unwrap())]:t instanceof sa||t instanceof jo?ar(t.unwrap()):t instanceof Mo?ar(t._def.innerType):[],xu=class t extends re{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.object)return M(n,{code:I.invalid_type,expected:H.object,received:n.parsedType}),G;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(M(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=ar(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:N.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...te(r)})}};Co=class extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(_u(s)||_u(i))return G;let a=Xf(s.value,i.value);return a.valid?((bu(s)||bu(i))&&n.dirty(),{status:n.value,value:a.data}):(M(r,{code:I.invalid_intersection_types}),G)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Co.create=(t,e,n)=>new Co({left:t,right:e,typeName:N.ZodIntersection,...te(n)});Hn=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.array)return M(r,{code:I.invalid_type,expected:H.array,received:r.parsedType}),G;if(r.data.length<this._def.items.length)return M(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&r.data.length>this._def.items.length&&(M(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new un(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>dt.mergeArray(n,i)):dt.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Hn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Hn({items:t,typeName:N.ZodTuple,rest:null,...te(e)})};Su=class t extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.object)return M(r,{code:I.invalid_type,expected:H.object,received:r.parsedType}),G;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new un(r,a,r.path,a)),value:i._parse(new un(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?dt.mergeObjectAsync(n,o):dt.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof re?new t({keyType:e,valueType:n,typeName:N.ZodRecord,...te(r)}):new t({keyType:Dr.create(),valueType:e,typeName:N.ZodRecord,...te(n)})}},Ms=class extends re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.map)return M(r,{code:I.invalid_type,expected:H.map,received:r.parsedType}),G;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new un(r,a,r.path,[u,"key"])),value:s._parse(new un(r,c,r.path,[u,"value"]))}));if(r.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 G;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Ms.create=(t,e,n)=>new Ms({valueType:e,keyType:t,typeName:N.ZodMap,...te(n)});js=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==H.set)return M(r,{code:I.invalid_type,expected:H.set,received:r.parsedType}),G;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(M(r,{code:I.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(M(r,{code:I.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return G;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new un(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:Z.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};js.create=(t,e)=>new js({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...te(e)});vu=class t extends re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.function)return M(n,{code:I.invalid_type,expected:H.function,received:n.parsedType}),G;function r(a,c){return oa({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),ir].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function o(a,c){return oa({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Os(),ir].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof jr){let a=this;return xt(async function(...c){let u=new Mt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(r(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return xt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Mt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Mt([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:Hn.create(e).rest(cr.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,n,r){return new t({args:e||Hn.create([]).rest(cr.create()),returns:n||cr.create(),typeName:N.ZodFunction,...te(r)})}},Oo=class extends re{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Oo.create=(t,e)=>new Oo({getter:t,typeName:N.ZodLazy,...te(e)});Io=class extends re{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return M(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};Io.create=(t,e)=>new Io({value:t,typeName:N.ZodLiteral,...te(e)});Ao=class t extends re{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{expected:ce.joinValues(r),received:n.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return M(n,{received:n.data,code:I.invalid_enum_value,options:r}),G}return xt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Ao.create=Wk;No=class extends re{_parse(e){let n=ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==H.string&&r.parsedType!==H.number){let o=ce.objectValues(n);return M(r,{expected:ce.joinValues(o),received:r.parsedType,code:I.invalid_type}),G}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(n);return M(r,{received:r.data,code:I.invalid_enum_value,options:o}),G}return xt(e.data)}get enum(){return this._def.values}};No.create=(t,e)=>new No({values:t,typeName:N.ZodNativeEnum,...te(e)});jr=class extends re{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==H.promise&&n.common.async===!1)return M(n,{code:I.invalid_type,expected:H.promise,received:n.parsedType}),G;let r=n.parsedType===H.promise?n.data:Promise.resolve(n.data);return xt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};jr.create=(t,e)=>new jr({type:t,typeName:N.ZodPromise,...te(e)});ln=class extends re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{M(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?G:c.status==="dirty"?vo(c.value):n.value==="dirty"?vo(c.value):c});{if(n.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?G:a.status==="dirty"?vo(a.value):n.value==="dirty"?vo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nr(i))return G;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Nr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):G);ce.assertNever(o)}};ln.create=(t,e,n)=>new ln({schema:t,typeName:N.ZodEffects,effect:e,...te(n)});ln.createWithPreprocess=(t,e,n)=>new ln({schema:e,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...te(n)});jt=class extends re{_parse(e){return this._getType(e)===H.undefined?xt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:N.ZodOptional,...te(e)});Un=class extends re{_parse(e){return this._getType(e)===H.null?xt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Un.create=(t,e)=>new Un({innerType:t,typeName:N.ZodNullable,...te(e)});Do=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===H.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Do.create=(t,e)=>new Do({innerType:t,typeName:N.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...te(e)});Mo=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Is(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Mt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Mt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Mo.create=(t,e)=>new Mo({innerType:t,typeName:N.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...te(e)});Ls=class extends re{_parse(e){if(this._getType(e)!==H.nan){let r=this._getOrReturnCtx(e);return M(r,{code:I.invalid_type,expected:H.nan,received:r.parsedType}),G}return{status:"valid",value:e.data}}};Ls.create=t=>new Ls({typeName:N.ZodNaN,...te(t)});_j=Symbol("zod_brand"),sa=class extends re{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ia=class t extends re{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?G:s.status==="dirty"?(n.dirty(),vo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?G:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:N.ZodPipeline})}},jo=class extends re{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Nr(o)&&(o.value=Object.freeze(o.value)),o);return Is(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};jo.create=(t,e)=>new jo({innerType:t,typeName:N.ZodReadonly,...te(e)});bj={object:Lt.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"})(N||(N={}));xj=(t,e={message:`Input not instance of ${t.name}`})=>Kk(n=>n instanceof t,e),Gk=Dr.create,Jk=ko.create,Sj=Ls.create,vj=wo.create,Xk=Eo.create,kj=To.create,wj=Ns.create,Ej=$o.create,Tj=Po.create,$j=Mr.create,Pj=cr.create,Rj=xn.create,Cj=Ds.create,Oj=ur.create,Yf=Lt.create,Ij=Lt.strictCreate,Aj=Ro.create,Nj=xu.create,Dj=Co.create,Mj=Hn.create,jj=Su.create,Lj=Ms.create,zj=js.create,Hj=vu.create,Uj=Oo.create,Fj=Io.create,Bj=Ao.create,Zj=No.create,qj=jr.create,Vj=ln.create,Wj=jt.create,Kj=Un.create,Gj=ln.createWithPreprocess,Jj=ia.create,Xj=()=>Gk().optional(),Yj=()=>Jk().optional(),Qj=()=>Xk().optional(),e1={string:(t=>Dr.create({...t,coerce:!0})),number:(t=>ko.create({...t,coerce:!0})),boolean:(t=>Eo.create({...t,coerce:!0})),bigint:(t=>wo.create({...t,coerce:!0})),date:(t=>To.create({...t,coerce:!0}))},t1=G});var j={};_e(j,{BRAND:()=>_j,DIRTY:()=>vo,EMPTY_PATH:()=>JM,INVALID:()=>G,NEVER:()=>t1,OK:()=>xt,ParseStatus:()=>dt,Schema:()=>re,ZodAny:()=>Mr,ZodArray:()=>ur,ZodBigInt:()=>wo,ZodBoolean:()=>Eo,ZodBranded:()=>sa,ZodCatch:()=>Mo,ZodDate:()=>To,ZodDefault:()=>Do,ZodDiscriminatedUnion:()=>xu,ZodEffects:()=>ln,ZodEnum:()=>Ao,ZodError:()=>Mt,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>vu,ZodIntersection:()=>Co,ZodIssueCode:()=>I,ZodLazy:()=>Oo,ZodLiteral:()=>Io,ZodMap:()=>Ms,ZodNaN:()=>Ls,ZodNativeEnum:()=>No,ZodNever:()=>xn,ZodNull:()=>Po,ZodNullable:()=>Un,ZodNumber:()=>ko,ZodObject:()=>Lt,ZodOptional:()=>jt,ZodParsedType:()=>H,ZodPipeline:()=>ia,ZodPromise:()=>jr,ZodReadonly:()=>jo,ZodRecord:()=>Su,ZodSchema:()=>re,ZodSet:()=>js,ZodString:()=>Dr,ZodSymbol:()=>Ns,ZodTransformer:()=>ln,ZodTuple:()=>Hn,ZodType:()=>re,ZodUndefined:()=>$o,ZodUnion:()=>Ro,ZodUnknown:()=>cr,ZodVoid:()=>Ds,addIssueToContext:()=>M,any:()=>$j,array:()=>Oj,bigint:()=>vj,boolean:()=>Xk,coerce:()=>e1,custom:()=>Kk,date:()=>kj,datetimeRegex:()=>Vk,defaultErrorMap:()=>ir,discriminatedUnion:()=>Nj,effect:()=>Vj,enum:()=>Bj,function:()=>Hj,getErrorMap:()=>Os,getParsedType:()=>zn,instanceof:()=>xj,intersection:()=>Dj,isAborted:()=>_u,isAsync:()=>Is,isDirty:()=>bu,isValid:()=>Nr,late:()=>bj,lazy:()=>Uj,literal:()=>Fj,makeIssue:()=>oa,map:()=>Lj,nan:()=>Sj,nativeEnum:()=>Zj,never:()=>Rj,null:()=>Tj,nullable:()=>Kj,number:()=>Jk,object:()=>Yf,objectUtil:()=>Wf,oboolean:()=>Qj,onumber:()=>Yj,optional:()=>Wj,ostring:()=>Xj,pipeline:()=>Jj,preprocess:()=>Gj,promise:()=>qj,quotelessJson:()=>WM,record:()=>jj,set:()=>zj,setErrorMap:()=>GM,strictObject:()=>Ij,string:()=>Gk,symbol:()=>wj,transformer:()=>Vj,tuple:()=>Mj,undefined:()=>Ej,union:()=>Aj,unknown:()=>Pj,util:()=>ce,void:()=>Cj});var ku=x(()=>{yu();Gf();Hk();ra();Yk();gu()});var aa=x(()=>{ku()});function E(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Gt(t){return t&&Object.assign(wu,t),wu}var r1,lr,wu,zs=x(()=>{r1=Object.freeze({status:"aborted"});lr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},wu={}});var ue={};_e(ue,{BIGINT_FORMAT_RANGES:()=>ew,Class:()=>em,NUMBER_FORMAT_RANGES:()=>am,aborted:()=>zo,allowsEval:()=>om,assert:()=>c1,assertEqual:()=>o1,assertIs:()=>i1,assertNever:()=>a1,assertNotEqual:()=>s1,assignProp:()=>rm,cached:()=>la,captureStackTrace:()=>Tu,cleanEnum:()=>S1,cleanRegex:()=>pa,clone:()=>Jt,createTransparentProxy:()=>m1,defineLazy:()=>$e,esc:()=>Lo,escapeRegex:()=>Lr,extend:()=>y1,finalizeIssue:()=>Sn,floatSafeRemainder:()=>nm,getElementAtPath:()=>u1,getEnumValues:()=>ua,getLengthableOrigin:()=>fa,getParsedType:()=>f1,getSizableOrigin:()=>tw,isObject:()=>Hs,isPlainObject:()=>Us,issue:()=>cm,joinValues:()=>Eu,jsonStringifyReplacer:()=>tm,merge:()=>_1,normalizeParams:()=>J,nullish:()=>da,numKeys:()=>p1,omit:()=>g1,optionalKeys:()=>im,partial:()=>b1,pick:()=>h1,prefixIssues:()=>Fn,primitiveTypes:()=>Qk,promiseAllObject:()=>l1,propertyKeyTypes:()=>sm,randomString:()=>d1,required:()=>x1,stringifyPrimitive:()=>$u,unwrapMessage:()=>ca});function o1(t){return t}function s1(t){return t}function i1(t){}function a1(t){throw new Error}function c1(t){}function ua(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function Eu(t,e="|"){return t.map(n=>$u(n)).join(e)}function tm(t,e){return typeof e=="bigint"?e.toString():e}function la(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function da(t){return t==null}function pa(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function nm(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function $e(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function rm(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function u1(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function l1(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function d1(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Lo(t){return JSON.stringify(t)}function Hs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Us(t){if(Hs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Hs(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function p1(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Lr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jt(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function m1(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function $u(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function im(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function h1(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return Jt(t,{...t._zod.def,shape:n,checks:[]})}function g1(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return Jt(t,{...t._zod.def,shape:n,checks:[]})}function y1(t,e){if(!Us(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return rm(this,"shape",r),r},checks:[]};return Jt(t,n)}function _1(t,e){return Jt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return rm(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function b1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return Jt(e,{...e._zod.def,shape:o,checks:[]})}function x1(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return Jt(e,{...e._zod.def,shape:o,checks:[]})}function zo(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Fn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function ca(t){return typeof t=="string"?t:t?.message}function Sn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=ca(t.inst?._zod.def?.error?.(t))??ca(e?.error?.(t))??ca(n.customError?.(t))??ca(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function tw(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function fa(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function cm(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function S1(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Tu,om,f1,sm,Qk,am,ew,em,Bn=x(()=>{Tu=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};om=la(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});f1=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}`)}},sm=new Set(["string","number","symbol"]),Qk=new Set(["string","number","bigint","boolean","symbol","undefined"]);am={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]},ew={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};em=class{constructor(...e){}}});function um(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function lm(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var nw,Pu,ma,dm=x(()=>{zs();Bn();nw=(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,tm,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Pu=E("$ZodError",nw),ma=E("$ZodError",nw,{Parent:Error})});var pm,fm,mm,hm,gm,Ho,ym,Uo,_m=x(()=>{zs();dm();Bn();pm=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new lr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Sn(c,s,Gt())));throw Tu(a,o?.callee),a}return i.value},fm=pm(ma),mm=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Sn(c,s,Gt())));throw Tu(a,o?.callee),a}return i.value},hm=mm(ma),gm=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new lr;return s.issues.length?{success:!1,error:new(t??Pu)(s.issues.map(i=>Sn(i,o,Gt())))}:{success:!0,data:s.value}},Ho=gm(ma),ym=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Sn(i,o,Gt())))}:{success:!0,data:s.value}},Uo=ym(ma)});function pw(){return new RegExp(k1,"u")}function vw(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 kw(t){return new RegExp(`^${vw(t)}$`)}function ww(t){let e=vw({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${xw}T(?:${r})$`)}var rw,ow,sw,iw,aw,cw,uw,lw,bm,dw,k1,fw,mw,hw,gw,yw,xm,_w,bw,xw,Sw,Ew,Tw,$w,Pw,Rw,Cw,Ow,Cu=x(()=>{rw=/^[cC][^\s-]{8,}$/,ow=/^[0-9a-z]+$/,sw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iw=/^[0-9a-vA-V]{20}$/,aw=/^[A-Za-z0-9]{27}$/,cw=/^[a-zA-Z0-9_-]{21}$/,uw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,lw=/^([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})$/,bm=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)$/,dw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,k1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";fw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,mw=/^(([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})$/,hw=/^((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])$/,gw=/^(([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])$/,yw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xm=/^[A-Za-z0-9_-]*$/,_w=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,bw=/^\+(?:[0-9]){6,14}[0-9]$/,xw="(?:(?:\\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])))",Sw=new RegExp(`^${xw}$`);Ew=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Tw=/^\d+$/,$w=/^-?\d+(?:\.\d+)?/i,Pw=/true|false/i,Rw=/null/i,Cw=/^[^A-Z]*$/,Ow=/^[^a-z]*$/});var pt,Iw,Sm,vm,Aw,Nw,Dw,Mw,jw,ha,Lw,zw,Hw,Uw,Fw,Bw,Zw,Ou=x(()=>{zs();Cu();Bn();pt=E("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Iw={number:"number",bigint:"bigint",object:"date"},Sm=E("$ZodCheckLessThan",(t,e)=>{pt.init(t,e);let n=Iw[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),vm=E("$ZodCheckGreaterThan",(t,e)=>{pt.init(t,e);let n=Iw[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Aw=E("$ZodCheckMultipleOf",(t,e)=>{pt.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):nm(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Nw=E("$ZodCheckNumberFormat",(t,e)=>{pt.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=am[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=Tw)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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})}}),Dw=E("$ZodCheckMaxLength",(t,e)=>{var n;pt.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!da(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=fa(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Mw=E("$ZodCheckMinLength",(t,e)=>{var n;pt.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!da(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=fa(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),jw=E("$ZodCheckLengthEquals",(t,e)=>{var n;pt.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!da(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=fa(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ha=E("$ZodCheckStringFormat",(t,e)=>{var n,r;pt.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),Lw=E("$ZodCheckRegex",(t,e)=>{ha.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),zw=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Cw),ha.init(t,e)}),Hw=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ow),ha.init(t,e)}),Uw=E("$ZodCheckIncludes",(t,e)=>{pt.init(t,e);let n=Lr(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),Fw=E("$ZodCheckStartsWith",(t,e)=>{pt.init(t,e);let n=new RegExp(`^${Lr(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Bw=E("$ZodCheckEndsWith",(t,e)=>{pt.init(t,e);let n=new RegExp(`.*${Lr(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),Zw=E("$ZodCheckOverwrite",(t,e)=>{pt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var Iu,km=x(()=>{Iu=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 r=e.split(`
|
|
461
461
|
`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.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,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
|
|
462
|
-
`))}}});var
|
|
462
|
+
`))}}});var Vw,wm=x(()=>{Vw={major:4,minor:0,patch:0}});function iE(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function w1(t){if(!xm.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return iE(n)}function E1(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Ww(t,e,n){t.issues.length&&e.issues.push(...Fn(n,t.issues)),e.value[n]=t.value}function Au(t,e,n){t.issues.length&&e.issues.push(...Fn(n,t.issues)),e.value[n]=t.value}function Kw(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Fn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Gw(t,e,n,r){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:n,errors:t.map(o=>o.issues.map(s=>Sn(s,r,Gt())))}),e}function Em(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(Us(t)&&Us(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Em(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 n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=Em(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jw(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),zo(t))return t;let r=Em(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function Xw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Yw(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 Qw(t,e,n){return zo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function eE(t){return t.value=Object.freeze(t.value),t}function tE(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(cm(o))}}var we,ga,Pe,Tm,$m,Pm,Rm,Cm,Om,Im,Am,Nm,Dm,Mm,nE,rE,oE,sE,jm,Lm,zm,Hm,Um,Fm,Bm,Zm,Nu,qm,Vm,Wm,Km,Gm,Jm,Du,Mu,Xm,Ym,Qm,eh,th,nh,rh,oh,sh,ih,ah,ch,uh,lh,dh,aE=x(()=>{Ou();zs();km();_m();Cu();Bn();wm();Bn();we=E("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Vw;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=zo(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 lr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=zo(s,d)))});else{if(s.issues.length===d)continue;c||(c=zo(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 lr;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Ho(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Uo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ga=E("$ZodString",(t,e)=>{we.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ew(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Pe=E("$ZodStringFormat",(t,e)=>{ha.init(t,e),ga.init(t,e)}),Tm=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=lw),Pe.init(t,e)}),$m=E("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=bm(r))}else e.pattern??(e.pattern=bm());Pe.init(t,e)}),Pm=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=dw),Pe.init(t,e)}),Rm=E("$ZodURL",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_w.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Cm=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=pw()),Pe.init(t,e)}),Om=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=cw),Pe.init(t,e)}),Im=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=rw),Pe.init(t,e)}),Am=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ow),Pe.init(t,e)}),Nm=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=sw),Pe.init(t,e)}),Dm=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=iw),Pe.init(t,e)}),Mm=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=aw),Pe.init(t,e)}),nE=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ww(e)),Pe.init(t,e)}),rE=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sw),Pe.init(t,e)}),oE=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=kw(e)),Pe.init(t,e)}),sE=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=uw),Pe.init(t,e)}),jm=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=fw),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Lm=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=mw),Pe.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),zm=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=hw),Pe.init(t,e)}),Hm=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=gw),Pe.init(t,e),t._zod.check=n=>{let[r,o]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});Um=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=yw),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{iE(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});Fm=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xm),Pe.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{w1(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Bm=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=bw),Pe.init(t,e)});Zm=E("$ZodJWT",(t,e)=>{Pe.init(t,e),t._zod.check=n=>{E1(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Nu=E("$ZodNumber",(t,e)=>{we.init(t,e),t._zod.pattern=t._zod.bag.pattern??$w,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),qm=E("$ZodNumber",(t,e)=>{Nw.init(t,e),Nu.init(t,e)}),Vm=E("$ZodBoolean",(t,e)=>{we.init(t,e),t._zod.pattern=Pw,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),Wm=E("$ZodNull",(t,e)=>{we.init(t,e),t._zod.pattern=Rw,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),Km=E("$ZodUnknown",(t,e)=>{we.init(t,e),t._zod.parse=n=>n}),Gm=E("$ZodNever",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});Jm=E("$ZodArray",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.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:[]},r);c instanceof Promise?s.push(c.then(u=>Ww(u,n,i))):Ww(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});Du=E("$ZodObject",(t,e)=>{we.init(t,e);let n=la(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof we))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let p=im(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});$e(t._zod,"propValues",()=>{let d=e.shape,p={};for(let m in d){let f=d[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(let h of f.values)p[m].add(h)}}return p});let r=d=>{let p=new Iu(["shape","payload","ctx"]),m=n.value,f=_=>{let b=Lo(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of m.keys)h[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of m.keys)if(m.optionalKeys.has(_)){let b=h[_];p.write(`const ${b} = ${f(_)};`);let S=Lo(_);p.write(`
|
|
463
463
|
if (${b}.issues.length) {
|
|
464
464
|
if (input[${S}] === undefined) {
|
|
465
465
|
if (${S} in input) {
|
|
@@ -482,27 +482,27 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
|
|
|
482
482
|
if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
483
483
|
...iss,
|
|
484
484
|
path: iss.path ? [${Lo(_)}, ...iss.path] : [${Lo(_)}]
|
|
485
|
-
})));`),p.write(`newResult[${Lo(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,b)=>y(d,_,b)},o,s=Hs,i=!Su.jitless,c=i&&nm.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let b=l.shape;for(let S of l.keys){let T=b[S],D=T._zod.run({value:m[S],issues:[]},p),v=T._zod.optin==="optional"&&T._zod.optout==="optional";D instanceof Promise?f.push(D.then($=>v?Bw($,d,S,m):Cu($,d,S))):v?Bw(D,d,S,m):Cu(D,d,S)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(m)){if(g.has(b))continue;if(_==="never"){h.push(b);continue}let S=y.run({value:m[b],issues:[]},p);S instanceof Promise?f.push(S.then(T=>Cu(T,d,b))):Cu(S,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Au=E("$ZodUnion",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),$e(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),$e(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),$e(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>ua(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>Zw(i,n,t,r)):Zw(s,n,t,r)}}),Gm=E("$ZodDiscriminatedUnion",(t,e)=>{Au.init(t,e);let n=t._zod.parse;$e(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 r=aa(()=>{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(!Hs(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Jm=E("$ZodIntersection",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>qw(n,c,u)):qw(n,s,i)}});Xm=E("$ZodRecord",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Us(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Fn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Fn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>xn(u,r,Wt())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Fn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Fn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Ym=E("$ZodEnum",(t,e)=>{we.init(t,e);let n=ia(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>rm.has(typeof r)).map(r=>typeof r=="string"?zr(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Qm=E("$ZodLiteral",(t,e)=>{we.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?zr(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),eh=E("$ZodTransform",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new lr;return n.value=o,n}}),th=E("$ZodOptional",(t,e)=>{we.init(t,e),t._zod.optin="optional",t._zod.optout="optional",$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ua(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),nh=E("$ZodNullable",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${ua(n.source)}|null)$`):void 0}),$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),rh=E("$ZodDefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Vw(s,e)):Vw(o,e)}});oh=E("$ZodPrefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),sh=E("$ZodNonOptional",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Ww(s,t)):Ww(o,t)}});ih=E("$ZodCatch",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>xn(i,r,Wt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>xn(s,r,Wt()))},input:n.value}),n.issues=[]),n)}}),ah=E("$ZodPipe",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>e.in._zod.values),$e(t._zod,"optin",()=>e.in._zod.optin),$e(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Kw(s,e,r)):Kw(o,e,r)}});ch=E("$ZodReadonly",(t,e)=>{we.init(t,e),$e(t._zod,"propValues",()=>e.innerType._zod.propValues),$e(t._zod,"values",()=>e.innerType._zod.values),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(Gw):Gw(o)}});uh=E("$ZodCustom",(t,e)=>{ut.init(t,e),we.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>Jw(s,n,r,t));Jw(o,n,r,t)}})});function rE(){return{localeError:k1()}}var v1,k1,oE=x(()=>{Bn();v1=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},k1=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${v1(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${wu(r.values[0])}`:`Invalid option: expected one of ${vu(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${vu(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var Nu=x(()=>{});function sE(){return new ma}var ma,Hr,dh=x(()=>{ma=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Hr=sE()});function ph(t,e){return new t({type:"string",...J(e)})}function fh(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function Du(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function mh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function hh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function gh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function yh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function _h(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function bh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function xh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function Sh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function vh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function kh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function wh(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function Eh(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function Th(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function $h(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function Ph(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function Rh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function Ch(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function Oh(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function Ih(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function Ah(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function iE(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function aE(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function cE(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function uE(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function Nh(t,e){return new t({type:"number",checks:[],...J(e)})}function Dh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function Mh(t,e){return new t({type:"boolean",...J(e)})}function jh(t,e){return new t({type:"null",...J(e)})}function Lh(t){return new t({type:"unknown"})}function zh(t,e){return new t({type:"never",...J(e)})}function Mu(t,e){return new bm({check:"less_than",...J(e),value:t,inclusive:!1})}function ha(t,e){return new bm({check:"less_than",...J(e),value:t,inclusive:!0})}function ju(t,e){return new xm({check:"greater_than",...J(e),value:t,inclusive:!1})}function ga(t,e){return new xm({check:"greater_than",...J(e),value:t,inclusive:!0})}function Lu(t,e){return new Pw({check:"multiple_of",...J(e),value:t})}function zu(t,e){return new Cw({check:"max_length",...J(e),maximum:t})}function Fs(t,e){return new Ow({check:"min_length",...J(e),minimum:t})}function Hu(t,e){return new Iw({check:"length_equals",...J(e),length:t})}function Hh(t,e){return new Aw({check:"string_format",format:"regex",...J(e),pattern:t})}function Uh(t){return new Nw({check:"string_format",format:"lowercase",...J(t)})}function Fh(t){return new Dw({check:"string_format",format:"uppercase",...J(t)})}function Bh(t,e){return new Mw({check:"string_format",format:"includes",...J(e),includes:t})}function Zh(t,e){return new jw({check:"string_format",format:"starts_with",...J(e),prefix:t})}function qh(t,e){return new Lw({check:"string_format",format:"ends_with",...J(e),suffix:t})}function Fo(t){return new zw({check:"overwrite",tx:t})}function Vh(t){return Fo(e=>e.normalize(t))}function Wh(){return Fo(t=>t.trim())}function Kh(){return Fo(t=>t.toLowerCase())}function Gh(){return Fo(t=>t.toUpperCase())}function lE(t,e,n){return new t({type:"array",element:e,...J(n)})}function Jh(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Xh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var dE=x(()=>{Pu();Bn()});var pE=x(()=>{});function Yh(t,e){if(t instanceof ma){let r=new Uu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Uu(e);return n.process(t),n.emit(t,e)}function tt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 tt(o.element,n);case"object":{for(let s in o.shape)if(tt(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(tt(s,n))return!0;return!1}case"intersection":return tt(o.left,n)||tt(o.right,n);case"tuple":{for(let s of o.items)if(tt(s,n))return!0;return!!(o.rest&&tt(o.rest,n))}case"record":return tt(o.keyType,n)||tt(o.valueType,n);case"map":return tt(o.keyType,n)||tt(o.valueType,n);case"set":return tt(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return tt(o.innerType,n);case"lazy":return tt(o.getter(),n);case"default":return tt(o.innerType,n);case"prefault":return tt(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return tt(o.in,n)||tt(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Uu,fE=x(()=>{dh();Bn();Uu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Hr,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof g=="number"&&(f.maxLength=g),y&&(f.format=s[y]??y,f.format===""&&delete f.format),b&&(f.contentEncoding=b),_&&_.size>0){let S=[..._];S.length===1?f.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{let f=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?f.type="integer":f.type="number",typeof S=="number"&&(f.exclusiveMinimum=S),typeof h=="number"&&(f.minimum=h,typeof S=="number"&&(S>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof b=="number"&&(f.exclusiveMaximum=b),typeof g=="number"&&(f.maximum=g,typeof b=="number"&&(b<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof _=="number"&&(f.multipleOf=_);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let _ in h)f.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),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&&(f.required=Array.from(y)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let f=m,h=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(h)?h.allOf:[h],...y(g)?g.allOf:[g]];f.allOf=_;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=_:f.additionalItems=_}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof y=="number"&&(f.maxItems=y);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=ia(o.entries);h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];f.type=g===null?"null":typeof g,f.const=g}else h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),h.every(g=>typeof g=="boolean")&&(f.type="string"),h.every(g=>g===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(f,h)):f.anyOf=_.map(b=>({...h,contentMediaType:b})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&tt(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(h)return{ref:g(h)};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 m=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let h in f)delete f[h];f.$ref=p};if(r.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>
|
|
485
|
+
})));`),p.write(`newResult[${Lo(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,b)=>y(d,_,b)},o,s=Hs,i=!wu.jitless,c=i&&om.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=n.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let f=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=r(e.shape)),d=o(d,p);else{d.value={};let b=l.shape;for(let S of l.keys){let T=b[S],D=T._zod.run({value:m[S],issues:[]},p),v=T._zod.optin==="optional"&&T._zod.optout==="optional";D instanceof Promise?f.push(D.then($=>v?Kw($,d,S,m):Au($,d,S))):v?Kw(D,d,S,m):Au(D,d,S)}}if(!u)return f.length?Promise.all(f).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(m)){if(g.has(b))continue;if(_==="never"){h.push(b);continue}let S=y.run({value:m[b],issues:[]},p);S instanceof Promise?f.push(S.then(T=>Au(T,d,b))):Au(S,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),f.length?Promise.all(f).then(()=>d):d}});Mu=E("$ZodUnion",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),$e(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),$e(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),$e(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>pa(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>Gw(i,n,t,r)):Gw(s,n,t,r)}}),Xm=E("$ZodDiscriminatedUnion",(t,e)=>{Mu.init(t,e);let n=t._zod.parse;$e(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 r=la(()=>{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(!Hs(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Ym=E("$ZodIntersection",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Jw(n,c,u)):Jw(n,s,i)}});Qm=E("$ZodRecord",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Us(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...Fn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...Fn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Sn(u,r,Gt())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...Fn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...Fn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),eh=E("$ZodEnum",(t,e)=>{we.init(t,e);let n=ua(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>sm.has(typeof r)).map(r=>typeof r=="string"?Lr(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),th=E("$ZodLiteral",(t,e)=>{we.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Lr(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),nh=E("$ZodTransform",(t,e)=>{we.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new lr;return n.value=o,n}}),rh=E("$ZodOptional",(t,e)=>{we.init(t,e),t._zod.optin="optional",t._zod.optout="optional",$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${pa(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),oh=E("$ZodNullable",(t,e)=>{we.init(t,e),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${pa(n.source)}|null)$`):void 0}),$e(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),sh=E("$ZodDefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Xw(s,e)):Xw(o,e)}});ih=E("$ZodPrefault",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),ah=E("$ZodNonOptional",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Yw(s,t)):Yw(o,t)}});ch=E("$ZodCatch",(t,e)=>{we.init(t,e),t._zod.optin="optional",$e(t._zod,"optout",()=>e.innerType._zod.optout),$e(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Sn(i,r,Gt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>Sn(s,r,Gt()))},input:n.value}),n.issues=[]),n)}}),uh=E("$ZodPipe",(t,e)=>{we.init(t,e),$e(t._zod,"values",()=>e.in._zod.values),$e(t._zod,"optin",()=>e.in._zod.optin),$e(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Qw(s,e,r)):Qw(o,e,r)}});lh=E("$ZodReadonly",(t,e)=>{we.init(t,e),$e(t._zod,"propValues",()=>e.innerType._zod.propValues),$e(t._zod,"values",()=>e.innerType._zod.values),$e(t._zod,"optin",()=>e.innerType._zod.optin),$e(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(eE):eE(o)}});dh=E("$ZodCustom",(t,e)=>{pt.init(t,e),we.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>tE(s,n,r,t));tE(o,n,r,t)}})});function cE(){return{localeError:$1()}}var T1,$1,uE=x(()=>{Bn();T1=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},$1=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${T1(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${$u(r.values[0])}`:`Invalid option: expected one of ${Eu(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Eu(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});var ju=x(()=>{});function lE(){return new ya}var ya,zr,fh=x(()=>{ya=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};zr=lE()});function mh(t,e){return new t({type:"string",...J(e)})}function hh(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function Lu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function gh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function yh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function _h(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function bh(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function xh(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function Sh(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function vh(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function kh(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function wh(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function Eh(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function Th(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function $h(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function Ph(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function Rh(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function Ch(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function Oh(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function Ih(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function Ah(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function Nh(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function Dh(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function dE(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function pE(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function fE(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function mE(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function Mh(t,e){return new t({type:"number",checks:[],...J(e)})}function jh(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function Lh(t,e){return new t({type:"boolean",...J(e)})}function zh(t,e){return new t({type:"null",...J(e)})}function Hh(t){return new t({type:"unknown"})}function Uh(t,e){return new t({type:"never",...J(e)})}function zu(t,e){return new Sm({check:"less_than",...J(e),value:t,inclusive:!1})}function _a(t,e){return new Sm({check:"less_than",...J(e),value:t,inclusive:!0})}function Hu(t,e){return new vm({check:"greater_than",...J(e),value:t,inclusive:!1})}function ba(t,e){return new vm({check:"greater_than",...J(e),value:t,inclusive:!0})}function Uu(t,e){return new Aw({check:"multiple_of",...J(e),value:t})}function Fu(t,e){return new Dw({check:"max_length",...J(e),maximum:t})}function Fs(t,e){return new Mw({check:"min_length",...J(e),minimum:t})}function Bu(t,e){return new jw({check:"length_equals",...J(e),length:t})}function Fh(t,e){return new Lw({check:"string_format",format:"regex",...J(e),pattern:t})}function Bh(t){return new zw({check:"string_format",format:"lowercase",...J(t)})}function Zh(t){return new Hw({check:"string_format",format:"uppercase",...J(t)})}function qh(t,e){return new Uw({check:"string_format",format:"includes",...J(e),includes:t})}function Vh(t,e){return new Fw({check:"string_format",format:"starts_with",...J(e),prefix:t})}function Wh(t,e){return new Bw({check:"string_format",format:"ends_with",...J(e),suffix:t})}function Fo(t){return new Zw({check:"overwrite",tx:t})}function Kh(t){return Fo(e=>e.normalize(t))}function Gh(){return Fo(t=>t.trim())}function Jh(){return Fo(t=>t.toLowerCase())}function Xh(){return Fo(t=>t.toUpperCase())}function hE(t,e,n){return new t({type:"array",element:e,...J(n)})}function Yh(t,e,n){let r=J(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Qh(t,e,n){return new t({type:"custom",check:"custom",fn:e,...J(n)})}var gE=x(()=>{Ou();Bn()});var yE=x(()=>{});function eg(t,e){if(t instanceof ya){let r=new Zu(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new Zu(e);return n.process(t),n.emit(t,e)}function nt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 nt(o.element,n);case"object":{for(let s in o.shape)if(nt(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(nt(s,n))return!0;return!1}case"intersection":return nt(o.left,n)||nt(o.right,n);case"tuple":{for(let s of o.items)if(nt(s,n))return!0;return!!(o.rest&&nt(o.rest,n))}case"record":return nt(o.keyType,n)||nt(o.valueType,n);case"map":return nt(o.keyType,n)||nt(o.valueType,n);case"set":return nt(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return nt(o.innerType,n);case"lazy":return nt(o.getter(),n);case"default":return nt(o.innerType,n);case"prefault":return nt(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return nt(o.in,n)||nt(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Zu,_E=x(()=>{fh();Bn();Zu=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??zr,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof g=="number"&&(f.maxLength=g),y&&(f.format=s[y]??y,f.format===""&&delete f.format),b&&(f.contentEncoding=b),_&&_.size>0){let S=[..._];S.length===1?f.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{let f=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?f.type="integer":f.type="number",typeof S=="number"&&(f.exclusiveMinimum=S),typeof h=="number"&&(f.minimum=h,typeof S=="number"&&(S>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof b=="number"&&(f.exclusiveMaximum=b),typeof g=="number"&&(f.maximum=g,typeof b=="number"&&(b<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof _=="number"&&(f.multipleOf=_);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=o.shape;for(let _ in h)f.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),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&&(f.required=Array.from(y)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let f=m,h=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(h)?h.allOf:[h],...y(g)?g.allOf:[g]];f.allOf=_;break}case"tuple":{let f=m;f.type="array";let h=o.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?f.items=_:f.additionalItems=_}o.rest&&(f.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof y=="number"&&(f.maxItems=y);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=ua(o.entries);h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];f.type=g===null?"null":typeof g,f.const=g}else h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),h.every(g=>typeof g=="boolean")&&(f.type="string"),h.every(g=>g===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(f,h)):f.anyOf=_.map(b=>({...h,contentMediaType:b})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,d);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,d),a.ref=f;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,d),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&nt(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(h)return{ref:g(h)};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 m=`#/${d}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let f=d.schema;for(let h in f)delete f[h];f.$ref=p};if(r.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>
|
|
486
486
|
|
|
487
|
-
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(r.external){let m=r.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,f))}p.isParent||this.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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
|
|
488
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function vE(t){return t.description}function kE(t){if(Zn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Zs(t){if(Zn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var ya=x(()=>{oa();tg()});var ng=x(()=>{Et()});var _a={};_e(_a,{ZodISODate:()=>EE,ZodISODateTime:()=>wE,ZodISODuration:()=>$E,ZodISOTime:()=>TE,date:()=>og,datetime:()=>rg,duration:()=>ig,time:()=>sg});function rg(t){return iE(wE,t)}function og(t){return aE(EE,t)}function sg(t){return cE(TE,t)}function ig(t){return uE($E,t)}var wE,EE,TE,$E,ag=x(()=>{Et();cg();wE=E("ZodISODateTime",(t,e)=>{Xw.init(t,e),Ne.init(t,e)});EE=E("ZodISODate",(t,e)=>{Yw.init(t,e),Ne.init(t,e)});TE=E("ZodISOTime",(t,e)=>{Qw.init(t,e),Ne.init(t,e)});$E=E("ZodISODuration",(t,e)=>{eE.init(t,e),Ne.init(t,e)})});var PE,uJ,ba,ug=x(()=>{Et();Et();PE=(t,e)=>{Eu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>cm(t,n)},flatten:{value:n=>am(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},uJ=E("ZodError",PE),ba=E("ZodError",PE,{Parent:Error})});var RE,CE,OE,IE,lg=x(()=>{Et();ug();RE=lm(ba),CE=pm(ba),OE=mm(ba),IE=hm(ba)});function w(t){return ph(gL,t)}function ye(t){return Nh(jE,t)}function NE(t){return Dh(NL,t)}function st(t){return Mh(DL,t)}function LE(t){return jh(ML,t)}function De(){return Lh(jL)}function zL(t){return zh(LL,t)}function le(t,e){return lE(HL,t,e)}function U(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new zE(n)}function Tt(t,e){return new zE({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Oe(t,e){return new HE({type:"union",options:t,...ue.normalizeParams(e)})}function fg(t,e,n){return new UL({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function qu(t,e){return new FL({type:"intersection",left:t,right:e})}function Re(t,e,n){return new BL({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function jt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new dg({type:"enum",entries:n,...ue.normalizeParams(e)})}function V(t,e){return new ZL({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function UE(t){return new qL({type:"transform",transform:t})}function Me(t){return new FE({type:"optional",innerType:t})}function DE(t){return new VL({type:"nullable",innerType:t})}function KL(t,e){return new WL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function JL(t,e){return new GL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function XL(t,e){return new BE({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function QL(t,e){return new YL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function pg(t,e){return new ez({type:"pipe",in:t,out:e})}function nz(t){return new tz({type:"readonly",innerType:t})}function rz(t){let e=new ut({check:"custom"});return e._zod.check=t,e}function qE(t,e){return Jh(ZE,t??(()=>!0),e)}function oz(t,e={}){return Xh(ZE,t,e)}function sz(t){let e=rz(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function mg(t,e){return pg(UE(t),e)}var Ue,ME,gL,Ne,yL,AE,Zu,_L,bL,xL,SL,vL,kL,wL,EL,TL,$L,PL,RL,CL,OL,IL,AL,jE,NL,DL,ML,jL,LL,HL,zE,HE,UL,FL,BL,dg,ZL,qL,FE,VL,WL,GL,BE,YL,ez,tz,ZE,cg=x(()=>{Et();Et();ng();ag();lg();Ue=E("ZodType",(t,e)=>(we.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Kt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>RE(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>OE(t,n,r),t.parseAsync=async(n,r)=>CE(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>IE(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(oz(n,r)),t.superRefine=n=>t.check(sz(n)),t.overwrite=n=>t.check(Fo(n)),t.optional=()=>Me(t),t.nullable=()=>DE(t),t.nullish=()=>Me(DE(t)),t.nonoptional=n=>XL(t,n),t.array=()=>le(t),t.or=n=>Oe([t,n]),t.and=n=>qu(t,n),t.transform=n=>pg(t,UE(n)),t.default=n=>KL(t,n),t.prefault=n=>JL(t,n),t.catch=n=>QL(t,n),t.pipe=n=>pg(t,n),t.readonly=()=>nz(t),t.describe=n=>{let r=t.clone();return Hr.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Hr.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Hr.get(t);let r=t.clone();return Hr.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ME=E("_ZodString",(t,e)=>{fa.init(t,e),Ue.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Hh(...r)),t.includes=(...r)=>t.check(Bh(...r)),t.startsWith=(...r)=>t.check(Zh(...r)),t.endsWith=(...r)=>t.check(qh(...r)),t.min=(...r)=>t.check(Fs(...r)),t.max=(...r)=>t.check(zu(...r)),t.length=(...r)=>t.check(Hu(...r)),t.nonempty=(...r)=>t.check(Fs(1,...r)),t.lowercase=r=>t.check(Uh(r)),t.uppercase=r=>t.check(Fh(r)),t.trim=()=>t.check(Wh()),t.normalize=(...r)=>t.check(Vh(...r)),t.toLowerCase=()=>t.check(Kh()),t.toUpperCase=()=>t.check(Gh())}),gL=E("ZodString",(t,e)=>{fa.init(t,e),ME.init(t,e),t.email=n=>t.check(fh(yL,n)),t.url=n=>t.check(_h(_L,n)),t.jwt=n=>t.check(Ah(AL,n)),t.emoji=n=>t.check(bh(bL,n)),t.guid=n=>t.check(Du(AE,n)),t.uuid=n=>t.check(mh(Zu,n)),t.uuidv4=n=>t.check(hh(Zu,n)),t.uuidv6=n=>t.check(gh(Zu,n)),t.uuidv7=n=>t.check(yh(Zu,n)),t.nanoid=n=>t.check(xh(xL,n)),t.guid=n=>t.check(Du(AE,n)),t.cuid=n=>t.check(Sh(SL,n)),t.cuid2=n=>t.check(vh(vL,n)),t.ulid=n=>t.check(kh(kL,n)),t.base64=n=>t.check(Ch(CL,n)),t.base64url=n=>t.check(Oh(OL,n)),t.xid=n=>t.check(wh(wL,n)),t.ksuid=n=>t.check(Eh(EL,n)),t.ipv4=n=>t.check(Th(TL,n)),t.ipv6=n=>t.check($h($L,n)),t.cidrv4=n=>t.check(Ph(PL,n)),t.cidrv6=n=>t.check(Rh(RL,n)),t.e164=n=>t.check(Ih(IL,n)),t.datetime=n=>t.check(rg(n)),t.date=n=>t.check(og(n)),t.time=n=>t.check(sg(n)),t.duration=n=>t.check(ig(n))});Ne=E("ZodStringFormat",(t,e)=>{Pe.init(t,e),ME.init(t,e)}),yL=E("ZodEmail",(t,e)=>{Tm.init(t,e),Ne.init(t,e)}),AE=E("ZodGUID",(t,e)=>{wm.init(t,e),Ne.init(t,e)}),Zu=E("ZodUUID",(t,e)=>{Em.init(t,e),Ne.init(t,e)}),_L=E("ZodURL",(t,e)=>{$m.init(t,e),Ne.init(t,e)}),bL=E("ZodEmoji",(t,e)=>{Pm.init(t,e),Ne.init(t,e)}),xL=E("ZodNanoID",(t,e)=>{Rm.init(t,e),Ne.init(t,e)}),SL=E("ZodCUID",(t,e)=>{Cm.init(t,e),Ne.init(t,e)}),vL=E("ZodCUID2",(t,e)=>{Om.init(t,e),Ne.init(t,e)}),kL=E("ZodULID",(t,e)=>{Im.init(t,e),Ne.init(t,e)}),wL=E("ZodXID",(t,e)=>{Am.init(t,e),Ne.init(t,e)}),EL=E("ZodKSUID",(t,e)=>{Nm.init(t,e),Ne.init(t,e)}),TL=E("ZodIPv4",(t,e)=>{Dm.init(t,e),Ne.init(t,e)}),$L=E("ZodIPv6",(t,e)=>{Mm.init(t,e),Ne.init(t,e)}),PL=E("ZodCIDRv4",(t,e)=>{jm.init(t,e),Ne.init(t,e)}),RL=E("ZodCIDRv6",(t,e)=>{Lm.init(t,e),Ne.init(t,e)}),CL=E("ZodBase64",(t,e)=>{zm.init(t,e),Ne.init(t,e)}),OL=E("ZodBase64URL",(t,e)=>{Hm.init(t,e),Ne.init(t,e)}),IL=E("ZodE164",(t,e)=>{Um.init(t,e),Ne.init(t,e)}),AL=E("ZodJWT",(t,e)=>{Fm.init(t,e),Ne.init(t,e)}),jE=E("ZodNumber",(t,e)=>{Ou.init(t,e),Ue.init(t,e),t.gt=(r,o)=>t.check(ju(r,o)),t.gte=(r,o)=>t.check(ga(r,o)),t.min=(r,o)=>t.check(ga(r,o)),t.lt=(r,o)=>t.check(Mu(r,o)),t.lte=(r,o)=>t.check(ha(r,o)),t.max=(r,o)=>t.check(ha(r,o)),t.int=r=>t.check(NE(r)),t.safe=r=>t.check(NE(r)),t.positive=r=>t.check(ju(0,r)),t.nonnegative=r=>t.check(ga(0,r)),t.negative=r=>t.check(Mu(0,r)),t.nonpositive=r=>t.check(ha(0,r)),t.multipleOf=(r,o)=>t.check(Lu(r,o)),t.step=(r,o)=>t.check(Lu(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});NL=E("ZodNumberFormat",(t,e)=>{Bm.init(t,e),jE.init(t,e)});DL=E("ZodBoolean",(t,e)=>{Zm.init(t,e),Ue.init(t,e)});ML=E("ZodNull",(t,e)=>{qm.init(t,e),Ue.init(t,e)});jL=E("ZodUnknown",(t,e)=>{Vm.init(t,e),Ue.init(t,e)});LL=E("ZodNever",(t,e)=>{Wm.init(t,e),Ue.init(t,e)});HL=E("ZodArray",(t,e)=>{Km.init(t,e),Ue.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Fs(n,r)),t.nonempty=n=>t.check(Fs(1,n)),t.max=(n,r)=>t.check(zu(n,r)),t.length=(n,r)=>t.check(Hu(n,r)),t.unwrap=()=>t.element});zE=E("ZodObject",(t,e)=>{Iu.init(t,e),Ue.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>jt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:zL()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(FE,t,n[0]),t.required=(...n)=>ue.required(BE,t,n[0])});HE=E("ZodUnion",(t,e)=>{Au.init(t,e),Ue.init(t,e),t.options=e.options});UL=E("ZodDiscriminatedUnion",(t,e)=>{HE.init(t,e),Gm.init(t,e)});FL=E("ZodIntersection",(t,e)=>{Jm.init(t,e),Ue.init(t,e)});BL=E("ZodRecord",(t,e)=>{Xm.init(t,e),Ue.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});dg=E("ZodEnum",(t,e)=>{Ym.init(t,e),Ue.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new dg({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new dg({...e,checks:[],...ue.normalizeParams(o),entries:s})}});ZL=E("ZodLiteral",(t,e)=>{Qm.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]}})});qL=E("ZodTransform",(t,e)=>{eh.init(t,e),Ue.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});FE=E("ZodOptional",(t,e)=>{th.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});VL=E("ZodNullable",(t,e)=>{nh.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});WL=E("ZodDefault",(t,e)=>{rh.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});GL=E("ZodPrefault",(t,e)=>{oh.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});BE=E("ZodNonOptional",(t,e)=>{sh.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType});YL=E("ZodCatch",(t,e)=>{ih.init(t,e),Ue.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});ez=E("ZodPipe",(t,e)=>{ah.init(t,e),Ue.init(t,e),t.in=e.in,t.out=e.out});tz=E("ZodReadonly",(t,e)=>{ch.init(t,e),Ue.init(t,e)});ZE=E("ZodCustom",(t,e)=>{uh.init(t,e),Ue.init(t,e)})});var VE=x(()=>{});var WE=x(()=>{});var KE=x(()=>{Et();cg();ng();ug();lg();VE();Et();oE();Nu();ag();WE();Wt(rE())});var GE=x(()=>{KE()});var JE=x(()=>{GE()});function f0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function m0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var gg,XE,Br,Wu,nt,YE,QE,EJ,cz,uz,yg,Gt,xa,e0,lt,un,ln,dt,Ku,t0,_g,n0,r0,bg,Sa,K,xg,o0,s0,TJ,Gu,lz,Ju,dz,va,qs,i0,pz,fz,mz,hz,gz,yz,Sg,_z,bz,vg,Xu,xz,Sz,Yu,vz,ka,wa,kz,Ea,Vs,wz,Ta,Qu,el,tl,$J,nl,rl,ol,a0,c0,u0,kg,l0,$a,Ws,d0,Ez,Ks,Tz,Gs,$z,wg,Pz,sl,Rz,Cz,Oz,Iz,Az,Nz,Dz,Mz,jz,Lz,Js,zz,Hz,il,Eg,Tg,$g,Uz,Fz,Bz,Pg,Zz,qz,Vz,Wz,Kz,p0,qo,Gz,al,PJ,Jz,Xs,Xz,RJ,Pa,Yz,Rg,Qz,eH,tH,nH,rH,oH,sH,Vu,iH,aH,cH,Ra,Cg,uH,lH,dH,pH,fH,mH,hH,gH,yH,_H,bH,xH,SH,vH,kH,wH,EH,TH,Ys,$H,PH,RH,cl,CH,OH,IH,Og,AH,CJ,OJ,IJ,AJ,NJ,DJ,q,hg,Vo=x(()=>{JE();gg="2025-11-25",XE=[gg,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Br="io.modelcontextprotocol/related-task",Wu="2.0",nt=qE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),YE=Oe([w(),ye().int()]),QE=w(),EJ=Tt({ttl:ye().optional(),pollInterval:ye().optional()}),cz=U({ttl:ye().optional()}),uz=U({taskId:w()}),yg=Tt({progressToken:YE.optional(),[Br]:uz.optional()}),Gt=U({_meta:yg.optional()}),xa=Gt.extend({task:cz.optional()}),e0=t=>xa.safeParse(t).success,lt=U({method:w(),params:Gt.loose().optional()}),un=U({_meta:yg.optional()}),ln=U({method:w(),params:un.loose().optional()}),dt=Tt({_meta:yg.optional()}),Ku=Oe([w(),ye().int()]),t0=U({jsonrpc:V(Wu),id:Ku,...lt.shape}).strict(),_g=t=>t0.safeParse(t).success,n0=U({jsonrpc:V(Wu),...ln.shape}).strict(),r0=t=>n0.safeParse(t).success,bg=U({jsonrpc:V(Wu),id:Ku,result:dt}).strict(),Sa=t=>bg.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"})(K||(K={}));xg=U({jsonrpc:V(Wu),id:Ku.optional(),error:U({code:ye().int(),message:w(),data:De().optional()})}).strict(),o0=t=>xg.safeParse(t).success,s0=Oe([t0,n0,bg,xg]),TJ=Oe([bg,xg]),Gu=dt.strict(),lz=un.extend({requestId:Ku.optional(),reason:w().optional()}),Ju=ln.extend({method:V("notifications/cancelled"),params:lz}),dz=U({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:jt(["light","dark"]).optional()}),va=U({icons:le(dz).optional()}),qs=U({name:w(),title:w().optional()}),i0=qs.extend({...qs.shape,...va.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),pz=qu(U({applyDefaults:st().optional()}),Re(w(),De())),fz=mg(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,qu(U({form:pz.optional(),url:nt.optional()}),Re(w(),De()).optional())),mz=Tt({list:nt.optional(),cancel:nt.optional(),requests:Tt({sampling:Tt({createMessage:nt.optional()}).optional(),elicitation:Tt({create:nt.optional()}).optional()}).optional()}),hz=Tt({list:nt.optional(),cancel:nt.optional(),requests:Tt({tools:Tt({call:nt.optional()}).optional()}).optional()}),gz=U({experimental:Re(w(),nt).optional(),sampling:U({context:nt.optional(),tools:nt.optional()}).optional(),elicitation:fz.optional(),roots:U({listChanged:st().optional()}).optional(),tasks:mz.optional(),extensions:Re(w(),nt).optional()}),yz=Gt.extend({protocolVersion:w(),capabilities:gz,clientInfo:i0}),Sg=lt.extend({method:V("initialize"),params:yz}),_z=U({experimental:Re(w(),nt).optional(),logging:nt.optional(),completions:nt.optional(),prompts:U({listChanged:st().optional()}).optional(),resources:U({subscribe:st().optional(),listChanged:st().optional()}).optional(),tools:U({listChanged:st().optional()}).optional(),tasks:hz.optional(),extensions:Re(w(),nt).optional()}),bz=dt.extend({protocolVersion:w(),capabilities:_z,serverInfo:i0,instructions:w().optional()}),vg=ln.extend({method:V("notifications/initialized"),params:un.optional()}),Xu=lt.extend({method:V("ping"),params:Gt.optional()}),xz=U({progress:ye(),total:Me(ye()),message:Me(w())}),Sz=U({...un.shape,...xz.shape,progressToken:YE}),Yu=ln.extend({method:V("notifications/progress"),params:Sz}),vz=Gt.extend({cursor:QE.optional()}),ka=lt.extend({params:vz.optional()}),wa=dt.extend({nextCursor:QE.optional()}),kz=jt(["working","input_required","completed","failed","cancelled"]),Ea=U({taskId:w(),status:kz,ttl:Oe([ye(),LE()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Me(ye()),statusMessage:Me(w())}),Vs=dt.extend({task:Ea}),wz=un.merge(Ea),Ta=ln.extend({method:V("notifications/tasks/status"),params:wz}),Qu=lt.extend({method:V("tasks/get"),params:Gt.extend({taskId:w()})}),el=dt.merge(Ea),tl=lt.extend({method:V("tasks/result"),params:Gt.extend({taskId:w()})}),$J=dt.loose(),nl=ka.extend({method:V("tasks/list")}),rl=wa.extend({tasks:le(Ea)}),ol=lt.extend({method:V("tasks/cancel"),params:Gt.extend({taskId:w()})}),a0=dt.merge(Ea),c0=U({uri:w(),mimeType:Me(w()),_meta:Re(w(),De()).optional()}),u0=c0.extend({text:w()}),kg=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),l0=c0.extend({blob:kg}),$a=jt(["user","assistant"]),Ws=U({audience:le($a).optional(),priority:ye().min(0).max(1).optional(),lastModified:_a.datetime({offset:!0}).optional()}),d0=U({...qs.shape,...va.shape,uri:w(),description:Me(w()),mimeType:Me(w()),size:Me(ye()),annotations:Ws.optional(),_meta:Me(Tt({}))}),Ez=U({...qs.shape,...va.shape,uriTemplate:w(),description:Me(w()),mimeType:Me(w()),annotations:Ws.optional(),_meta:Me(Tt({}))}),Ks=ka.extend({method:V("resources/list")}),Tz=wa.extend({resources:le(d0)}),Gs=ka.extend({method:V("resources/templates/list")}),$z=wa.extend({resourceTemplates:le(Ez)}),wg=Gt.extend({uri:w()}),Pz=wg,sl=lt.extend({method:V("resources/read"),params:Pz}),Rz=dt.extend({contents:le(Oe([u0,l0]))}),Cz=ln.extend({method:V("notifications/resources/list_changed"),params:un.optional()}),Oz=wg,Iz=lt.extend({method:V("resources/subscribe"),params:Oz}),Az=wg,Nz=lt.extend({method:V("resources/unsubscribe"),params:Az}),Dz=un.extend({uri:w()}),Mz=ln.extend({method:V("notifications/resources/updated"),params:Dz}),jz=U({name:w(),description:Me(w()),required:Me(st())}),Lz=U({...qs.shape,...va.shape,description:Me(w()),arguments:Me(le(jz)),_meta:Me(Tt({}))}),Js=ka.extend({method:V("prompts/list")}),zz=wa.extend({prompts:le(Lz)}),Hz=Gt.extend({name:w(),arguments:Re(w(),w()).optional()}),il=lt.extend({method:V("prompts/get"),params:Hz}),Eg=U({type:V("text"),text:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Tg=U({type:V("image"),data:kg,mimeType:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),$g=U({type:V("audio"),data:kg,mimeType:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Uz=U({type:V("tool_use"),name:w(),id:w(),input:Re(w(),De()),_meta:Re(w(),De()).optional()}),Fz=U({type:V("resource"),resource:Oe([u0,l0]),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Bz=d0.extend({type:V("resource_link")}),Pg=Oe([Eg,Tg,$g,Bz,Fz]),Zz=U({role:$a,content:Pg}),qz=dt.extend({description:w().optional(),messages:le(Zz)}),Vz=ln.extend({method:V("notifications/prompts/list_changed"),params:un.optional()}),Wz=U({title:w().optional(),readOnlyHint:st().optional(),destructiveHint:st().optional(),idempotentHint:st().optional(),openWorldHint:st().optional()}),Kz=U({taskSupport:jt(["required","optional","forbidden"]).optional()}),p0=U({...qs.shape,...va.shape,description:w().optional(),inputSchema:U({type:V("object"),properties:Re(w(),nt).optional(),required:le(w()).optional()}).catchall(De()),outputSchema:U({type:V("object"),properties:Re(w(),nt).optional(),required:le(w()).optional()}).catchall(De()).optional(),annotations:Wz.optional(),execution:Kz.optional(),_meta:Re(w(),De()).optional()}),qo=ka.extend({method:V("tools/list")}),Gz=wa.extend({tools:le(p0)}),al=dt.extend({content:le(Pg).default([]),structuredContent:Re(w(),De()).optional(),isError:st().optional()}),PJ=al.or(dt.extend({toolResult:De()})),Jz=xa.extend({name:w(),arguments:Re(w(),De()).optional()}),Xs=lt.extend({method:V("tools/call"),params:Jz}),Xz=ln.extend({method:V("notifications/tools/list_changed"),params:un.optional()}),RJ=U({autoRefresh:st().default(!0),debounceMs:ye().int().nonnegative().default(300)}),Pa=jt(["debug","info","notice","warning","error","critical","alert","emergency"]),Yz=Gt.extend({level:Pa}),Rg=lt.extend({method:V("logging/setLevel"),params:Yz}),Qz=un.extend({level:Pa,logger:w().optional(),data:De()}),eH=ln.extend({method:V("notifications/message"),params:Qz}),tH=U({name:w().optional()}),nH=U({hints:le(tH).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),rH=U({mode:jt(["auto","required","none"]).optional()}),oH=U({type:V("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(Pg).default([]),structuredContent:U({}).loose().optional(),isError:st().optional(),_meta:Re(w(),De()).optional()}),sH=fg("type",[Eg,Tg,$g]),Vu=fg("type",[Eg,Tg,$g,Uz,oH]),iH=U({role:$a,content:Oe([Vu,le(Vu)]),_meta:Re(w(),De()).optional()}),aH=xa.extend({messages:le(iH),modelPreferences:nH.optional(),systemPrompt:w().optional(),includeContext:jt(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le(w()).optional(),metadata:nt.optional(),tools:le(p0).optional(),toolChoice:rH.optional()}),cH=lt.extend({method:V("sampling/createMessage"),params:aH}),Ra=dt.extend({model:w(),stopReason:Me(jt(["endTurn","stopSequence","maxTokens"]).or(w())),role:$a,content:sH}),Cg=dt.extend({model:w(),stopReason:Me(jt(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:$a,content:Oe([Vu,le(Vu)])}),uH=U({type:V("boolean"),title:w().optional(),description:w().optional(),default:st().optional()}),lH=U({type:V("string"),title:w().optional(),description:w().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:jt(["email","uri","date","date-time"]).optional(),default:w().optional()}),dH=U({type:jt(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),pH=U({type:V("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),fH=U({type:V("string"),title:w().optional(),description:w().optional(),oneOf:le(U({const:w(),title:w()})),default:w().optional()}),mH=U({type:V("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),hH=Oe([pH,fH]),gH=U({type:V("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({type:V("string"),enum:le(w())}),default:le(w()).optional()}),yH=U({type:V("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({anyOf:le(U({const:w(),title:w()}))}),default:le(w()).optional()}),_H=Oe([gH,yH]),bH=Oe([mH,hH,_H]),xH=Oe([bH,uH,lH,dH]),SH=xa.extend({mode:V("form").optional(),message:w(),requestedSchema:U({type:V("object"),properties:Re(w(),xH),required:le(w()).optional()})}),vH=xa.extend({mode:V("url"),message:w(),elicitationId:w(),url:w().url()}),kH=Oe([SH,vH]),wH=lt.extend({method:V("elicitation/create"),params:kH}),EH=un.extend({elicitationId:w()}),TH=ln.extend({method:V("notifications/elicitation/complete"),params:EH}),Ys=dt.extend({action:jt(["accept","decline","cancel"]),content:mg(t=>t===null?void 0:t,Re(w(),Oe([w(),ye(),st(),le(w())])).optional())}),$H=U({type:V("ref/resource"),uri:w()}),PH=U({type:V("ref/prompt"),name:w()}),RH=Gt.extend({ref:Oe([PH,$H]),argument:U({name:w(),value:w()}),context:U({arguments:Re(w(),w()).optional()}).optional()}),cl=lt.extend({method:V("completion/complete"),params:RH});CH=dt.extend({completion:Tt({values:le(w()).max(100),total:Me(ye().int()),hasMore:Me(st())})}),OH=U({uri:w().startsWith("file://"),name:w().optional(),_meta:Re(w(),De()).optional()}),IH=lt.extend({method:V("roots/list"),params:Gt.optional()}),Og=dt.extend({roots:le(OH)}),AH=ln.extend({method:V("notifications/roots/list_changed"),params:un.optional()}),CJ=Oe([Xu,Sg,cl,Rg,il,Js,Ks,Gs,sl,Iz,Nz,Xs,qo,Qu,tl,nl,ol]),OJ=Oe([Ju,Yu,vg,AH,Ta]),IJ=Oe([Gu,Ra,Cg,Ys,Og,el,rl,Vs]),AJ=Oe([Xu,cH,wH,IH,Qu,tl,nl,ol]),NJ=Oe([Ju,Yu,eH,Mz,Cz,Xz,Vz,Ta,TH]),DJ=Oe([Gu,bz,CH,qz,zz,Tz,$z,Rz,al,Gz,el,rl,Vs]),q=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new hg(o.elicitations,n)}return new t(e,n,r)}},hg=class extends q{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Zr(t){return t==="completed"||t==="failed"||t==="cancelled"}var h0=x(()=>{});var y0,g0,_0,ul=x(()=>{y0=Symbol("Let zodToJsonSchema decide on which parser to use"),g0={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"},_0=t=>typeof t=="string"?{...g0,name:t}:{...g0,...t}});var b0,Ig=x(()=>{ul();b0=t=>{let e=_0(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function Ag(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,Ag(t,e,r,o)}var qr=x(()=>{});var ll,dl=x(()=>{ll=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ll(e,t.currentPath):e.join("/")}}var dn=x(()=>{dl()});function x0(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==N.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Ng=x(()=>{oa();qr();Xe()});function S0(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var Dg=x(()=>{qr()});function v0(){return{type:"boolean"}}var Mg=x(()=>{});function pl(t,e){return Y(t.type._def,e)}var fl=x(()=>{Xe()});var k0,jg=x(()=>{Xe();k0=(t,e)=>Y(t.innerType._def,e)});function Lg(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Lg(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return NH(t,e)}}var NH,zg=x(()=>{qr();NH=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function w0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Hg=x(()=>{Xe()});function E0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):je(e)}var Ug=x(()=>{Xe();dn()});function T0(t){return{type:"string",enum:Array.from(t.values)}}var Fg=x(()=>{});function $0(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(DH(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var DH,Bg=x(()=>{Xe();DH=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function P0(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Zg=x(()=>{});function ml(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":vn(n,"email",r.message,e);break;case"format:idn-email":vn(n,"idn-email",r.message,e);break;case"pattern:zod":$t(n,Sn.email,r.message,e);break}break;case"url":vn(n,"uri",r.message,e);break;case"uuid":vn(n,"uuid",r.message,e);break;case"regex":$t(n,r.regex,r.message,e);break;case"cuid":$t(n,Sn.cuid,r.message,e);break;case"cuid2":$t(n,Sn.cuid2,r.message,e);break;case"startsWith":$t(n,RegExp(`^${Vg(r.value,e)}`),r.message,e);break;case"endsWith":$t(n,RegExp(`${Vg(r.value,e)}$`),r.message,e);break;case"datetime":vn(n,"date-time",r.message,e);break;case"date":vn(n,"date",r.message,e);break;case"time":vn(n,"time",r.message,e);break;case"duration":vn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{$t(n,RegExp(Vg(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&vn(n,"ipv4",r.message,e),r.version!=="v4"&&vn(n,"ipv6",r.message,e);break}case"base64url":$t(n,Sn.base64url,r.message,e);break;case"jwt":$t(n,Sn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&$t(n,Sn.ipv4Cidr,r.message,e),r.version!=="v4"&&$t(n,Sn.ipv6Cidr,r.message,e);break}case"emoji":$t(n,Sn.emoji(),r.message,e);break;case"ulid":{$t(n,Sn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{$t(n,Sn.base64,r.message,e);break}}break}case"nanoid":$t(n,Sn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Vg(t,e){return e.patternStrategy==="escape"?jH(t):t}function jH(t){let e="";for(let n=0;n<t.length;n++)MH.has(t[n])||(e+="\\"),e+=t[n];return e}function vn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function $t(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:R0(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",R0(e,r),n,r)}function R0(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
|
|
487
|
+
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(r.external){let m=r.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),m=p.def??p.schema,f={...m};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,f))}p.isParent||this.override({zodSchema:l,jsonSchema:m,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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 bE=x(()=>{});var Rt=x(()=>{zs();_m();dm();aE();Ou();wm();Bn();Cu();ju();fh();km();yE();gE();_E();bE()});var tg=x(()=>{Rt()});function ng(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new uL(n)}var cL,uL,xE=x(()=>{Rt();Rt();tg();cL=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");we.init(t,e),t.def=e,t.parse=(n,r)=>fm(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Ho(t,n,r),t.parseAsync=async(n,r)=>hm(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Uo(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Jt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))}),uL=E("ZodMiniObject",(t,e)=>{Du.init(t,e),cL.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var SE=x(()=>{});var vE=x(()=>{});var kE=x(()=>{});var wE=x(()=>{Rt();tg();xE();SE();Rt();ju();vE();kE()});var EE=x(()=>{wE()});var rg=x(()=>{EE()});function Zn(t){return!!t._zod}function Zo(t){let e=Object.values(t);if(e.length===0)return ng({});let n=e.every(Zn),r=e.every(o=>!Zn(o));if(n)return ng(t);if(r)return Yf(t);throw new Error("Mixed Zod versions detected in object shape.")}function Hr(t,e){return Zn(t)?Ho(t,e):t.safeParse(e)}async function qu(t,e){return Zn(t)?await Uo(t,e):await t.safeParseAsync(e)}function Ur(t){if(!t)return;let e;if(Zn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bs(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Zo(t)}}if(Zn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function pL(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Vu(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${pL(e.path)}`:e.message).join(`
|
|
488
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function $E(t){return t.description}function PE(t){if(Zn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Zs(t){if(Zn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var xa=x(()=>{aa();rg()});var og=x(()=>{Rt()});var Sa={};_e(Sa,{ZodISODate:()=>CE,ZodISODateTime:()=>RE,ZodISODuration:()=>IE,ZodISOTime:()=>OE,date:()=>ig,datetime:()=>sg,duration:()=>cg,time:()=>ag});function sg(t){return dE(RE,t)}function ig(t){return pE(CE,t)}function ag(t){return fE(OE,t)}function cg(t){return mE(IE,t)}var RE,CE,OE,IE,ug=x(()=>{Rt();lg();RE=E("ZodISODateTime",(t,e)=>{nE.init(t,e),Ne.init(t,e)});CE=E("ZodISODate",(t,e)=>{rE.init(t,e),Ne.init(t,e)});OE=E("ZodISOTime",(t,e)=>{oE.init(t,e),Ne.init(t,e)});IE=E("ZodISODuration",(t,e)=>{sE.init(t,e),Ne.init(t,e)})});var AE,mJ,va,dg=x(()=>{Rt();Rt();AE=(t,e)=>{Pu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>lm(t,n)},flatten:{value:n=>um(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},mJ=E("ZodError",AE),va=E("ZodError",AE,{Parent:Error})});var NE,DE,ME,jE,pg=x(()=>{Rt();dg();NE=pm(va),DE=mm(va),ME=gm(va),jE=ym(va)});function w(t){return mh(xL,t)}function ye(t){return Mh(FE,t)}function zE(t){return jh(LL,t)}function ct(t){return Lh(zL,t)}function BE(t){return zh(HL,t)}function De(){return Hh(UL)}function BL(t){return Uh(FL,t)}function le(t,e){return hE(ZL,t,e)}function U(t,e){let n={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new ZE(n)}function Ct(t,e){return new ZE({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ue.normalizeParams(e)})}function Oe(t,e){return new qE({type:"union",options:t,...ue.normalizeParams(e)})}function hg(t,e,n){return new qL({type:"union",options:e,discriminator:t,...ue.normalizeParams(n)})}function Ku(t,e){return new VL({type:"intersection",left:t,right:e})}function Re(t,e,n){return new WL({type:"record",keyType:t,valueType:e,...ue.normalizeParams(n)})}function zt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new fg({type:"enum",entries:n,...ue.normalizeParams(e)})}function V(t,e){return new KL({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function VE(t){return new GL({type:"transform",transform:t})}function Me(t){return new WE({type:"optional",innerType:t})}function HE(t){return new JL({type:"nullable",innerType:t})}function YL(t,e){return new XL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ez(t,e){return new QL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function tz(t,e){return new KE({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function rz(t,e){return new nz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function mg(t,e){return new oz({type:"pipe",in:t,out:e})}function iz(t){return new sz({type:"readonly",innerType:t})}function az(t){let e=new pt({check:"custom"});return e._zod.check=t,e}function JE(t,e){return Yh(GE,t??(()=>!0),e)}function cz(t,e={}){return Qh(GE,t,e)}function uz(t){let e=az(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ue.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ue.issue(o))}},t(n.value,n)));return e}function gg(t,e){return mg(VE(t),e)}var Fe,UE,xL,Ne,SL,LE,Wu,vL,kL,wL,EL,TL,$L,PL,RL,CL,OL,IL,AL,NL,DL,ML,jL,FE,LL,zL,HL,UL,FL,ZL,ZE,qE,qL,VL,WL,fg,KL,GL,WE,JL,XL,QL,KE,nz,oz,sz,GE,lg=x(()=>{Rt();Rt();og();ug();pg();Fe=E("ZodType",(t,e)=>(we.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Jt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>NE(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>ME(t,n,r),t.parseAsync=async(n,r)=>DE(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>jE(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(cz(n,r)),t.superRefine=n=>t.check(uz(n)),t.overwrite=n=>t.check(Fo(n)),t.optional=()=>Me(t),t.nullable=()=>HE(t),t.nullish=()=>Me(HE(t)),t.nonoptional=n=>tz(t,n),t.array=()=>le(t),t.or=n=>Oe([t,n]),t.and=n=>Ku(t,n),t.transform=n=>mg(t,VE(n)),t.default=n=>YL(t,n),t.prefault=n=>ez(t,n),t.catch=n=>rz(t,n),t.pipe=n=>mg(t,n),t.readonly=()=>iz(t),t.describe=n=>{let r=t.clone();return zr.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return zr.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return zr.get(t);let r=t.clone();return zr.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),UE=E("_ZodString",(t,e)=>{ga.init(t,e),Fe.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Fh(...r)),t.includes=(...r)=>t.check(qh(...r)),t.startsWith=(...r)=>t.check(Vh(...r)),t.endsWith=(...r)=>t.check(Wh(...r)),t.min=(...r)=>t.check(Fs(...r)),t.max=(...r)=>t.check(Fu(...r)),t.length=(...r)=>t.check(Bu(...r)),t.nonempty=(...r)=>t.check(Fs(1,...r)),t.lowercase=r=>t.check(Bh(r)),t.uppercase=r=>t.check(Zh(r)),t.trim=()=>t.check(Gh()),t.normalize=(...r)=>t.check(Kh(...r)),t.toLowerCase=()=>t.check(Jh()),t.toUpperCase=()=>t.check(Xh())}),xL=E("ZodString",(t,e)=>{ga.init(t,e),UE.init(t,e),t.email=n=>t.check(hh(SL,n)),t.url=n=>t.check(xh(vL,n)),t.jwt=n=>t.check(Dh(jL,n)),t.emoji=n=>t.check(Sh(kL,n)),t.guid=n=>t.check(Lu(LE,n)),t.uuid=n=>t.check(gh(Wu,n)),t.uuidv4=n=>t.check(yh(Wu,n)),t.uuidv6=n=>t.check(_h(Wu,n)),t.uuidv7=n=>t.check(bh(Wu,n)),t.nanoid=n=>t.check(vh(wL,n)),t.guid=n=>t.check(Lu(LE,n)),t.cuid=n=>t.check(kh(EL,n)),t.cuid2=n=>t.check(wh(TL,n)),t.ulid=n=>t.check(Eh($L,n)),t.base64=n=>t.check(Ih(NL,n)),t.base64url=n=>t.check(Ah(DL,n)),t.xid=n=>t.check(Th(PL,n)),t.ksuid=n=>t.check($h(RL,n)),t.ipv4=n=>t.check(Ph(CL,n)),t.ipv6=n=>t.check(Rh(OL,n)),t.cidrv4=n=>t.check(Ch(IL,n)),t.cidrv6=n=>t.check(Oh(AL,n)),t.e164=n=>t.check(Nh(ML,n)),t.datetime=n=>t.check(sg(n)),t.date=n=>t.check(ig(n)),t.time=n=>t.check(ag(n)),t.duration=n=>t.check(cg(n))});Ne=E("ZodStringFormat",(t,e)=>{Pe.init(t,e),UE.init(t,e)}),SL=E("ZodEmail",(t,e)=>{Pm.init(t,e),Ne.init(t,e)}),LE=E("ZodGUID",(t,e)=>{Tm.init(t,e),Ne.init(t,e)}),Wu=E("ZodUUID",(t,e)=>{$m.init(t,e),Ne.init(t,e)}),vL=E("ZodURL",(t,e)=>{Rm.init(t,e),Ne.init(t,e)}),kL=E("ZodEmoji",(t,e)=>{Cm.init(t,e),Ne.init(t,e)}),wL=E("ZodNanoID",(t,e)=>{Om.init(t,e),Ne.init(t,e)}),EL=E("ZodCUID",(t,e)=>{Im.init(t,e),Ne.init(t,e)}),TL=E("ZodCUID2",(t,e)=>{Am.init(t,e),Ne.init(t,e)}),$L=E("ZodULID",(t,e)=>{Nm.init(t,e),Ne.init(t,e)}),PL=E("ZodXID",(t,e)=>{Dm.init(t,e),Ne.init(t,e)}),RL=E("ZodKSUID",(t,e)=>{Mm.init(t,e),Ne.init(t,e)}),CL=E("ZodIPv4",(t,e)=>{jm.init(t,e),Ne.init(t,e)}),OL=E("ZodIPv6",(t,e)=>{Lm.init(t,e),Ne.init(t,e)}),IL=E("ZodCIDRv4",(t,e)=>{zm.init(t,e),Ne.init(t,e)}),AL=E("ZodCIDRv6",(t,e)=>{Hm.init(t,e),Ne.init(t,e)}),NL=E("ZodBase64",(t,e)=>{Um.init(t,e),Ne.init(t,e)}),DL=E("ZodBase64URL",(t,e)=>{Fm.init(t,e),Ne.init(t,e)}),ML=E("ZodE164",(t,e)=>{Bm.init(t,e),Ne.init(t,e)}),jL=E("ZodJWT",(t,e)=>{Zm.init(t,e),Ne.init(t,e)}),FE=E("ZodNumber",(t,e)=>{Nu.init(t,e),Fe.init(t,e),t.gt=(r,o)=>t.check(Hu(r,o)),t.gte=(r,o)=>t.check(ba(r,o)),t.min=(r,o)=>t.check(ba(r,o)),t.lt=(r,o)=>t.check(zu(r,o)),t.lte=(r,o)=>t.check(_a(r,o)),t.max=(r,o)=>t.check(_a(r,o)),t.int=r=>t.check(zE(r)),t.safe=r=>t.check(zE(r)),t.positive=r=>t.check(Hu(0,r)),t.nonnegative=r=>t.check(ba(0,r)),t.negative=r=>t.check(zu(0,r)),t.nonpositive=r=>t.check(_a(0,r)),t.multipleOf=(r,o)=>t.check(Uu(r,o)),t.step=(r,o)=>t.check(Uu(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});LL=E("ZodNumberFormat",(t,e)=>{qm.init(t,e),FE.init(t,e)});zL=E("ZodBoolean",(t,e)=>{Vm.init(t,e),Fe.init(t,e)});HL=E("ZodNull",(t,e)=>{Wm.init(t,e),Fe.init(t,e)});UL=E("ZodUnknown",(t,e)=>{Km.init(t,e),Fe.init(t,e)});FL=E("ZodNever",(t,e)=>{Gm.init(t,e),Fe.init(t,e)});ZL=E("ZodArray",(t,e)=>{Jm.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Fs(n,r)),t.nonempty=n=>t.check(Fs(1,n)),t.max=(n,r)=>t.check(Fu(n,r)),t.length=(n,r)=>t.check(Bu(n,r)),t.unwrap=()=>t.element});ZE=E("ZodObject",(t,e)=>{Du.init(t,e),Fe.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>zt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:BL()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ue.extend(t,n),t.merge=n=>ue.merge(t,n),t.pick=n=>ue.pick(t,n),t.omit=n=>ue.omit(t,n),t.partial=(...n)=>ue.partial(WE,t,n[0]),t.required=(...n)=>ue.required(KE,t,n[0])});qE=E("ZodUnion",(t,e)=>{Mu.init(t,e),Fe.init(t,e),t.options=e.options});qL=E("ZodDiscriminatedUnion",(t,e)=>{qE.init(t,e),Xm.init(t,e)});VL=E("ZodIntersection",(t,e)=>{Ym.init(t,e),Fe.init(t,e)});WL=E("ZodRecord",(t,e)=>{Qm.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});fg=E("ZodEnum",(t,e)=>{eh.init(t,e),Fe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new fg({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new fg({...e,checks:[],...ue.normalizeParams(o),entries:s})}});KL=E("ZodLiteral",(t,e)=>{th.init(t,e),Fe.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]}})});GL=E("ZodTransform",(t,e)=>{nh.init(t,e),Fe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ue.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ue.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});WE=E("ZodOptional",(t,e)=>{rh.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});JL=E("ZodNullable",(t,e)=>{oh.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});XL=E("ZodDefault",(t,e)=>{sh.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});QL=E("ZodPrefault",(t,e)=>{ih.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});KE=E("ZodNonOptional",(t,e)=>{ah.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});nz=E("ZodCatch",(t,e)=>{ch.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});oz=E("ZodPipe",(t,e)=>{uh.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});sz=E("ZodReadonly",(t,e)=>{lh.init(t,e),Fe.init(t,e)});GE=E("ZodCustom",(t,e)=>{dh.init(t,e),Fe.init(t,e)})});var XE=x(()=>{});var YE=x(()=>{});var QE=x(()=>{Rt();lg();og();dg();pg();XE();Rt();uE();ju();ug();YE();Gt(cE())});var e0=x(()=>{QE()});var t0=x(()=>{e0()});function _0(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function b0(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var _g,n0,Fr,Ju,rt,r0,o0,CJ,pz,fz,bg,Xt,ka,s0,ft,dn,pn,mt,Xu,i0,xg,a0,c0,Sg,wa,K,vg,u0,l0,OJ,Yu,mz,Qu,hz,Ea,qs,d0,gz,yz,_z,bz,xz,Sz,kg,vz,kz,wg,el,wz,Ez,tl,Tz,Ta,$a,$z,Pa,Vs,Pz,Ra,nl,rl,ol,IJ,sl,il,al,p0,f0,m0,Eg,h0,Ca,Ws,g0,Rz,Ks,Cz,Gs,Oz,Tg,Iz,cl,Az,Nz,Dz,Mz,jz,Lz,zz,Hz,Uz,Fz,Js,Bz,Zz,ul,$g,Pg,Rg,qz,Vz,Wz,Cg,Kz,Gz,Jz,Xz,Yz,y0,qo,Qz,ll,AJ,eH,Xs,tH,NJ,Oa,nH,Og,rH,oH,sH,iH,aH,cH,uH,Gu,lH,dH,pH,Ia,Ig,fH,mH,hH,gH,yH,_H,bH,xH,SH,vH,kH,wH,EH,TH,$H,PH,RH,CH,Ys,OH,IH,AH,dl,NH,DH,MH,Ag,jH,DJ,MJ,jJ,LJ,zJ,HJ,q,yg,Vo=x(()=>{t0();_g="2025-11-25",n0=[_g,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Fr="io.modelcontextprotocol/related-task",Ju="2.0",rt=JE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),r0=Oe([w(),ye().int()]),o0=w(),CJ=Ct({ttl:ye().optional(),pollInterval:ye().optional()}),pz=U({ttl:ye().optional()}),fz=U({taskId:w()}),bg=Ct({progressToken:r0.optional(),[Fr]:fz.optional()}),Xt=U({_meta:bg.optional()}),ka=Xt.extend({task:pz.optional()}),s0=t=>ka.safeParse(t).success,ft=U({method:w(),params:Xt.loose().optional()}),dn=U({_meta:bg.optional()}),pn=U({method:w(),params:dn.loose().optional()}),mt=Ct({_meta:bg.optional()}),Xu=Oe([w(),ye().int()]),i0=U({jsonrpc:V(Ju),id:Xu,...ft.shape}).strict(),xg=t=>i0.safeParse(t).success,a0=U({jsonrpc:V(Ju),...pn.shape}).strict(),c0=t=>a0.safeParse(t).success,Sg=U({jsonrpc:V(Ju),id:Xu,result:mt}).strict(),wa=t=>Sg.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"})(K||(K={}));vg=U({jsonrpc:V(Ju),id:Xu.optional(),error:U({code:ye().int(),message:w(),data:De().optional()})}).strict(),u0=t=>vg.safeParse(t).success,l0=Oe([i0,a0,Sg,vg]),OJ=Oe([Sg,vg]),Yu=mt.strict(),mz=dn.extend({requestId:Xu.optional(),reason:w().optional()}),Qu=pn.extend({method:V("notifications/cancelled"),params:mz}),hz=U({src:w(),mimeType:w().optional(),sizes:le(w()).optional(),theme:zt(["light","dark"]).optional()}),Ea=U({icons:le(hz).optional()}),qs=U({name:w(),title:w().optional()}),d0=qs.extend({...qs.shape,...Ea.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),gz=Ku(U({applyDefaults:ct().optional()}),Re(w(),De())),yz=gg(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ku(U({form:gz.optional(),url:rt.optional()}),Re(w(),De()).optional())),_z=Ct({list:rt.optional(),cancel:rt.optional(),requests:Ct({sampling:Ct({createMessage:rt.optional()}).optional(),elicitation:Ct({create:rt.optional()}).optional()}).optional()}),bz=Ct({list:rt.optional(),cancel:rt.optional(),requests:Ct({tools:Ct({call:rt.optional()}).optional()}).optional()}),xz=U({experimental:Re(w(),rt).optional(),sampling:U({context:rt.optional(),tools:rt.optional()}).optional(),elicitation:yz.optional(),roots:U({listChanged:ct().optional()}).optional(),tasks:_z.optional(),extensions:Re(w(),rt).optional()}),Sz=Xt.extend({protocolVersion:w(),capabilities:xz,clientInfo:d0}),kg=ft.extend({method:V("initialize"),params:Sz}),vz=U({experimental:Re(w(),rt).optional(),logging:rt.optional(),completions:rt.optional(),prompts:U({listChanged:ct().optional()}).optional(),resources:U({subscribe:ct().optional(),listChanged:ct().optional()}).optional(),tools:U({listChanged:ct().optional()}).optional(),tasks:bz.optional(),extensions:Re(w(),rt).optional()}),kz=mt.extend({protocolVersion:w(),capabilities:vz,serverInfo:d0,instructions:w().optional()}),wg=pn.extend({method:V("notifications/initialized"),params:dn.optional()}),el=ft.extend({method:V("ping"),params:Xt.optional()}),wz=U({progress:ye(),total:Me(ye()),message:Me(w())}),Ez=U({...dn.shape,...wz.shape,progressToken:r0}),tl=pn.extend({method:V("notifications/progress"),params:Ez}),Tz=Xt.extend({cursor:o0.optional()}),Ta=ft.extend({params:Tz.optional()}),$a=mt.extend({nextCursor:o0.optional()}),$z=zt(["working","input_required","completed","failed","cancelled"]),Pa=U({taskId:w(),status:$z,ttl:Oe([ye(),BE()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Me(ye()),statusMessage:Me(w())}),Vs=mt.extend({task:Pa}),Pz=dn.merge(Pa),Ra=pn.extend({method:V("notifications/tasks/status"),params:Pz}),nl=ft.extend({method:V("tasks/get"),params:Xt.extend({taskId:w()})}),rl=mt.merge(Pa),ol=ft.extend({method:V("tasks/result"),params:Xt.extend({taskId:w()})}),IJ=mt.loose(),sl=Ta.extend({method:V("tasks/list")}),il=$a.extend({tasks:le(Pa)}),al=ft.extend({method:V("tasks/cancel"),params:Xt.extend({taskId:w()})}),p0=mt.merge(Pa),f0=U({uri:w(),mimeType:Me(w()),_meta:Re(w(),De()).optional()}),m0=f0.extend({text:w()}),Eg=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),h0=f0.extend({blob:Eg}),Ca=zt(["user","assistant"]),Ws=U({audience:le(Ca).optional(),priority:ye().min(0).max(1).optional(),lastModified:Sa.datetime({offset:!0}).optional()}),g0=U({...qs.shape,...Ea.shape,uri:w(),description:Me(w()),mimeType:Me(w()),size:Me(ye()),annotations:Ws.optional(),_meta:Me(Ct({}))}),Rz=U({...qs.shape,...Ea.shape,uriTemplate:w(),description:Me(w()),mimeType:Me(w()),annotations:Ws.optional(),_meta:Me(Ct({}))}),Ks=Ta.extend({method:V("resources/list")}),Cz=$a.extend({resources:le(g0)}),Gs=Ta.extend({method:V("resources/templates/list")}),Oz=$a.extend({resourceTemplates:le(Rz)}),Tg=Xt.extend({uri:w()}),Iz=Tg,cl=ft.extend({method:V("resources/read"),params:Iz}),Az=mt.extend({contents:le(Oe([m0,h0]))}),Nz=pn.extend({method:V("notifications/resources/list_changed"),params:dn.optional()}),Dz=Tg,Mz=ft.extend({method:V("resources/subscribe"),params:Dz}),jz=Tg,Lz=ft.extend({method:V("resources/unsubscribe"),params:jz}),zz=dn.extend({uri:w()}),Hz=pn.extend({method:V("notifications/resources/updated"),params:zz}),Uz=U({name:w(),description:Me(w()),required:Me(ct())}),Fz=U({...qs.shape,...Ea.shape,description:Me(w()),arguments:Me(le(Uz)),_meta:Me(Ct({}))}),Js=Ta.extend({method:V("prompts/list")}),Bz=$a.extend({prompts:le(Fz)}),Zz=Xt.extend({name:w(),arguments:Re(w(),w()).optional()}),ul=ft.extend({method:V("prompts/get"),params:Zz}),$g=U({type:V("text"),text:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Pg=U({type:V("image"),data:Eg,mimeType:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Rg=U({type:V("audio"),data:Eg,mimeType:w(),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),qz=U({type:V("tool_use"),name:w(),id:w(),input:Re(w(),De()),_meta:Re(w(),De()).optional()}),Vz=U({type:V("resource"),resource:Oe([m0,h0]),annotations:Ws.optional(),_meta:Re(w(),De()).optional()}),Wz=g0.extend({type:V("resource_link")}),Cg=Oe([$g,Pg,Rg,Wz,Vz]),Kz=U({role:Ca,content:Cg}),Gz=mt.extend({description:w().optional(),messages:le(Kz)}),Jz=pn.extend({method:V("notifications/prompts/list_changed"),params:dn.optional()}),Xz=U({title:w().optional(),readOnlyHint:ct().optional(),destructiveHint:ct().optional(),idempotentHint:ct().optional(),openWorldHint:ct().optional()}),Yz=U({taskSupport:zt(["required","optional","forbidden"]).optional()}),y0=U({...qs.shape,...Ea.shape,description:w().optional(),inputSchema:U({type:V("object"),properties:Re(w(),rt).optional(),required:le(w()).optional()}).catchall(De()),outputSchema:U({type:V("object"),properties:Re(w(),rt).optional(),required:le(w()).optional()}).catchall(De()).optional(),annotations:Xz.optional(),execution:Yz.optional(),_meta:Re(w(),De()).optional()}),qo=Ta.extend({method:V("tools/list")}),Qz=$a.extend({tools:le(y0)}),ll=mt.extend({content:le(Cg).default([]),structuredContent:Re(w(),De()).optional(),isError:ct().optional()}),AJ=ll.or(mt.extend({toolResult:De()})),eH=ka.extend({name:w(),arguments:Re(w(),De()).optional()}),Xs=ft.extend({method:V("tools/call"),params:eH}),tH=pn.extend({method:V("notifications/tools/list_changed"),params:dn.optional()}),NJ=U({autoRefresh:ct().default(!0),debounceMs:ye().int().nonnegative().default(300)}),Oa=zt(["debug","info","notice","warning","error","critical","alert","emergency"]),nH=Xt.extend({level:Oa}),Og=ft.extend({method:V("logging/setLevel"),params:nH}),rH=dn.extend({level:Oa,logger:w().optional(),data:De()}),oH=pn.extend({method:V("notifications/message"),params:rH}),sH=U({name:w().optional()}),iH=U({hints:le(sH).optional(),costPriority:ye().min(0).max(1).optional(),speedPriority:ye().min(0).max(1).optional(),intelligencePriority:ye().min(0).max(1).optional()}),aH=U({mode:zt(["auto","required","none"]).optional()}),cH=U({type:V("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:le(Cg).default([]),structuredContent:U({}).loose().optional(),isError:ct().optional(),_meta:Re(w(),De()).optional()}),uH=hg("type",[$g,Pg,Rg]),Gu=hg("type",[$g,Pg,Rg,qz,cH]),lH=U({role:Ca,content:Oe([Gu,le(Gu)]),_meta:Re(w(),De()).optional()}),dH=ka.extend({messages:le(lH),modelPreferences:iH.optional(),systemPrompt:w().optional(),includeContext:zt(["none","thisServer","allServers"]).optional(),temperature:ye().optional(),maxTokens:ye().int(),stopSequences:le(w()).optional(),metadata:rt.optional(),tools:le(y0).optional(),toolChoice:aH.optional()}),pH=ft.extend({method:V("sampling/createMessage"),params:dH}),Ia=mt.extend({model:w(),stopReason:Me(zt(["endTurn","stopSequence","maxTokens"]).or(w())),role:Ca,content:uH}),Ig=mt.extend({model:w(),stopReason:Me(zt(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Ca,content:Oe([Gu,le(Gu)])}),fH=U({type:V("boolean"),title:w().optional(),description:w().optional(),default:ct().optional()}),mH=U({type:V("string"),title:w().optional(),description:w().optional(),minLength:ye().optional(),maxLength:ye().optional(),format:zt(["email","uri","date","date-time"]).optional(),default:w().optional()}),hH=U({type:zt(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ye().optional(),maximum:ye().optional(),default:ye().optional()}),gH=U({type:V("string"),title:w().optional(),description:w().optional(),enum:le(w()),default:w().optional()}),yH=U({type:V("string"),title:w().optional(),description:w().optional(),oneOf:le(U({const:w(),title:w()})),default:w().optional()}),_H=U({type:V("string"),title:w().optional(),description:w().optional(),enum:le(w()),enumNames:le(w()).optional(),default:w().optional()}),bH=Oe([gH,yH]),xH=U({type:V("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({type:V("string"),enum:le(w())}),default:le(w()).optional()}),SH=U({type:V("array"),title:w().optional(),description:w().optional(),minItems:ye().optional(),maxItems:ye().optional(),items:U({anyOf:le(U({const:w(),title:w()}))}),default:le(w()).optional()}),vH=Oe([xH,SH]),kH=Oe([_H,bH,vH]),wH=Oe([kH,fH,mH,hH]),EH=ka.extend({mode:V("form").optional(),message:w(),requestedSchema:U({type:V("object"),properties:Re(w(),wH),required:le(w()).optional()})}),TH=ka.extend({mode:V("url"),message:w(),elicitationId:w(),url:w().url()}),$H=Oe([EH,TH]),PH=ft.extend({method:V("elicitation/create"),params:$H}),RH=dn.extend({elicitationId:w()}),CH=pn.extend({method:V("notifications/elicitation/complete"),params:RH}),Ys=mt.extend({action:zt(["accept","decline","cancel"]),content:gg(t=>t===null?void 0:t,Re(w(),Oe([w(),ye(),ct(),le(w())])).optional())}),OH=U({type:V("ref/resource"),uri:w()}),IH=U({type:V("ref/prompt"),name:w()}),AH=Xt.extend({ref:Oe([IH,OH]),argument:U({name:w(),value:w()}),context:U({arguments:Re(w(),w()).optional()}).optional()}),dl=ft.extend({method:V("completion/complete"),params:AH});NH=mt.extend({completion:Ct({values:le(w()).max(100),total:Me(ye().int()),hasMore:Me(ct())})}),DH=U({uri:w().startsWith("file://"),name:w().optional(),_meta:Re(w(),De()).optional()}),MH=ft.extend({method:V("roots/list"),params:Xt.optional()}),Ag=mt.extend({roots:le(DH)}),jH=pn.extend({method:V("notifications/roots/list_changed"),params:dn.optional()}),DJ=Oe([el,kg,dl,Og,ul,Js,Ks,Gs,cl,Mz,Lz,Xs,qo,nl,ol,sl,al]),MJ=Oe([Qu,tl,wg,jH,Ra]),jJ=Oe([Yu,Ia,Ig,Ys,Ag,rl,il,Vs]),LJ=Oe([el,pH,PH,MH,nl,ol,sl,al]),zJ=Oe([Qu,tl,oH,Hz,Nz,tH,Jz,Ra,CH]),HJ=Oe([Yu,kz,NH,Gz,Bz,Cz,Oz,Az,ll,Qz,rl,il,Vs]),q=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===K.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new yg(o.elicitations,n)}return new t(e,n,r)}},yg=class extends q{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Br(t){return t==="completed"||t==="failed"||t==="cancelled"}var x0=x(()=>{});var v0,S0,k0,pl=x(()=>{v0=Symbol("Let zodToJsonSchema decide on which parser to use"),S0={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"},k0=t=>typeof t=="string"?{...S0,name:t}:{...S0,...t}});var w0,Ng=x(()=>{pl();w0=t=>{let e=k0(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function Dg(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function de(t,e,n,r,o){t[e]=n,Dg(t,e,r,o)}var Zr=x(()=>{});var fl,ml=x(()=>{fl=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?fl(e,t.currentPath):e.join("/")}}var fn=x(()=>{ml()});function E0(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==N.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(n,"minItems",t.exactLength.value,t.exactLength.message,e),de(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Mg=x(()=>{aa();Zr();Ye()});function T0(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var jg=x(()=>{Zr()});function $0(){return{type:"boolean"}}var Lg=x(()=>{});function hl(t,e){return Y(t.type._def,e)}var gl=x(()=>{Ye()});var P0,zg=x(()=>{Ye();P0=(t,e)=>Y(t.innerType._def,e)});function Hg(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Hg(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return LH(t,e)}}var LH,Ug=x(()=>{Zr();LH=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":de(n,"minimum",r.value,r.message,e);break;case"max":de(n,"maximum",r.value,r.message,e);break}return n}});function R0(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var Fg=x(()=>{Ye()});function C0(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):je(e)}var Bg=x(()=>{Ye();fn()});function O0(t){return{type:"string",enum:Array.from(t.values)}}var Zg=x(()=>{});function I0(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(zH(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}var zH,qg=x(()=>{Ye();zH=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function A0(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Vg=x(()=>{});function yl(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":kn(n,"email",r.message,e);break;case"format:idn-email":kn(n,"idn-email",r.message,e);break;case"pattern:zod":Ot(n,vn.email,r.message,e);break}break;case"url":kn(n,"uri",r.message,e);break;case"uuid":kn(n,"uuid",r.message,e);break;case"regex":Ot(n,r.regex,r.message,e);break;case"cuid":Ot(n,vn.cuid,r.message,e);break;case"cuid2":Ot(n,vn.cuid2,r.message,e);break;case"startsWith":Ot(n,RegExp(`^${Kg(r.value,e)}`),r.message,e);break;case"endsWith":Ot(n,RegExp(`${Kg(r.value,e)}$`),r.message,e);break;case"datetime":kn(n,"date-time",r.message,e);break;case"date":kn(n,"date",r.message,e);break;case"time":kn(n,"time",r.message,e);break;case"duration":kn(n,"duration",r.message,e);break;case"length":de(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),de(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Ot(n,RegExp(Kg(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&kn(n,"ipv4",r.message,e),r.version!=="v4"&&kn(n,"ipv6",r.message,e);break}case"base64url":Ot(n,vn.base64url,r.message,e);break;case"jwt":Ot(n,vn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Ot(n,vn.ipv4Cidr,r.message,e),r.version!=="v4"&&Ot(n,vn.ipv6Cidr,r.message,e);break}case"emoji":Ot(n,vn.emoji(),r.message,e);break;case"ulid":{Ot(n,vn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{kn(n,"binary",r.message,e);break}case"contentEncoding:base64":{de(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Ot(n,vn.base64,r.message,e);break}}break}case"nanoid":Ot(n,vn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Kg(t,e){return e.patternStrategy==="escape"?UH(t):t}function UH(t){let e="";for(let n=0;n<t.length;n++)HH.has(t[n])||(e+="\\"),e+=t[n];return e}function kn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):de(t,"format",e,n,r)}function Ot(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:N0(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):de(t,"pattern",N0(e,r),n,r)}function N0(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
|
|
489
489
|
]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
|
|
490
490
|
]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
|
|
491
491
|
`:`[${r[c]}\r
|
|
492
|
-
]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[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 qg,Sn,MH,hl=x(()=>{qr();Sn={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:()=>(qg===void 0&&(qg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qg),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-_]*$/};MH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function gl(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===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=ml(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===N.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===N.ZodBranded&&t.keyType._def.type._def.typeName===N.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=pl(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var yl=x(()=>{oa();Xe();hl();fl();dn()});function C0(t,e){if(e.mapStrategy==="record")return gl(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),r=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Wg=x(()=>{Xe();yl();dn()});function O0(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var Kg=x(()=>{});function I0(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var Gg=x(()=>{dn()});function A0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jg=x(()=>{});function D0(t,e){if(e.target==="openApi3")return N0(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Ca&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Ca[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return N0(t,e)}var Ca,N0,_l=x(()=>{Xe();Ca={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};N0=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Y(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function M0(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:Ca[t.innerType._def.typeName],nullable:!0}:{type:[Ca[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Xg=x(()=>{Xe();_l()});function j0(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Ag(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var Yg=x(()=>{qr()});function L0(t,e){let n=e.target==="openAi",r={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=zH(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=LH(t,e);return i!==void 0&&(r.additionalProperties=i),r}function LH(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 zH(t){try{return t.isOptional()}catch{return!0}}var Qg=x(()=>{Xe()});var z0,ey=x(()=>{Xe();dn();z0=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:je(e)},n]}:je(e)}});var H0,ty=x(()=>{Xe();H0=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function U0(t,e){return Y(t.type._def,e)}var ny=x(()=>{Xe()});function F0(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var ry=x(()=>{qr();Xe()});function B0(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var oy=x(()=>{Xe()});function Z0(t){return{not:je(t)}}var sy=x(()=>{dn()});function q0(t){return je(t)}var iy=x(()=>{dn()});var V0,ay=x(()=>{Xe();V0=(t,e)=>Y(t.innerType._def,e)});var W0,cy=x(()=>{oa();dn();Ng();Dg();Mg();fl();jg();zg();Hg();Ug();Fg();Bg();Zg();Wg();Kg();Gg();Jg();Xg();Yg();Qg();ey();ty();ny();yl();ry();hl();oy();sy();_l();iy();ay();W0=(t,e,n)=>{switch(e){case N.ZodString:return ml(t,n);case N.ZodNumber:return j0(t,n);case N.ZodObject:return L0(t,n);case N.ZodBigInt:return S0(t,n);case N.ZodBoolean:return v0();case N.ZodDate:return Lg(t,n);case N.ZodUndefined:return Z0(n);case N.ZodNull:return A0(n);case N.ZodArray:return x0(t,n);case N.ZodUnion:case N.ZodDiscriminatedUnion:return D0(t,n);case N.ZodIntersection:return $0(t,n);case N.ZodTuple:return B0(t,n);case N.ZodRecord:return gl(t,n);case N.ZodLiteral:return P0(t,n);case N.ZodEnum:return T0(t);case N.ZodNativeEnum:return O0(t);case N.ZodNullable:return M0(t,n);case N.ZodOptional:return z0(t,n);case N.ZodMap:return C0(t,n);case N.ZodSet:return F0(t,n);case N.ZodLazy:return()=>t.getter()._def;case N.ZodPromise:return U0(t,n);case N.ZodNaN:case N.ZodNever:return I0(n);case N.ZodEffects:return E0(t,n);case N.ZodAny:return je(n);case N.ZodUnknown:return q0(n);case N.ZodDefault:return w0(t,n);case N.ZodBranded:return pl(t,n);case N.ZodReadonly:return V0(t,n);case N.ZodCatch:return k0(t,n);case N.ZodPipeline:return H0(t,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==y0)return a}if(r&&!n){let a=HH(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=W0(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&UH(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var HH,UH,Xe=x(()=>{ul();cy();dl();dn();HH=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ll(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},UH=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var K0=x(()=>{});var uy,ly=x(()=>{Xe();Ig();dn();uy=(t,e)=>{let n=b0(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??je(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??je(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 G0=x(()=>{ul();Ig();qr();dl();Xe();K0();dn();Ng();Dg();Mg();fl();jg();zg();Hg();Ug();Fg();Bg();Zg();Wg();Kg();Gg();Jg();Xg();Yg();Qg();ey();ty();ny();ay();yl();ry();hl();oy();sy();_l();iy();cy();ly();ly()});function FH(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function dy(t,e){return Zn(t)?Yh(t,{target:FH(e?.target),io:e?.pipeStrategy??"input"}):uy(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function py(t){let n=Fr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Zs(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function fy(t,e){let n=Ur(t,e);if(!n.success)throw n.error;return n.data}var my=x(()=>{tg();ya();G0()});function J0(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X0(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];J0(i)&&J0(s)?n[o]={...i,...s}:n[o]=s}return n}var BH,bl,Y0=x(()=>{ya();Vo();h0();my();BH=6e4,bl=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(Ju,n=>{this._oncancel(n)}),this.setNotificationHandler(Yu,n=>{this._onprogress(n)}),this.setRequestHandler(Xu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qu,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new q(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(tl,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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 q(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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new q(K.InvalidParams,`Task not found: ${s}`);if(!Zr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Zr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Br]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(nl,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new q(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ol,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new q(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Zr(o.status))throw new q(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(K.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),q.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Sa(s)||o0(s)?this._onresponse(s):_g(s)?this._onrequest(s,i):r0(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=q.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Br]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.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=e0(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 q(K.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:K.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Sa(e))r(e);else{let i=new q(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(Sa(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,n))}}if(s||this._progressHandlers.delete(n),Sa(e))o(e);else{let i=q.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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof q?i:new q(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vs,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Zr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new q(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof q?i:new q(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};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}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Br]:c}});let f=_=>{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(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let b=_ instanceof q?_:new q(K.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Ur(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{f(r?.signal?.reason)});let h=r?.timeout??BH,g=()=>f(q.fromError(K.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let S=this._responseHandlers.get(p);S?S(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},el,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},rl,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},a0,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Br]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Br]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Br]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=py(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=fy(e,o);return Promise.resolve(n(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,n){let r=py(e);this._notificationHandlers.set(r,o=>{let s=fy(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&_g(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new q(K.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new q(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new q(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new q(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=Ta.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Zr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new q(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zr(a.status))throw new q(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=Ta.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Zr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var Aa=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 Oa=class{};he._CodeOrName=Oa;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wo=class extends Oa{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=Wo;var pn=class extends Oa{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Wo&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=pn;he.nil=new pn("");function Q0(t,...e){let n=[t[0]],r=0;for(;r<e.length;)gy(n,e[r]),n.push(t[++r]);return new pn(n)}he._=Q0;var hy=new pn("+");function eT(t,...e){let n=[Ia(t[0])],r=0;for(;r<e.length;)n.push(hy),gy(n,e[r]),n.push(hy,Ia(t[++r]));return ZH(n),new pn(n)}he.str=eT;function gy(t,e){e instanceof pn?t.push(...e._items):e instanceof Wo?t.push(e):t.push(WH(e))}he.addCodeArg=gy;function ZH(t){let e=1;for(;e<t.length-1;){if(t[e]===hy){let n=qH(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function qH(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Wo||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 Wo))return`"${t}${e.slice(1)}`}function VH(t,e){return e.emptyStr()?t:t.emptyStr()?e:eT`${t}${e}`}he.strConcat=VH;function WH(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ia(Array.isArray(t)?t.join(","):t)}function KH(t){return new pn(Ia(t))}he.stringify=KH;function Ia(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Ia;function GH(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new pn(`.${t}`):Q0`[${t}]`}he.getProperty=GH;function JH(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new pn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=JH;function XH(t){return new pn(t.toString())}he.regexpCode=XH});var by=L(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.ValueScope=zt.ValueScopeName=zt.Scope=zt.varKinds=zt.UsedValueState=void 0;var Lt=Aa(),yy=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},xl;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(xl||(zt.UsedValueState=xl={}));zt.varKinds={const:new Lt.Name("const"),let:new Lt.Name("let"),var:new Lt.Name("var")};var Sl=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Lt.Name?e:this.name(e)}name(e){return new Lt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};zt.Scope=Sl;var vl=class extends Lt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Lt._)`.${new Lt.Name(n)}[${r}]`}};zt.ValueScopeName=vl;var YH=(0,Lt._)`\n`,_y=class extends Sl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?YH:Lt.nil}}get(){return this._scope}name(e){return new vl(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Lt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=Lt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,xl.Started);let l=n(u);if(l){let d=this.opts.es5?zt.varKinds.var:zt.varKinds.const;s=(0,Lt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Lt._)`${s}${l}${this.opts._n}`;else throw new yy(u);c.set(u,xl.Completed)})}return s}};zt.ValueScope=_y});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=Aa(),kn=by(),Vr=Aa();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Vr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Vr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return Vr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Vr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return Vr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Vr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return Vr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Vr.Name}});var Tl=by();Object.defineProperty(se,"Scope",{enumerable:!0,get:function(){return Tl.Scope}});Object.defineProperty(se,"ValueScope",{enumerable:!0,get:function(){return Tl.ValueScope}});Object.defineProperty(se,"ValueScopeName",{enumerable:!0,get:function(){return Tl.ValueScopeName}});Object.defineProperty(se,"varKinds",{enumerable:!0,get:function(){return Tl.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 dr=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},xy=class extends dr{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?kn.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=ei(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},kl=class extends dr{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ei(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return El(e,this.rhs)}},Sy=class extends kl{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},vy=class extends dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ky=class extends dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},wy=class extends dr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ey=class extends dr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=ei(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},Na=class extends dr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(QH(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Jo(e,n.names),{})}},pr=class extends Na{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ty=class extends Na{},Qs=class extends pr{};Qs.kind="else";var Ko=class t extends pr{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Qs(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(tT(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=ei(this.condition,e,n),this}get names(){let e=super.names;return El(e,this.condition),this.else&&Jo(e,this.else.names),e}};Ko.kind="if";var Go=class extends pr{};Go.kind="for";var $y=class extends Go{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=ei(this.iteration,e,n),this}get names(){return Jo(super.names,this.iteration.names)}},Py=class extends Go{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?kn.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=El(super.names,this.from);return El(e,this.to)}},wl=class extends Go{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=ei(this.iterable,e,n),this}get names(){return Jo(super.names,this.iterable.names)}},Da=class extends pr{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Da.kind="func";var Ma=class extends Na{render(e){return"return "+super.render(e)}};Ma.kind="return";var Ry=class extends pr{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Jo(e,this.catch.names),this.finally&&Jo(e,this.finally.names),e}},ja=class extends pr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ja.kind="catch";var La=class extends pr{render(e){return"finally"+super.render(e)}};La.kind="finally";var Cy=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
493
|
-
`:""},this._extScope=e,this._scope=new kn.Scope({parent:e}),this._nodes=[new Ty]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new xy(e,s,r)),s}const(e,n,r){return this._def(kn.varKinds.const,e,n,r)}let(e,n,r){return this._def(kn.varKinds.let,e,n,r)}var(e,n,r){return this._def(kn.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new kl(e,n,r))}add(e,n){return this._leafNode(new Sy(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Ey(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Ko(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ko(e))}else(){return this._elseNode(new Qs)}endIf(){return this._endBlockNode(Ko,Qs)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new $y(e),n)}forRange(e,n,r,o,s=this.opts.es5?kn.varKinds.var:kn.varKinds.let){let i=this._scope.toName(e);return this._for(new Py(s,i,n,r),()=>o(i))}forOf(e,n,r,o=kn.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new wl("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?kn.varKinds.var:kn.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new wl("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Go)}label(e){return this._leafNode(new vy(e))}break(e){return this._leafNode(new ky(e))}return(e){let n=new Ma;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ma)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ry;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new ja(s),n(s)}return r&&(this._currNode=o.finally=new La,this.code(r)),this._endBlockNode(ja,La)}throw(e){return this._leafNode(new wy(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new Da(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Da)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ko))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=Cy;function Jo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function El(t,e){return e instanceof pe._CodeOrName?Jo(t,e.names):t}function ei(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[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&&n[i.str]!==void 0)}}function QH(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function tT(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Oy(t)}`}se.not=tT;var eU=nT(se.operators.AND);function tU(...t){return t.reduce(eU)}se.and=tU;var nU=nT(se.operators.OR);function rU(...t){return t.reduce(nU)}se.or=rU;function nT(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${Oy(e)} ${t} ${Oy(n)}`}function Oy(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var fe=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 Te=oe(),oU=Aa();function sU(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=sU;function iU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(sT(t,e),!iT(e,t.self.RULES.all))}ae.alwaysValidSchema=iU;function sT(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||uT(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=sT;function iT(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=iT;function aU(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=aU;function cU({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Te._)`${n}`}return(0,Te._)`${t}${e}${(0,Te.getProperty)(r)}`}ae.schemaRefOrVal=cU;function uU(t){return aT(decodeURIComponent(t))}ae.unescapeFragment=uU;function lU(t){return encodeURIComponent(Ay(t))}ae.escapeFragment=lU;function Ay(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Ay;function aT(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=aT;function dU(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=dU;function rT({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Te.Name?(s instanceof Te.Name?t(o,s,i):e(o,s,i),i):s instanceof Te.Name?(e(o,i,s),s):n(s,i);return a===Te.Name&&!(c instanceof Te.Name)?r(o,c):c}}ae.mergeEvaluated={props:rT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,Te._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,Te._)`${n} || {}`).code((0,Te._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,Te._)`${n} || {}`),Ny(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:cT}),items:rT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,Te._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,Te._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function cT(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,Te._)`{}`);return e!==void 0&&Ny(t,n,e),n}ae.evaluatedPropsToName=cT;function Ny(t,e,n){Object.keys(n).forEach(r=>t.assign((0,Te._)`${e}${(0,Te.getProperty)(r)}`,!0))}ae.setEvaluated=Ny;var oT={};function pU(t,e){return t.scopeValue("func",{ref:e,code:oT[e.code]||(oT[e.code]=new oU._Code(e.code))})}ae.useFunc=pU;var Iy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Iy||(ae.Type=Iy={}));function fU(t,e,n){if(t instanceof Te.Name){let r=e===Iy.Num;return n?r?(0,Te._)`"[" + ${t} + "]"`:(0,Te._)`"['" + ${t} + "']"`:r?(0,Te._)`"/" + ${t}`:(0,Te._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Te.getProperty)(t).toString():"/"+Ay(t)}ae.getErrorPath=fU;function uT(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=uT});var fr=L(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var _t=oe(),mU={data:new _t.Name("data"),valCxt:new _t.Name("valCxt"),instancePath:new _t.Name("instancePath"),parentData:new _t.Name("parentData"),parentDataProperty:new _t.Name("parentDataProperty"),rootData:new _t.Name("rootData"),dynamicAnchors:new _t.Name("dynamicAnchors"),vErrors:new _t.Name("vErrors"),errors:new _t.Name("errors"),this:new _t.Name("this"),self:new _t.Name("self"),scope:new _t.Name("scope"),json:new _t.Name("json"),jsonPos:new _t.Name("jsonPos"),jsonLen:new _t.Name("jsonLen"),jsonPart:new _t.Name("jsonPart")};Dy.default=mU});var za=L(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.extendErrors=bt.resetErrorsCount=bt.reportExtraError=bt.reportError=bt.keyword$DataError=bt.keywordError=void 0;var me=oe(),$l=fe(),Pt=fr();bt.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};bt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,me.str)`"${t}" keyword must be ${e} ($data)`:(0,me.str)`"${t}" keyword is invalid ($data)`};function hU(t,e=bt.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=pT(t,e,n);r??(i||a)?lT(s,c):dT(o,(0,me._)`[${c}]`)}bt.reportError=hU;function gU(t,e=bt.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=pT(t,e,n);lT(o,a),s||i||dT(r,Pt.default.vErrors)}bt.reportExtraError=gU;function yU(t,e){t.assign(Pt.default.errors,e),t.if((0,me._)`${Pt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${Pt.default.vErrors}.length`,e),()=>t.assign(Pt.default.vErrors,null)))}bt.resetErrorsCount=yU;function _U({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Pt.default.errors,a=>{t.const(i,(0,me._)`${Pt.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(Pt.default.instancePath,s.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,me._)`${i}.schema`,n),t.assign((0,me._)`${i}.data`,r))})}bt.extendErrors=_U;function lT(t,e){let n=t.const("err",e);t.if((0,me._)`${Pt.default.vErrors} === null`,()=>t.assign(Pt.default.vErrors,(0,me._)`[${n}]`),(0,me._)`${Pt.default.vErrors}.push(${n})`),t.code((0,me._)`${Pt.default.errors}++`)}function dT(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,me._)`new ${t.ValidationError}(${e})`):(n.assign((0,me._)`${r}.errors`,e),n.return(!1))}var Xo={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function pT(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,me._)`{}`:bU(t,e,n)}function bU(t,e,n={}){let{gen:r,it:o}=t,s=[xU(o,n),SU(t,n)];return vU(t,e,s),r.object(...s)}function xU({errorPath:t},{instancePath:e}){let n=e?(0,me.str)`${t}${(0,$l.getErrorPath)(e,$l.Type.Str)}`:t;return[Pt.default.instancePath,(0,me.strConcat)(Pt.default.instancePath,n)]}function SU({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,me.str)`${e}/${t}`;return n&&(o=(0,me.str)`${o}${(0,$l.getErrorPath)(n,$l.Type.Str)}`),[Xo.schemaPath,o]}function vU(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Xo.keyword,o],[Xo.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&r.push([Xo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Xo.schema,i],[Xo.parentSchema,(0,me._)`${l}${d}`],[Pt.default.data,s]),u&&r.push([Xo.propertyName,u])}});var mT=L(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.boolOrEmptySchema=ti.topBoolOrEmptySchema=void 0;var kU=za(),wU=oe(),EU=fr(),TU={message:"boolean schema is false"};function $U(t){let{gen:e,schema:n,validateName:r}=t;n===!1?fT(t,!1):typeof n=="object"&&n.$async===!0?e.return(EU.default.data):(e.assign((0,wU._)`${r}.errors`,null),e.return(!0))}ti.topBoolOrEmptySchema=$U;function PU(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),fT(t)):n.var(e,!0)}ti.boolOrEmptySchema=PU;function fT(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,kU.reportError)(o,TU,void 0,e)}});var My=L(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.getRules=ni.isJSONType=void 0;var RU=["string","number","integer","boolean","null","object","array"],CU=new Set(RU);function OU(t){return typeof t=="string"&&CU.has(t)}ni.isJSONType=OU;function IU(){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:{}}}ni.getRules=IU});var jy=L(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.shouldUseRule=Wr.shouldUseGroup=Wr.schemaHasRulesForType=void 0;function AU({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&hT(t,r)}Wr.schemaHasRulesForType=AU;function hT(t,e){return e.rules.some(n=>gT(t,n))}Wr.shouldUseGroup=hT;function gT(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Wr.shouldUseRule=gT});var Ha=L(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.reportTypeError=xt.checkDataTypes=xt.checkDataType=xt.coerceAndCheckDataType=xt.getJSONTypes=xt.getSchemaTypes=xt.DataType=void 0;var NU=My(),DU=jy(),MU=za(),ne=oe(),yT=fe(),ri;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ri||(xt.DataType=ri={}));function jU(t){let e=_T(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}xt.getSchemaTypes=jU;function _T(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(NU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}xt.getJSONTypes=_T;function LU(t,e){let{gen:n,data:r,opts:o}=t,s=zU(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,DU.schemaHasRulesForType)(t,e[0]));if(i){let a=zy(e,r,o.strictNumbers,ri.Wrong);n.if(a,()=>{s.length?HU(t,e,s):Hy(t)})}return i}xt.coerceAndCheckDataType=LU;var bT=new Set(["string","number","integer","boolean","null"]);function zU(t,e){return e?t.filter(n=>bT.has(n)||e==="array"&&n==="array"):[]}function HU(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(zy(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(bT.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Hy(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),UU(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
|
|
492
|
+
]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[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 Wg,vn,HH,_l=x(()=>{Zr();vn={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:()=>(Wg===void 0&&(Wg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wg),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-_]*$/};HH=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function bl(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===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=yl(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===N.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===N.ZodBranded&&t.keyType._def.type._def.typeName===N.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=hl(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var xl=x(()=>{aa();Ye();_l();gl();fn()});function D0(t,e){if(e.mapStrategy==="record")return bl(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),r=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Gg=x(()=>{Ye();xl();fn()});function M0(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var Jg=x(()=>{});function j0(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var Xg=x(()=>{fn()});function L0(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yg=x(()=>{});function H0(t,e){if(e.target==="openApi3")return z0(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Aa&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Aa[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return z0(t,e)}var Aa,z0,Sl=x(()=>{Ye();Aa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};z0=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Y(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function U0(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:Aa[t.innerType._def.typeName],nullable:!0}:{type:[Aa[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Qg=x(()=>{Ye();Sl()});function F0(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Dg(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?de(n,"minimum",r.value,r.message,e):de(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),de(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?de(n,"maximum",r.value,r.message,e):de(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),de(n,"maximum",r.value,r.message,e));break;case"multipleOf":de(n,"multipleOf",r.value,r.message,e);break}return n}var ey=x(()=>{Zr()});function B0(t,e){let n=e.target==="openAi",r={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=BH(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=FH(t,e);return i!==void 0&&(r.additionalProperties=i),r}function FH(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 BH(t){try{return t.isOptional()}catch{return!0}}var ty=x(()=>{Ye()});var Z0,ny=x(()=>{Ye();fn();Z0=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:je(e)},n]}:je(e)}});var q0,ry=x(()=>{Ye();q0=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function V0(t,e){return Y(t.type._def,e)}var oy=x(()=>{Ye()});function W0(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var sy=x(()=>{Zr();Ye()});function K0(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var iy=x(()=>{Ye()});function G0(t){return{not:je(t)}}var ay=x(()=>{fn()});function J0(t){return je(t)}var cy=x(()=>{fn()});var X0,uy=x(()=>{Ye();X0=(t,e)=>Y(t.innerType._def,e)});var Y0,ly=x(()=>{aa();fn();Mg();jg();Lg();gl();zg();Ug();Fg();Bg();Zg();qg();Vg();Gg();Jg();Xg();Yg();Qg();ey();ty();ny();ry();oy();xl();sy();_l();iy();ay();Sl();cy();uy();Y0=(t,e,n)=>{switch(e){case N.ZodString:return yl(t,n);case N.ZodNumber:return F0(t,n);case N.ZodObject:return B0(t,n);case N.ZodBigInt:return T0(t,n);case N.ZodBoolean:return $0();case N.ZodDate:return Hg(t,n);case N.ZodUndefined:return G0(n);case N.ZodNull:return L0(n);case N.ZodArray:return E0(t,n);case N.ZodUnion:case N.ZodDiscriminatedUnion:return H0(t,n);case N.ZodIntersection:return I0(t,n);case N.ZodTuple:return K0(t,n);case N.ZodRecord:return bl(t,n);case N.ZodLiteral:return A0(t,n);case N.ZodEnum:return O0(t);case N.ZodNativeEnum:return M0(t);case N.ZodNullable:return U0(t,n);case N.ZodOptional:return Z0(t,n);case N.ZodMap:return D0(t,n);case N.ZodSet:return W0(t,n);case N.ZodLazy:return()=>t.getter()._def;case N.ZodPromise:return V0(t,n);case N.ZodNaN:case N.ZodNever:return j0(n);case N.ZodEffects:return C0(t,n);case N.ZodAny:return je(n);case N.ZodUnknown:return J0(n);case N.ZodDefault:return R0(t,n);case N.ZodBranded:return hl(t,n);case N.ZodReadonly:return X0(t,n);case N.ZodCatch:return P0(t,n);case N.ZodPipeline:return q0(t,n);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==v0)return a}if(r&&!n){let a=ZH(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Y0(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&qH(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var ZH,qH,Ye=x(()=>{pl();ly();ml();fn();ZH=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fl(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},qH=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Q0=x(()=>{});var dy,py=x(()=>{Ye();Ng();fn();dy=(t,e)=>{let n=w0(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Y(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??je(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??je(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 eT=x(()=>{pl();Ng();Zr();ml();Ye();Q0();fn();Mg();jg();Lg();gl();zg();Ug();Fg();Bg();Zg();qg();Vg();Gg();Jg();Xg();Yg();Qg();ey();ty();ny();ry();oy();uy();xl();sy();_l();iy();ay();Sl();cy();ly();py();py()});function VH(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function fy(t,e){return Zn(t)?eg(t,{target:VH(e?.target),io:e?.pipeStrategy??"input"}):dy(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function my(t){let n=Ur(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Zs(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function hy(t,e){let n=Hr(t,e);if(!n.success)throw n.error;return n.data}var gy=x(()=>{rg();xa();eT()});function tT(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function nT(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];tT(i)&&tT(s)?n[o]={...i,...s}:n[o]=s}return n}var WH,vl,rT=x(()=>{xa();Vo();x0();gy();WH=6e4,vl=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(Qu,n=>{this._oncancel(n)}),this.setNotificationHandler(tl,n=>{this._onprogress(n)}),this.setRequestHandler(el,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(nl,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new q(K.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ol,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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 q(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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new q(K.InvalidParams,`Task not found: ${s}`);if(!Br(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(Br(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Fr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(sl,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new q(K.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(al,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new q(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Br(o.status))throw new q(K.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(K.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),q.fromError(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),wa(s)||u0(s)?this._onresponse(s):xg(s)?this._onrequest(s,i):c0(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=q.fromError(K.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Fr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:K.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=s0(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 q(K.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let f=m.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(l,d,m)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:K.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),wa(e))r(e);else{let i=new q(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(wa(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,n))}}if(s||this._progressHandlers.delete(n),wa(e))o(e);else{let i=q.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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof q?i:new q(K.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vs,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},Br(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new q(K.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(K.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof q?i:new q(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};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}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};r?.onprogress&&(this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Fr]:c}});let f=_=>{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(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let b=_ instanceof q?_:new q(K.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Hr(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{f(r?.signal?.reason)});let h=r?.timeout??WH,g=()=>f(q.fromError(K.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let S=this._responseHandlers.get(p);S?S(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},rl,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},il,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},p0,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Fr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Fr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Fr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=my(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=hy(e,o);return Promise.resolve(n(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,n){let r=my(e);this._notificationHandlers.set(r,o=>{let s=hy(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&xg(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new q(K.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new q(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new q(K.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new q(K.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=Ra.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Br(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new q(K.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Br(a.status))throw new q(K.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=Ra.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Br(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}}});var Ma=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 Na=class{};he._CodeOrName=Na;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wo=class extends Na{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=Wo;var mn=class extends Na{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Wo&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=mn;he.nil=new mn("");function oT(t,...e){let n=[t[0]],r=0;for(;r<e.length;)_y(n,e[r]),n.push(t[++r]);return new mn(n)}he._=oT;var yy=new mn("+");function sT(t,...e){let n=[Da(t[0])],r=0;for(;r<e.length;)n.push(yy),_y(n,e[r]),n.push(yy,Da(t[++r]));return KH(n),new mn(n)}he.str=sT;function _y(t,e){e instanceof mn?t.push(...e._items):e instanceof Wo?t.push(e):t.push(XH(e))}he.addCodeArg=_y;function KH(t){let e=1;for(;e<t.length-1;){if(t[e]===yy){let n=GH(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function GH(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Wo||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 Wo))return`"${t}${e.slice(1)}`}function JH(t,e){return e.emptyStr()?t:t.emptyStr()?e:sT`${t}${e}`}he.strConcat=JH;function XH(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Da(Array.isArray(t)?t.join(","):t)}function YH(t){return new mn(Da(t))}he.stringify=YH;function Da(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Da;function QH(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new mn(`.${t}`):oT`[${t}]`}he.getProperty=QH;function eU(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new mn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=eU;function tU(t){return new mn(t.toString())}he.regexpCode=tU});var Sy=L(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.ValueScope=Ut.ValueScopeName=Ut.Scope=Ut.varKinds=Ut.UsedValueState=void 0;var Ht=Ma(),by=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},kl;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(kl||(Ut.UsedValueState=kl={}));Ut.varKinds={const:new Ht.Name("const"),let:new Ht.Name("let"),var:new Ht.Name("var")};var wl=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ht.Name?e:this.name(e)}name(e){return new Ht.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Ut.Scope=wl;var El=class extends Ht.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ht._)`.${new Ht.Name(n)}[${r}]`}};Ut.ValueScopeName=El;var nU=(0,Ht._)`\n`,xy=class extends wl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?nU:Ht.nil}}get(){return this._scope}name(e){return new El(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Ht._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=Ht.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,kl.Started);let l=n(u);if(l){let d=this.opts.es5?Ut.varKinds.var:Ut.varKinds.const;s=(0,Ht._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ht._)`${s}${l}${this.opts._n}`;else throw new by(u);c.set(u,kl.Completed)})}return s}};Ut.ValueScope=xy});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=Ma(),wn=Sy(),qr=Ma();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return qr._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return qr.str}});Object.defineProperty(se,"strConcat",{enumerable:!0,get:function(){return qr.strConcat}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return qr.nil}});Object.defineProperty(se,"getProperty",{enumerable:!0,get:function(){return qr.getProperty}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return qr.stringify}});Object.defineProperty(se,"regexpCode",{enumerable:!0,get:function(){return qr.regexpCode}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return qr.Name}});var Rl=Sy();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 dr=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},vy=class extends dr{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?wn.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=ei(this.rhs,e,n)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Tl=class extends dr{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ei(this.rhs,e,n),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return Pl(e,this.rhs)}},ky=class extends Tl{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},wy=class extends dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ey=class extends dr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ty=class extends dr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},$y=class extends dr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=ei(this.code,e,n),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},ja=class extends dr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(rU(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Jo(e,n.names),{})}},pr=class extends ja{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Py=class extends ja{},Qs=class extends pr{};Qs.kind="else";var Ko=class t extends pr{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Qs(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(iT(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=ei(this.condition,e,n),this}get names(){let e=super.names;return Pl(e,this.condition),this.else&&Jo(e,this.else.names),e}};Ko.kind="if";var Go=class extends pr{};Go.kind="for";var Ry=class extends Go{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=ei(this.iteration,e,n),this}get names(){return Jo(super.names,this.iteration.names)}},Cy=class extends Go{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?wn.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=Pl(super.names,this.from);return Pl(e,this.to)}},$l=class extends Go{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=ei(this.iterable,e,n),this}get names(){return Jo(super.names,this.iterable.names)}},La=class extends pr{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};La.kind="func";var za=class extends ja{render(e){return"return "+super.render(e)}};za.kind="return";var Oy=class extends pr{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Jo(e,this.catch.names),this.finally&&Jo(e,this.finally.names),e}},Ha=class extends pr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ha.kind="catch";var Ua=class extends pr{render(e){return"finally"+super.render(e)}};Ua.kind="finally";var Iy=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
493
|
+
`:""},this._extScope=e,this._scope=new wn.Scope({parent:e}),this._nodes=[new Py]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new vy(e,s,r)),s}const(e,n,r){return this._def(wn.varKinds.const,e,n,r)}let(e,n,r){return this._def(wn.varKinds.let,e,n,r)}var(e,n,r){return this._def(wn.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new Tl(e,n,r))}add(e,n){return this._leafNode(new ky(e,se.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new $y(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,pe.addCodeArg)(n,o));return n.push("}"),new pe._Code(n)}if(e,n,r){if(this._blockNode(new Ko(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ko(e))}else(){return this._elseNode(new Qs)}endIf(){return this._endBlockNode(Ko,Qs)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Ry(e),n)}forRange(e,n,r,o,s=this.opts.es5?wn.varKinds.var:wn.varKinds.let){let i=this._scope.toName(e);return this._for(new Cy(s,i,n,r),()=>o(i))}forOf(e,n,r,o=wn.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof pe.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),r(s)})}return this._for(new $l("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?wn.varKinds.var:wn.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new $l("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Go)}label(e){return this._leafNode(new wy(e))}break(e){return this._leafNode(new Ey(e))}return(e){let n=new za;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(za)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Oy;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new Ha(s),n(s)}return r&&(this._currNode=o.finally=new Ua,this.code(r)),this._endBlockNode(Ha,Ua)}throw(e){return this._leafNode(new Ty(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=pe.nil,r,o){return this._blockNode(new La(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(La)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ko))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};se.CodeGen=Iy;function Jo(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Pl(t,e){return e instanceof pe._CodeOrName?Jo(t,e.names):t}function ei(t,e,n){if(t instanceof pe.Name)return r(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=r(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[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&&n[i.str]!==void 0)}}function rU(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function iT(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${Ay(t)}`}se.not=iT;var oU=aT(se.operators.AND);function sU(...t){return t.reduce(oU)}se.and=sU;var iU=aT(se.operators.OR);function aU(...t){return t.reduce(iU)}se.or=aU;function aT(t){return(e,n)=>e===pe.nil?n:n===pe.nil?e:(0,pe._)`${Ay(e)} ${t} ${Ay(n)}`}function Ay(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var fe=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 Te=oe(),cU=Ma();function uU(t){let e={};for(let n of t)e[n]=!0;return e}ae.toHash=uU;function lU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(lT(t,e),!dT(e,t.self.RULES.all))}ae.alwaysValidSchema=lU;function lT(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||mT(t,`unknown keyword: "${s}"`)}ae.checkUnknownRules=lT;function dT(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ae.schemaHasRules=dT;function dU(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ae.schemaHasRulesButRef=dU;function pU({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Te._)`${n}`}return(0,Te._)`${t}${e}${(0,Te.getProperty)(r)}`}ae.schemaRefOrVal=pU;function fU(t){return pT(decodeURIComponent(t))}ae.unescapeFragment=fU;function mU(t){return encodeURIComponent(Dy(t))}ae.escapeFragment=mU;function Dy(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ae.escapeJsonPointer=Dy;function pT(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ae.unescapeJsonPointer=pT;function hU(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ae.eachItem=hU;function cT({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Te.Name?(s instanceof Te.Name?t(o,s,i):e(o,s,i),i):s instanceof Te.Name?(e(o,i,s),s):n(s,i);return a===Te.Name&&!(c instanceof Te.Name)?r(o,c):c}}ae.mergeEvaluated={props:cT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,Te._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,Te._)`${n} || {}`).code((0,Te._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,Te._)`${n} || {}`),My(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:fT}),items:cT({mergeNames:(t,e,n)=>t.if((0,Te._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,Te._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,Te._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,Te._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function fT(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,Te._)`{}`);return e!==void 0&&My(t,n,e),n}ae.evaluatedPropsToName=fT;function My(t,e,n){Object.keys(n).forEach(r=>t.assign((0,Te._)`${e}${(0,Te.getProperty)(r)}`,!0))}ae.setEvaluated=My;var uT={};function gU(t,e){return t.scopeValue("func",{ref:e,code:uT[e.code]||(uT[e.code]=new cU._Code(e.code))})}ae.useFunc=gU;var Ny;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ny||(ae.Type=Ny={}));function yU(t,e,n){if(t instanceof Te.Name){let r=e===Ny.Num;return n?r?(0,Te._)`"[" + ${t} + "]"`:(0,Te._)`"['" + ${t} + "']"`:r?(0,Te._)`"/" + ${t}`:(0,Te._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Te.getProperty)(t).toString():"/"+Dy(t)}ae.getErrorPath=yU;function mT(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ae.checkStrictMode=mT});var fr=L(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var St=oe(),_U={data:new St.Name("data"),valCxt:new St.Name("valCxt"),instancePath:new St.Name("instancePath"),parentData:new St.Name("parentData"),parentDataProperty:new St.Name("parentDataProperty"),rootData:new St.Name("rootData"),dynamicAnchors:new St.Name("dynamicAnchors"),vErrors:new St.Name("vErrors"),errors:new St.Name("errors"),this:new St.Name("this"),self:new St.Name("self"),scope:new St.Name("scope"),json:new St.Name("json"),jsonPos:new St.Name("jsonPos"),jsonLen:new St.Name("jsonLen"),jsonPart:new St.Name("jsonPart")};jy.default=_U});var Fa=L(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.extendErrors=vt.resetErrorsCount=vt.reportExtraError=vt.reportError=vt.keyword$DataError=vt.keywordError=void 0;var me=oe(),Cl=fe(),It=fr();vt.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};vt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,me.str)`"${t}" keyword must be ${e} ($data)`:(0,me.str)`"${t}" keyword is invalid ($data)`};function bU(t,e=vt.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=yT(t,e,n);r??(i||a)?hT(s,c):gT(o,(0,me._)`[${c}]`)}vt.reportError=bU;function xU(t,e=vt.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=yT(t,e,n);hT(o,a),s||i||gT(r,It.default.vErrors)}vt.reportExtraError=xU;function SU(t,e){t.assign(It.default.errors,e),t.if((0,me._)`${It.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${It.default.vErrors}.length`,e),()=>t.assign(It.default.vErrors,null)))}vt.resetErrorsCount=SU;function vU({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,It.default.errors,a=>{t.const(i,(0,me._)`${It.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(It.default.instancePath,s.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,me._)`${i}.schema`,n),t.assign((0,me._)`${i}.data`,r))})}vt.extendErrors=vU;function hT(t,e){let n=t.const("err",e);t.if((0,me._)`${It.default.vErrors} === null`,()=>t.assign(It.default.vErrors,(0,me._)`[${n}]`),(0,me._)`${It.default.vErrors}.push(${n})`),t.code((0,me._)`${It.default.errors}++`)}function gT(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,me._)`new ${t.ValidationError}(${e})`):(n.assign((0,me._)`${r}.errors`,e),n.return(!1))}var Xo={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function yT(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,me._)`{}`:kU(t,e,n)}function kU(t,e,n={}){let{gen:r,it:o}=t,s=[wU(o,n),EU(t,n)];return TU(t,e,s),r.object(...s)}function wU({errorPath:t},{instancePath:e}){let n=e?(0,me.str)`${t}${(0,Cl.getErrorPath)(e,Cl.Type.Str)}`:t;return[It.default.instancePath,(0,me.strConcat)(It.default.instancePath,n)]}function EU({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,me.str)`${e}/${t}`;return n&&(o=(0,me.str)`${o}${(0,Cl.getErrorPath)(n,Cl.Type.Str)}`),[Xo.schemaPath,o]}function TU(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Xo.keyword,o],[Xo.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&r.push([Xo.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Xo.schema,i],[Xo.parentSchema,(0,me._)`${l}${d}`],[It.default.data,s]),u&&r.push([Xo.propertyName,u])}});var bT=L(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.boolOrEmptySchema=ti.topBoolOrEmptySchema=void 0;var $U=Fa(),PU=oe(),RU=fr(),CU={message:"boolean schema is false"};function OU(t){let{gen:e,schema:n,validateName:r}=t;n===!1?_T(t,!1):typeof n=="object"&&n.$async===!0?e.return(RU.default.data):(e.assign((0,PU._)`${r}.errors`,null),e.return(!0))}ti.topBoolOrEmptySchema=OU;function IU(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),_T(t)):n.var(e,!0)}ti.boolOrEmptySchema=IU;function _T(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,$U.reportError)(o,CU,void 0,e)}});var Ly=L(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.getRules=ni.isJSONType=void 0;var AU=["string","number","integer","boolean","null","object","array"],NU=new Set(AU);function DU(t){return typeof t=="string"&&NU.has(t)}ni.isJSONType=DU;function MU(){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:{}}}ni.getRules=MU});var zy=L(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.shouldUseRule=Vr.shouldUseGroup=Vr.schemaHasRulesForType=void 0;function jU({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&xT(t,r)}Vr.schemaHasRulesForType=jU;function xT(t,e){return e.rules.some(n=>ST(t,n))}Vr.shouldUseGroup=xT;function ST(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Vr.shouldUseRule=ST});var Ba=L(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.reportTypeError=kt.checkDataTypes=kt.checkDataType=kt.coerceAndCheckDataType=kt.getJSONTypes=kt.getSchemaTypes=kt.DataType=void 0;var LU=Ly(),zU=zy(),HU=Fa(),ne=oe(),vT=fe(),ri;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ri||(kt.DataType=ri={}));function UU(t){let e=kT(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}kt.getSchemaTypes=UU;function kT(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(LU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}kt.getJSONTypes=kT;function FU(t,e){let{gen:n,data:r,opts:o}=t,s=BU(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,zU.schemaHasRulesForType)(t,e[0]));if(i){let a=Uy(e,r,o.strictNumbers,ri.Wrong);n.if(a,()=>{s.length?ZU(t,e,s):Fy(t)})}return i}kt.coerceAndCheckDataType=FU;var wT=new Set(["string","number","integer","boolean","null"]);function BU(t,e){return e?t.filter(n=>wT.has(n)||e==="array"&&n==="array"):[]}function ZU(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(Uy(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(let u of n)(wT.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Fy(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),qU(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
|
|
494
494
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
|
|
495
495
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
|
|
496
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function UU({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Ly(t,e,n,r=ri.Correct){let o=r===ri.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===ri.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}xt.checkDataType=Ly;function zy(t,e,n,r){if(t.length===1)return Ly(t[0],e,n,r);let o,s=(0,yT.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,Ly(i,e,n,r));return o}xt.checkDataTypes=zy;var FU={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Hy(t){let e=BU(t);(0,MU.reportError)(e,FU)}xt.reportTypeError=Hy;function BU(t){let{gen:e,data:n,schema:r}=t,o=(0,yT.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var ST=L(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});Pl.assignDefaults=void 0;var oi=oe(),ZU=fe();function qU(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)xT(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>xT(t,s,o.default))}Pl.assignDefaults=qU;function xT(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,oi._)`${s}${(0,oi.getProperty)(e)}`;if(o){(0,ZU.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,oi._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,oi._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,oi._)`${a} = ${(0,oi.stringify)(n)}`)}});var fn=L(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.validateUnion=Ee.validateArray=Ee.usePattern=Ee.callValidateCode=Ee.schemaProperties=Ee.allSchemaProperties=Ee.noPropertyInData=Ee.propertyInData=Ee.isOwnProperty=Ee.hasPropFunc=Ee.reportMissingProp=Ee.checkMissingProp=Ee.checkReportMissingProp=void 0;var Ie=oe(),Uy=fe(),Kr=fr(),VU=fe();function WU(t,e){let{gen:n,data:r,it:o}=t;n.if(By(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ie._)`${e}`},!0),t.error()})}Ee.checkReportMissingProp=WU;function KU({gen:t,data:e,it:{opts:n}},r,o){return(0,Ie.or)(...r.map(s=>(0,Ie.and)(By(t,e,s,n.ownProperties),(0,Ie._)`${o} = ${s}`)))}Ee.checkMissingProp=KU;function GU(t,e){t.setParams({missingProperty:e},!0),t.error()}Ee.reportMissingProp=GU;function vT(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ie._)`Object.prototype.hasOwnProperty`})}Ee.hasPropFunc=vT;function Fy(t,e,n){return(0,Ie._)`${vT(t)}.call(${e}, ${n})`}Ee.isOwnProperty=Fy;function JU(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} !== undefined`;return r?(0,Ie._)`${o} && ${Fy(t,e,n)}`:o}Ee.propertyInData=JU;function By(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} === undefined`;return r?(0,Ie.or)(o,(0,Ie.not)(Fy(t,e,n))):o}Ee.noPropertyInData=By;function kT(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ee.allSchemaProperties=kT;function XU(t,e){return kT(e).filter(n=>!(0,Uy.alwaysValidSchema)(t,e[n]))}Ee.schemaProperties=XU;function YU({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ie._)`${t}, ${e}, ${r}${o}`:e,d=[[Kr.default.instancePath,(0,Ie.strConcat)(Kr.default.instancePath,s)],[Kr.default.parentData,i.parentData],[Kr.default.parentDataProperty,i.parentDataProperty],[Kr.default.rootData,Kr.default.rootData]];i.opts.dynamicRef&&d.push([Kr.default.dynamicAnchors,Kr.default.dynamicAnchors]);let p=(0,Ie._)`${l}, ${n.object(...d)}`;return c!==Ie.nil?(0,Ie._)`${a}.call(${c}, ${p})`:(0,Ie._)`${a}(${p})`}Ee.callValidateCode=YU;var QU=(0,Ie._)`new RegExp`;function eF({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ie._)`${o.code==="new RegExp"?QU:(0,VU.useFunc)(t,o)}(${n}, ${r})`})}Ee.usePattern=eF;function tF(t){let{gen:e,data:n,keyword:r,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,Ie._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Uy.Type.Num},s),e.if((0,Ie.not)(s),a)})}}Ee.validateArray=tF;function nF(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Uy.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ie._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ie.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ee.validateUnion=nF});var TT=L(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.validateKeywordUsage=qn.validSchemaType=qn.funcKeywordCode=qn.macroKeywordCode=void 0;var Rt=oe(),Yo=fr(),rF=fn(),oF=za();function sF(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=ET(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Rt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qn.macroKeywordCode=sF;function iF(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;cF(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=ET(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)h(),e.modifying&&wT(t),g(()=>t.error());else{let y=e.async?m():f();e.modifying&&wT(t),g(()=>aF(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,Rt._)`await `),_=>r.assign(d,!1).if((0,Rt._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,Rt._)`${_}.errors`),()=>r.throw(_))),y}function f(){let y=(0,Rt._)`${l}.errors`;return r.assign(y,null),h(Rt.nil),y}function h(y=e.async?(0,Rt._)`await `:Rt.nil){let _=c.opts.passContext?Yo.default.this:Yo.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,Rt._)`${y}${(0,rF.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,Rt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}qn.funcKeywordCode=iF;function wT(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Rt._)`${r.parentData}[${r.parentDataProperty}]`))}function aF(t,e){let{gen:n}=t;n.if((0,Rt._)`Array.isArray(${e})`,()=>{n.assign(Yo.default.vErrors,(0,Rt._)`${Yo.default.vErrors} === null ? ${e} : ${Yo.default.vErrors}.concat(${e})`).assign(Yo.default.errors,(0,Rt._)`${Yo.default.vErrors}.length`),(0,oF.extendErrors)(t)},()=>t.error())}function cF({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ET(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Rt.stringify)(n)})}function uF(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}qn.validSchemaType=uF;function lF({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}qn.validateKeywordUsage=lF});var PT=L(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.extendSubschemaMode=Gr.extendSubschemaData=Gr.getSubschema=void 0;var Vn=oe(),$T=fe();function dF(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Vn._)`${t.schemaPath}${(0,Vn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Vn._)`${t.schemaPath}${(0,Vn.getProperty)(e)}${(0,Vn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$T.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Gr.getSubschema=dF;function pF(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Vn._)`${e.data}${(0,Vn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,Vn.str)`${u}${(0,$T.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Vn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Vn.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]}}Gr.extendSubschemaData=pF;function fF(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Gr.extendSubschemaMode=fF});var Zy=L((XY,RT)=>{"use strict";RT.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var OT=L((YY,CT)=>{"use strict";var Jr=CT.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Rl(e,r,o,t,"",t)};Jr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Jr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Jr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Jr.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 Rl(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Jr.arrayKeywords)for(var p=0;p<d.length;p++)Rl(t,e,n,d[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in Jr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Rl(t,e,n,d[m],o+"/"+l+"/"+mF(m),s,o,l,r,m)}else(l in Jr.keywords||t.allKeys&&!(l in Jr.skipKeywords))&&Rl(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function mF(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ua=L(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.getSchemaRefs=Ht.resolveUrl=Ht.normalizeId=Ht._getFullPath=Ht.getFullPath=Ht.inlineRef=void 0;var hF=fe(),gF=Zy(),yF=OT(),_F=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function bF(t,e=!0){return typeof t=="boolean"?!0:e===!0?!qy(t):e?IT(t)<=e:!1}Ht.inlineRef=bF;var xF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qy(t){for(let e in t){if(xF.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(qy)||typeof n=="object"&&qy(n))return!0}return!1}function IT(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!_F.has(n)&&(typeof t[n]=="object"&&(0,hF.eachItem)(t[n],r=>e+=IT(r)),e===1/0))return 1/0}return e}function AT(t,e="",n){n!==!1&&(e=si(e));let r=t.parse(e);return NT(t,r)}Ht.getFullPath=AT;function NT(t,e){return t.serialize(e).split("#")[0]+"#"}Ht._getFullPath=NT;var SF=/#\/?$/;function si(t){return t?t.replace(SF,""):""}Ht.normalizeId=si;function vF(t,e,n){return n=si(n),t.resolve(e,n)}Ht.resolveUrl=vF;var kF=/^[a-z_][-a-z0-9._]*$/i;function wF(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=si(t[n]||e),s={"":o},i=AT(r,o,!1),a={},c=new Set;return yF(t,{allKeys:!0},(d,p,m,f)=>{if(f===void 0)return;let h=i+p,g=s[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(b){let S=this.opts.uriResolver.resolve;if(b=si(g?S(g,b):b),c.has(b))throw l(b);c.add(b);let T=this.refs[b];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,b):b!==si(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!kF.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,p,m){if(p!==void 0&&!gF(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ht.getSchemaRefs=wF});var Za=L(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.getData=Xr.KeywordCxt=Xr.validateFunctionCode=void 0;var zT=mT(),DT=Ha(),Wy=jy(),Cl=Ha(),EF=ST(),Ba=TT(),Vy=PT(),W=oe(),ee=fr(),TF=Ua(),mr=fe(),Fa=za();function $F(t){if(FT(t)&&(BT(t),UT(t))){CF(t);return}HT(t,()=>(0,zT.topBoolOrEmptySchema)(t))}Xr.validateFunctionCode=$F;function HT({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,W._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,W._)`"use strict"; ${MT(n,o)}`),RF(t,o),t.code(s)}):t.func(e,(0,W._)`${ee.default.data}, ${PF(o)}`,r.$async,()=>t.code(MT(n,o)).code(s))}function PF(t){return(0,W._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,W._)`, ${ee.default.dynamicAnchors}={}`:W.nil}}={}`}function RF(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,W._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,W._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,W._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,W._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,W._)`""`),t.var(ee.default.parentData,(0,W._)`undefined`),t.var(ee.default.parentDataProperty,(0,W._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`{}`)})}function CF(t){let{schema:e,opts:n,gen:r}=t;HT(t,()=>{n.$comment&&e.$comment&&qT(t),DF(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&OF(t),ZT(t),LF(t)})}function OF(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,W._)`${n}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function MT(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${n} */`:W.nil}function IF(t,e){if(FT(t)&&(BT(t),UT(t))){AF(t,e);return}(0,zT.boolOrEmptySchema)(t,e)}function UT({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function FT(t){return typeof t.schema!="boolean"}function AF(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&qT(t),MF(t),jF(t);let s=r.const("_errs",ee.default.errors);ZT(t,s),r.var(e,(0,W._)`${s} === ${ee.default.errors}`)}function BT(t){(0,mr.checkUnknownRules)(t),NF(t)}function ZT(t,e){if(t.opts.jtd)return jT(t,[],!1,e);let n=(0,DT.getSchemaTypes)(t.schema),r=(0,DT.coerceAndCheckDataType)(t,n);jT(t,n,!r,e)}function NF(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,mr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function DF(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,mr.checkStrictMode)(t,"default is ignored in the schema root")}function MF(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,TF.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function jF(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qT({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,W._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,W.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function LF(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,W._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,W._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,W._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&zF(t),e.return((0,W._)`${ee.default.errors} === 0`))}function zF({gen:t,evaluated:e,props:n,items:r}){n instanceof W.Name&&t.assign((0,W._)`${e}.props`,n),r instanceof W.Name&&t.assign((0,W._)`${e}.items`,r)}function jT(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,mr.schemaHasRulesButRef)(s,l))){o.block(()=>WT(t,"$ref",l.all.$ref.definition));return}c.jtd||HF(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Wy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Cl.checkDataType)(p.type,i,c.strictNumbers)),LT(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,Cl.reportTypeError)(t)),o.endIf()):LT(t,p),a||o.if((0,W._)`${ee.default.errors} === ${r||0}`))}}function LT(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,EF.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,Wy.shouldUseRule)(r,s)&&WT(t,s.keyword,s.definition,e.type)})}function HF(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(UF(t,e),t.opts.allowUnionTypes||FF(t,e),BF(t,t.dataTypes))}function UF(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{VT(t.dataTypes,n)||Ky(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),qF(t,e)}}function FF(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ky(t,"use allowUnionTypes to allow union type keyword")}function BF(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Wy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>ZF(e,i))&&Ky(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function ZF(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function VT(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function qF(t,e){let n=[];for(let r of t.dataTypes)VT(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Ky(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,mr.checkStrictMode)(t,e,t.opts.strictTypes)}var Ol=class{constructor(e,n,r){if((0,Ba.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,mr.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",KT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ba.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,W.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,W.not)(e),void 0,n)}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:n}=this;this.fail((0,W._)`${n} !== undefined && (${(0,W.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Fa.reportExtraError:Fa.reportError)(this,this.def.error,n)}$dataError(){(0,Fa.reportError)(this,this.def.$dataError||Fa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Fa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=W.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=W.nil,n=W.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,W.or)((0,W._)`${o} === undefined`,n)),e!==W.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(r.length){if(!(n instanceof W.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,W._)`${(0,Cl.checkDataTypes)(c,n,s.opts.strictNumbers,Cl.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${n})`}return W.nil}}subschema(e,n){let r=(0,Vy.getSubschema)(this.it,e);(0,Vy.extendSubschemaData)(r,this.it,e),(0,Vy.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return IF(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=mr.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=mr.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,W.Name)),!0}};Xr.KeywordCxt=Ol;function WT(t,e,n,r){let o=new Ol(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Ba.funcKeywordCode)(o,n):"macro"in n?(0,Ba.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Ba.funcKeywordCode)(o,n)}var VF=/^\/(?:[^~]|~0|~1)*$/,WF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function KT(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!VF.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=WF.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,W._)`${s}${(0,W.getProperty)((0,mr.unescapeJsonPointer)(u))}`,i=(0,W._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Xr.getData=KT});var Il=L(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var Gy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Jy.default=Gy});var qa=L(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var Xy=Ua(),Yy=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Xy.resolveUrl)(e,n,r),this.missingSchema=(0,Xy.normalizeId)((0,Xy.getFullPath)(e,this.missingRef))}};Qy.default=Yy});var Nl=L(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.resolveSchema=mn.getCompilingSchema=mn.resolveRef=mn.compileSchema=mn.SchemaEnv=void 0;var wn=oe(),KF=Il(),Qo=fr(),En=Ua(),GT=fe(),GF=Za(),ii=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,En.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};mn.SchemaEnv=ii;function t_(t){let e=JT.call(this,t);if(e)return e;let n=(0,En.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new wn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:KF.default,code:(0,wn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Qo.default.data,parentData:Qo.default.parentData,parentDataProperty:Qo.default.parentDataProperty,dataNames:[Qo.default.data],dataPathArr:[wn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,wn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:wn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,GF.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Qo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Qo.default.self}`,`${Qo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof wn.Name?void 0:f,items:h instanceof wn.Name?void 0:h,dynamicProps:f instanceof wn.Name,dynamicItems:h instanceof wn.Name},m.source&&(m.source.evaluated=(0,wn.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}mn.compileSchema=t_;function JF(t,e,n){var r;n=(0,En.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=QF.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new ii({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=XF.call(this,s)}mn.resolveRef=JF;function XF(t){return(0,En.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:t_.call(this,t)}function JT(t){for(let e of this._compilations)if(YF(e,t))return e}mn.getCompilingSchema=JT;function YF(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function QF(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Al.call(this,t,e)}function Al(t,e){let n=this.opts.uriResolver.parse(e),r=(0,En._getFullPath)(this.opts.uriResolver,n),o=(0,En.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return e_.call(this,n,t);let s=(0,En.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Al.call(this,t,i);return typeof a?.schema!="object"?void 0:e_.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||t_.call(this,i),s===(0,En.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,En.resolveUrl)(this.opts.uriResolver,o,u)),new ii({schema:a,schemaId:c,root:t,baseId:o})}return e_.call(this,n,i)}}mn.resolveSchema=Al;var eB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function e_(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,GT.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!eB.has(a)&&u&&(e=(0,En.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,GT.schemaHasRulesButRef)(n,this.RULES)){let a=(0,En.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=Al.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new ii({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var XT=L((o7,tB)=>{tB.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 a_=L((s7,o$)=>{"use strict";var nB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r_=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),rB=RegExp.prototype.test.bind(/^\d*$/u),es=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o_=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),QT=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),s_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),oB=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Ut=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Ut[e]="%"+t[e>>4]+t[e&15]}function St(t){return t<2048?Ut[192|t>>6]+Ut[128|t&63]:t<65536?Ut[224|t>>12]+Ut[128|t>>6&63]+Ut[128|t&63]:Ut[240|t>>18]+Ut[128|t>>12&63]+Ut[128|t>>6&63]+Ut[128|t&63]}function sB(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var iB=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),aB=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),cB=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),uB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function lB(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!cB(t[e])){if(t[e]==="%"&&e+2<t.length&&es(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function YT(t){let e=-1,n=0,r=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(r===-1&&(r=a),o++,o>n&&(n=o,e=r)):(r=-1,o=0);if(n<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+n).join(":");return s+"::"+i}function dB(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let n=e===-1?t.split(":"):t.slice(0,e).split(":"),r=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(n.length===1&&n[0]===""&&(n.length=0),r.length===1&&r[0]===""&&(r.length=0));let o=n.concat(r),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&r.length===0||!r_(c))return;s+=2;continue}if(!iB(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:YT(o);if(s>=8)return;let i=o.slice(0,n.length);for(let a=s;a<8;a++)i.push("0");for(let a=n.length;a<o.length;a++)i.push(o[a]);return YT(i)}function n_(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let r=e?t.slice(1,-1):t;if(e&&aB(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(pB(r,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=r.indexOf("%");if(s!==-1){let a=r.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=r.slice(s+a),!lB(o))return{host:t,isIPV6:!1,error:!0};r=r.slice(0,s)}let i=dB(r);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function pB(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function fB(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var mB={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},hB=/[@/?#:]/g,gB=/[@/?#]/g;function e$(t,e){let n=e?gB:hB;return n.lastIndex=0,t.replace(n,r=>mB[r])}function t$(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&o_(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function yB(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&o_(i)?e+=i:e+="%"+s,n+=2;continue}}if(QT(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=r$(o)?r:Ut[o];else if(o<55296||o>57343)e+=St(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=St(65536+(o-55296<<10)+(s-56320)),n++):e+=St(65533)}else e+=St(65533)}}return e}function _B(t,e=!1){let n="",r=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(es(i)){n+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(r=!1),QT(s)&&(s!==":"||!r))n+=s;else{let i=t.charCodeAt(o);if(i<128)n+=Ut[i];else if(i<55296||i>57343)n+=St(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(n+=St(65536+(i-55296<<10)+(a-56320)),o++):n+=St(65533)}else n+=St(65533)}}return n}function i_(t,e){let n="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(es(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(e(o))n+=o;else{let s=t.charCodeAt(r);if(s<128)n+=Ut[s];else if(s<55296||s>57343)n+=St(s);else if(s<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(n+=St(65536+(s-55296<<10)+(i-56320)),r++):n+=St(65533)}else n+=St(65533)}}return n}function n$(t){return i_(t,oB)}function bB(t){return i_(t,s_)}function xB(t){return i_(t,s_)}function r$(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function SB(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));o_(i)?e+=i:e+="%"+s,n+=2;continue}}if(s_(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=r$(o)?r:Ut[o];else if(o<55296||o>57343)e+=St(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=St(65536+(o-55296<<10)+(s-56320)),n++):e+=St(65533)}else e+=St(65533)}}return e}function vB(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(es(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function kB(t){let e=[];if(t.userinfo!==void 0&&(e.push(n$(t.userinfo)),e.push("@")),t.host!==void 0){let n=t.host;if(!r_(n)){let r=n_(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=t$(n,!0),r=n_(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=e$(n,!1)}e.push(n)}if(typeof t.port=="number"||typeof t.port=="string"){let n=String(t.port);if(!rB(n))throw new TypeError("URI port is malformed.");e.push(":"),e.push(n)}return e.length?e.join(""):void 0}o$.exports={nonSimpleDomain:uB,recomposeAuthority:kB,reescapeHostDelimiters:e$,normalizePercentEncoding:t$,normalizePathEncoding:yB,serializePathEncoding:_B,normalizeQueryFragmentEncoding:SB,encodeUserinfo:n$,encodeQuery:bB,encodeFragment:xB,escapePreservingEscapes:vB,removeDotSegments:fB,isIPv4:r_,isUUID:nB,normalizeIPv6:n_,stringArrayToHexStripped:sB}});var u$=L((i7,c$)=>{"use strict";var{isUUID:wB}=a_(),EB=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,TB=["http","https","ws","wss","urn","urn:uuid"];function $B(t){return TB.indexOf(t)!==-1}function c_(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 s$(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function i$(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 PB(t){return t.secure=c_(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function RB(t){if((t.port===(c_(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),n=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=n&&n!=="/"?n:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function CB(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(EB);if(n&&n[0]===t.path){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=u_(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function OB(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=u_(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function IB(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!wB(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function AB(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var a$={scheme:"http",domainHost:!0,parse:s$,serialize:i$},NB={scheme:"https",domainHost:a$.domainHost,parse:s$,serialize:i$},Dl={scheme:"ws",domainHost:!0,parse:PB,serialize:RB},DB={scheme:"wss",domainHost:Dl.domainHost,parse:Dl.parse,serialize:Dl.serialize},MB={scheme:"urn",parse:CB,serialize:OB,skipNormalize:!0},jB={scheme:"urn:uuid",parse:IB,serialize:AB,skipNormalize:!0},Ml={http:a$,https:NB,ws:Dl,wss:DB,urn:MB,"urn:uuid":jB};Object.setPrototypeOf(Ml,null);function u_(t){return t&&(Ml[t]||Ml[t.toLowerCase()])||void 0}c$.exports={wsIsSecure:c_,SCHEMES:Ml,isValidSchemeName:$B,getSchemeHandler:u_}});var k$=L((a7,zl)=>{"use strict";var{normalizeIPv6:m$,removeDotSegments:Wa,recomposeAuthority:LB,normalizePercentEncoding:h$,normalizePathEncoding:zB,serializePathEncoding:l$,normalizeQueryFragmentEncoding:d$,encodeQuery:HB,encodeFragment:UB,reescapeHostDelimiters:FB,isIPv4:g$,nonSimpleDomain:BB}=a_(),{SCHEMES:y$,getSchemeHandler:l_}=u$(),_$=/^[A-Za-z][A-Za-z0-9+.-]*$/u,b$="URI scheme is malformed.";function p$(t){let e=unescape(String(t));if(!_$.test(e))throw new TypeError(b$);return e}function ZB(t,e){return typeof t=="string"?t=YB(t,e):typeof t=="object"&&(t=Ll(ts(t,e),e)),t}function qB(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=jl(t,r),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=jl(e,r);if(s||d||i||p||a||m||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=x$(o,l,r,!0),y=l_(n&&n.scheme||g.scheme),_=g.host,b=_!==void 0&&_!==""&&(g$(_)||m$(_).isIPV6);S$(g,n||{},y,b);let S=_&&_.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(_);if(g.error&&!S)throw new Error(g.error);return r.skipEscape=!0,ts(g,r)}function x$(t,e,n,r){let o={};return r||(t=Ll(ts(t,n),n),e=Ll(ts(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Wa(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=Wa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Wa(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=Wa(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 VB(t,e,n){let r=f$(t,n),o=f$(e,n);return r!==void 0&&o!==void 0&&r===o}function ts(t,e){let n={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:""},r=Object.assign({},e),o=[];n.scheme&&(n.scheme=p$(n.scheme));let s=l_(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r);let i=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,a=!r.skipEscape&&n.scheme===void 0&&!i;n.path!==void 0&&(r.skipEscape?n.path=h$(n.path):n.path=l$(n.path,a)),r.reference!=="suffix"&&n.scheme&&(n.scheme=p$(n.scheme),o.push(n.scheme,":"));let c=LB(n);if(c!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(c),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let u=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(u=Wa(u)),a&&(u=l$(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return n.query!==void 0&&o.push("?",HB(n.query)),n.fragment!==void 0&&o.push("#",UB(n.fragment)),o.join("")}var WB=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,KB=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,GB=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function JB(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Va(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function d_(t){return t[0]==="["&&t[t.length-1]==="]"}function XB(t){let e=t[4];return Va(t[3])||e!==void 0&&!d_(e)&&Va(e)||Va(t[6])||Va(t[7])||Va(t[8])}function S$(t,e,n,r){if(!e.unicodeSupport&&(!n||!n.unicodeSupport)&&t.host&&!d_(t.host)&&(e.domainHost||n&&n.domainHost)&&r===!1&&BB(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function jl(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let d=t.match(KB);d!==null&&d[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(GB);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(WB);if(m){if(r.scheme=m[1],r.userinfo=m[3],r.host=m[4],r.port=parseInt(m[5],10),r.path=m[6]||"",r.query=m[7],r.fragment=m[8],r.scheme!==void 0){let g=unescape(r.scheme);_$.test(g)?r.scheme=g.toLowerCase():(r.error=r.error||b$,u=!0)}s=XB(m),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=m[5]);let f=JB(r,m);if(f!==void 0&&(r.error=r.error||f,o=!0),r.host)if(g$(r.host)===!1){let y=d_(r.host),_=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,b=m$(r.host);l=b.isIPV6||b.isIPVFuture===!0,c=_&&(!y||b.error===!0),r.host=l?b.host:b.host.toLowerCase(),c&&(r.error=r.error||"URI host is malformed.",o=!0)}else l=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let h=l_(n.scheme||r.scheme);if(c||(a=S$(r,n,h,l)),!h||h&&!h.skipNormalize){if(t.indexOf("%")!==-1&&r.host!==void 0&&!c){let g=l?r.host:h$(r.host,!0);r.host=FB(g,l)}r.path&&(r.path=zB(r.path)),r.query&&(r.query=d$(r.query)),r.fragment&&(r.fragment=d$(r.fragment))}h&&h.parse&&(h.parse(r,n),h===y$.urn&&r.nid===void 0&&(i=!0))}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ll(t,e){return jl(t,e).parsed}function YB(t,e){return v$(t,e).normalized}function v$(t,e){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=jl(t,e);return{normalized:r||o||s||i||a?t:ts(n,e),malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function f$(t,e){if(typeof t!="string"&&typeof t!="object")return;let n;try{n=typeof t=="string"?t:ts(t,e)}catch{return}let{normalized:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=v$(n,e);return o||s||i||a||c?void 0:r}var p_={SCHEMES:y$,normalize:ZB,resolve:qB,resolveComponent:x$,equal:VB,serialize:ts,parse:Ll};zl.exports=p_;zl.exports.default=p_;zl.exports.fastUri=p_});var E$=L(f_=>{"use strict";Object.defineProperty(f_,"__esModule",{value:!0});var w$=k$();w$.code='require("ajv/dist/runtime/uri").default';f_.default=w$});var A$=L(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.CodeGen=pt.Name=pt.nil=pt.stringify=pt.str=pt._=pt.KeywordCxt=void 0;var QB=Za();Object.defineProperty(pt,"KeywordCxt",{enumerable:!0,get:function(){return QB.KeywordCxt}});var ai=oe();Object.defineProperty(pt,"_",{enumerable:!0,get:function(){return ai._}});Object.defineProperty(pt,"str",{enumerable:!0,get:function(){return ai.str}});Object.defineProperty(pt,"stringify",{enumerable:!0,get:function(){return ai.stringify}});Object.defineProperty(pt,"nil",{enumerable:!0,get:function(){return ai.nil}});Object.defineProperty(pt,"Name",{enumerable:!0,get:function(){return ai.Name}});Object.defineProperty(pt,"CodeGen",{enumerable:!0,get:function(){return ai.CodeGen}});var e2=Il(),C$=qa(),t2=My(),Ka=Nl(),n2=oe(),Ga=Ua(),Hl=Ha(),h_=fe(),T$=XT(),r2=E$(),O$=(t,e)=>new RegExp(t,e);O$.code="new RegExp";var o2=["removeAdditional","useDefaults","coerceTypes"],s2=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),i2={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."},a2={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$$=200;function c2(t){var e,n,r,o,s,i,a,c,u,l,d,p,m,f,h,g,y,_,b,S,T,D,v,$,P;let A=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,z=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:O$,B=(o=t.uriResolver)!==null&&o!==void 0?o:r2.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:A)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:A)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:A)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:A)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:C,regExp:z}:{optimize:C,regExp:z},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:$$,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:$$,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:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(v=t.validateFormats)!==null&&v!==void 0?v:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:B}}var Ja=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,...c2(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new n2.ValueScope({scope:{},prefixes:s2,es5:n,lines:r}),this.logger=m2(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,t2.getRules)(),P$.call(this,i2,e,"NOT SUPPORTED"),P$.call(this,a2,e,"DEPRECATED","warn"),this._metaOpts=p2.call(this),e.formats&&l2.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&d2.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),u2.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=T$;r==="id"&&(o={...T$},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);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 C$.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ga.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=R$.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Ka.SchemaEnv({schema:{},schemaId:r});if(n=Ka.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=R$.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ga.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(g2.call(this,r,n),!n)return(0,h_.eachItem)(r,s=>m_.call(this,s)),this;_2.call(this,n);let o={...n,type:(0,Hl.getJSONTypes)(n.type),schemaType:(0,Hl.getJSONTypes)(n.schemaType)};return(0,h_.eachItem)(r,o.type.length===0?s=>m_.call(this,s,o):s=>o.type.forEach(i=>m_.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=I$(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ga.normalizeId)(i||r);let u=Ga.getSchemaRefs.call(this,e,r);return c=new Ka.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):Ka.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Ka.compileSchema.call(this,e)}finally{this.opts=n}}};Ja.ValidationError=e2.default;Ja.MissingRefError=C$.default;pt.default=Ja;function P$(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function R$(t){return t=(0,Ga.normalizeId)(t),this.schemas[t]||this.refs[t]}function u2(){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 l2(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function d2(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function p2(){let t={...this.opts};for(let e of o2)delete t[e];return t}var f2={log(){},warn(){},error(){}};function m2(t){if(t===!1)return f2;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 h2=/^[a-z_$][a-z0-9_$:-]*$/i;function g2(t,e){let{RULES:n}=this;if((0,h_.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!h2.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function m_(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,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?y2.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function y2(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function _2(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=I$(e)),t.validateSchema=this.compile(e,!0))}var b2={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function I$(t){return{anyOf:[t,b2]}}});var N$=L(g_=>{"use strict";Object.defineProperty(g_,"__esModule",{value:!0});var x2={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};g_.default=x2});var L$=L(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.callRef=ns.getValidate=void 0;var S2=qa(),D$=fn(),Ft=oe(),ci=fr(),M$=Nl(),Ul=fe(),v2={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=M$.resolveRef.call(c,u,o,n);if(l===void 0)throw new S2.default(r.opts.uriResolver,o,n);if(l instanceof M$.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return Fl(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return Fl(t,(0,Ft._)`${f}.validate`,u,u.$async)}function p(f){let h=j$(t,f);Fl(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Ft.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:Ft.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function j$(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Ft._)`${n.scopeValue("wrapper",{ref:e})}.validate`}ns.getValidate=j$;function Fl(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ci.default.this:Ft.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Ft._)`await ${(0,D$.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,Ft._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,D$.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,Ft._)`${f}.errors`;o.assign(ci.default.vErrors,(0,Ft._)`${ci.default.vErrors} === null ? ${h} : ${ci.default.vErrors}.concat(${h})`),o.assign(ci.default.errors,(0,Ft._)`${ci.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Ul.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,Ft._)`${f}.evaluated.props`);s.props=Ul.mergeEvaluated.props(o,y,s.props,Ft.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Ul.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,Ft._)`${f}.evaluated.items`);s.items=Ul.mergeEvaluated.items(o,y,s.items,Ft.Name)}}}ns.callRef=Fl;ns.default=v2});var z$=L(y_=>{"use strict";Object.defineProperty(y_,"__esModule",{value:!0});var k2=N$(),w2=L$(),E2=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",k2.default,w2.default];y_.default=E2});var H$=L(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var Bl=oe(),Yr=Bl.operators,Zl={maximum:{okStr:"<=",ok:Yr.LTE,fail:Yr.GT},minimum:{okStr:">=",ok:Yr.GTE,fail:Yr.LT},exclusiveMaximum:{okStr:"<",ok:Yr.LT,fail:Yr.GTE},exclusiveMinimum:{okStr:">",ok:Yr.GT,fail:Yr.LTE}},T2={message:({keyword:t,schemaCode:e})=>(0,Bl.str)`must be ${Zl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Bl._)`{comparison: ${Zl[t].okStr}, limit: ${e}}`},$2={keyword:Object.keys(Zl),type:"number",schemaType:"number",$data:!0,error:T2,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Bl._)`${n} ${Zl[e].fail} ${r} || isNaN(${n})`)}};__.default=$2});var U$=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var Xa=oe(),P2={message:({schemaCode:t})=>(0,Xa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Xa._)`{multipleOf: ${t}}`},R2={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:P2,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Xa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Xa._)`${i} !== parseInt(${i})`;t.fail$data((0,Xa._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};b_.default=R2});var B$=L(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});function F$(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}x_.default=F$;F$.code='require("ajv/dist/runtime/ucs2length").default'});var Z$=L(S_=>{"use strict";Object.defineProperty(S_,"__esModule",{value:!0});var rs=oe(),C2=fe(),O2=B$(),I2={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,rs.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,rs._)`{limit: ${t}}`},A2={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:I2,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?rs.operators.GT:rs.operators.LT,i=o.opts.unicode===!1?(0,rs._)`${n}.length`:(0,rs._)`${(0,C2.useFunc)(t.gen,O2.default)}(${n})`;t.fail$data((0,rs._)`${i} ${s} ${r}`)}};S_.default=A2});var q$=L(v_=>{"use strict";Object.defineProperty(v_,"__esModule",{value:!0});var N2=fn(),D2=fe(),ui=oe(),M2={message:({schemaCode:t})=>(0,ui.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ui._)`{pattern: ${t}}`},j2={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:M2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ui._)`new RegExp`:(0,D2.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ui._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ui._)`!${l}`)}else{let c=(0,N2.usePattern)(t,o);t.fail$data((0,ui._)`!${c}.test(${n})`)}}};v_.default=j2});var V$=L(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var Ya=oe(),L2={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ya.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ya._)`{limit: ${t}}`},z2={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:L2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ya.operators.GT:Ya.operators.LT;t.fail$data((0,Ya._)`Object.keys(${n}).length ${o} ${r}`)}};k_.default=z2});var W$=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var Qa=fn(),ec=oe(),H2=fe(),U2={message:({params:{missingProperty:t}})=>(0,ec.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ec._)`{missingProperty: ${t}}`},F2={keyword:"required",type:"object",schemaType:"array",$data:!0,error:U2,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of n)if(m?.[h]===void 0&&!f.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,H2.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ec.nil,d);else for(let m of n)(0,Qa.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,Qa.checkMissingProp)(t,n,m)),(0,Qa.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,Qa.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(f,(0,Qa.propertyInData)(e,o,m,a.ownProperties)),e.if((0,ec.not)(f),()=>{t.error(),e.break()})},ec.nil)}}};w_.default=F2});var K$=L(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var tc=oe(),B2={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,tc.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,tc._)`{limit: ${t}}`},Z2={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:B2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?tc.operators.GT:tc.operators.LT;t.fail$data((0,tc._)`${n}.length ${o} ${r}`)}};E_.default=Z2});var ql=L(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});var G$=Zy();G$.code='require("ajv/dist/runtime/equal").default';T_.default=G$});var J$=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var $_=Ha(),ft=oe(),q2=fe(),V2=ql(),W2={message:({params:{i:t,j:e}})=>(0,ft.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ft._)`{i: ${t}, j: ${e}}`},K2={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:W2,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,$_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ft._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,ft._)`${n}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,ft._)`${f} > 1`,()=>(d()?p:m)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let g=e.name("item"),y=(0,$_.checkDataTypes)(u,g,a.opts.strictNumbers,$_.DataType.Wrong),_=e.const("indices",(0,ft._)`{}`);e.for((0,ft._)`;${f}--;`,()=>{e.let(g,(0,ft._)`${n}[${f}]`),e.if(y,(0,ft._)`continue`),u.length>1&&e.if((0,ft._)`typeof ${g} == "string"`,(0,ft._)`${g} += "_"`),e.if((0,ft._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,ft._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ft._)`${_}[${g}] = ${f}`)})}function m(f,h){let g=(0,q2.useFunc)(e,V2.default),y=e.name("outer");e.label(y).for((0,ft._)`;${f}--;`,()=>e.for((0,ft._)`${h} = ${f}; ${h}--;`,()=>e.if((0,ft._)`${g}(${n}[${f}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};P_.default=K2});var X$=L(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var R_=oe(),G2=fe(),J2=ql(),X2={message:"must be equal to constant",params:({schemaCode:t})=>(0,R_._)`{allowedValue: ${t}}`},Y2={keyword:"const",$data:!0,error:X2,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,R_._)`!${(0,G2.useFunc)(e,J2.default)}(${n}, ${o})`):t.fail((0,R_._)`${s} !== ${n}`)}};C_.default=Y2});var Y$=L(O_=>{"use strict";Object.defineProperty(O_,"__esModule",{value:!0});var nc=oe(),Q2=fe(),eZ=ql(),tZ={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,nc._)`{allowedValues: ${t}}`},nZ={keyword:"enum",schemaType:"array",$data:!0,error:tZ,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,Q2.useFunc)(e,eZ.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,nc.or)(...o.map((f,h)=>p(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,nc._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,nc._)`${u()}(${n}, ${m}[${f}])`:(0,nc._)`${n} === ${h}`}}};O_.default=nZ});var Q$=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var rZ=H$(),oZ=U$(),sZ=Z$(),iZ=q$(),aZ=V$(),cZ=W$(),uZ=K$(),lZ=J$(),dZ=X$(),pZ=Y$(),fZ=[rZ.default,oZ.default,sZ.default,iZ.default,aZ.default,cZ.default,uZ.default,lZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dZ.default,pZ.default];I_.default=fZ});var N_=L(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.validateAdditionalItems=void 0;var os=oe(),A_=fe(),mZ={message:({params:{len:t}})=>(0,os.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,os._)`{limit: ${t}}`},hZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:mZ,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,A_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}eP(t,r)}};function eP(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,os._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,os._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,A_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,os._)`${a} <= ${e.length}`);n.if((0,os.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:A_.Type.Num},u),i.allErrors||n.if((0,os.not)(u),()=>n.break())})}}rc.validateAdditionalItems=eP;rc.default=hZ});var D_=L(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.validateTuple=void 0;var tP=oe(),Vl=fe(),gZ=fn(),yZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return nP(t,"additionalItems",e);n.items=!0,!(0,Vl.alwaysValidSchema)(n,e)&&t.ok((0,gZ.validateArray)(t))}};function nP(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Vl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,tP._)`${s}.length`);n.forEach((d,p)=>{(0,Vl.alwaysValidSchema)(a,d)||(r.if((0,tP._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,f=n.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Vl.checkStrictMode)(a,g,p.strictTuples)}}}oc.validateTuple=nP;oc.default=yZ});var rP=L(M_=>{"use strict";Object.defineProperty(M_,"__esModule",{value:!0});var _Z=D_(),bZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,_Z.validateTuple)(t,"items")};M_.default=bZ});var sP=L(j_=>{"use strict";Object.defineProperty(j_,"__esModule",{value:!0});var oP=oe(),xZ=fe(),SZ=fn(),vZ=N_(),kZ={message:({params:{len:t}})=>(0,oP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,oP._)`{limit: ${t}}`},wZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:kZ,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,xZ.alwaysValidSchema)(r,e)&&(o?(0,vZ.validateAdditionalItems)(t,o):t.ok((0,SZ.validateArray)(t)))}};j_.default=wZ});var iP=L(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var hn=oe(),Wl=fe(),EZ={message:({params:{min:t,max:e}})=>e===void 0?(0,hn.str)`must contain at least ${t} valid item(s)`:(0,hn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,hn._)`{minContains: ${t}}`:(0,hn._)`{minContains: ${t}, maxContains: ${e}}`},TZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:EZ,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,hn._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Wl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Wl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Wl.alwaysValidSchema)(s,n)){let h=(0,hn._)`${l} >= ${i}`;a!==void 0&&(h=(0,hn._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,hn._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>f(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Wl.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,hn._)`${h}++`),a===void 0?e.if((0,hn._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,hn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,hn._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};L_.default=TZ});var uP=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.validateSchemaDeps=Wn.validatePropertyDeps=Wn.error=void 0;var z_=oe(),$Z=fe(),sc=fn();Wn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,z_.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,z_._)`{property: ${t},
|
|
496
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function qU({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Hy(t,e,n,r=ri.Correct){let o=r===ri.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===ri.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}kt.checkDataType=Hy;function Uy(t,e,n,r){if(t.length===1)return Hy(t[0],e,n,r);let o,s=(0,vT.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,Hy(i,e,n,r));return o}kt.checkDataTypes=Uy;var VU={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Fy(t){let e=WU(t);(0,HU.reportError)(e,VU)}kt.reportTypeError=Fy;function WU(t){let{gen:e,data:n,schema:r}=t,o=(0,vT.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var TT=L(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.assignDefaults=void 0;var oi=oe(),KU=fe();function GU(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ET(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>ET(t,s,o.default))}Ol.assignDefaults=GU;function ET(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,oi._)`${s}${(0,oi.getProperty)(e)}`;if(o){(0,KU.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,oi._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,oi._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,oi._)`${a} = ${(0,oi.stringify)(n)}`)}});var hn=L(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.validateUnion=Ee.validateArray=Ee.usePattern=Ee.callValidateCode=Ee.schemaProperties=Ee.allSchemaProperties=Ee.noPropertyInData=Ee.propertyInData=Ee.isOwnProperty=Ee.hasPropFunc=Ee.reportMissingProp=Ee.checkMissingProp=Ee.checkReportMissingProp=void 0;var Ie=oe(),By=fe(),Wr=fr(),JU=fe();function XU(t,e){let{gen:n,data:r,it:o}=t;n.if(qy(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ie._)`${e}`},!0),t.error()})}Ee.checkReportMissingProp=XU;function YU({gen:t,data:e,it:{opts:n}},r,o){return(0,Ie.or)(...r.map(s=>(0,Ie.and)(qy(t,e,s,n.ownProperties),(0,Ie._)`${o} = ${s}`)))}Ee.checkMissingProp=YU;function QU(t,e){t.setParams({missingProperty:e},!0),t.error()}Ee.reportMissingProp=QU;function $T(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ie._)`Object.prototype.hasOwnProperty`})}Ee.hasPropFunc=$T;function Zy(t,e,n){return(0,Ie._)`${$T(t)}.call(${e}, ${n})`}Ee.isOwnProperty=Zy;function eF(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} !== undefined`;return r?(0,Ie._)`${o} && ${Zy(t,e,n)}`:o}Ee.propertyInData=eF;function qy(t,e,n,r){let o=(0,Ie._)`${e}${(0,Ie.getProperty)(n)} === undefined`;return r?(0,Ie.or)(o,(0,Ie.not)(Zy(t,e,n))):o}Ee.noPropertyInData=qy;function PT(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ee.allSchemaProperties=PT;function tF(t,e){return PT(e).filter(n=>!(0,By.alwaysValidSchema)(t,e[n]))}Ee.schemaProperties=tF;function nF({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ie._)`${t}, ${e}, ${r}${o}`:e,d=[[Wr.default.instancePath,(0,Ie.strConcat)(Wr.default.instancePath,s)],[Wr.default.parentData,i.parentData],[Wr.default.parentDataProperty,i.parentDataProperty],[Wr.default.rootData,Wr.default.rootData]];i.opts.dynamicRef&&d.push([Wr.default.dynamicAnchors,Wr.default.dynamicAnchors]);let p=(0,Ie._)`${l}, ${n.object(...d)}`;return c!==Ie.nil?(0,Ie._)`${a}.call(${c}, ${p})`:(0,Ie._)`${a}(${p})`}Ee.callValidateCode=nF;var rF=(0,Ie._)`new RegExp`;function oF({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ie._)`${o.code==="new RegExp"?rF:(0,JU.useFunc)(t,o)}(${n}, ${r})`})}Ee.usePattern=oF;function sF(t){let{gen:e,data:n,keyword:r,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,Ie._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:By.Type.Num},s),e.if((0,Ie.not)(s),a)})}}Ee.validateArray=sF;function iF(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,By.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ie._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ie.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ee.validateUnion=iF});var OT=L(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.validateKeywordUsage=qn.validSchemaType=qn.funcKeywordCode=qn.macroKeywordCode=void 0;var At=oe(),Yo=fr(),aF=hn(),cF=Fa();function uF(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=CT(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:At.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qn.macroKeywordCode=uF;function lF(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;pF(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=CT(r,o,u),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)h(),e.modifying&&RT(t),g(()=>t.error());else{let y=e.async?m():f();e.modifying&&RT(t),g(()=>dF(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,At._)`await `),_=>r.assign(d,!1).if((0,At._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,At._)`${_}.errors`),()=>r.throw(_))),y}function f(){let y=(0,At._)`${l}.errors`;return r.assign(y,null),h(At.nil),y}function h(y=e.async?(0,At._)`await `:At.nil){let _=c.opts.passContext?Yo.default.this:Yo.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,At._)`${y}${(0,aF.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,At.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}qn.funcKeywordCode=lF;function RT(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,At._)`${r.parentData}[${r.parentDataProperty}]`))}function dF(t,e){let{gen:n}=t;n.if((0,At._)`Array.isArray(${e})`,()=>{n.assign(Yo.default.vErrors,(0,At._)`${Yo.default.vErrors} === null ? ${e} : ${Yo.default.vErrors}.concat(${e})`).assign(Yo.default.errors,(0,At._)`${Yo.default.vErrors}.length`),(0,cF.extendErrors)(t)},()=>t.error())}function pF({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function CT(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,At.stringify)(n)})}function fF(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}qn.validSchemaType=fF;function mF({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}qn.validateKeywordUsage=mF});var AT=L(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.extendSubschemaMode=Kr.extendSubschemaData=Kr.getSubschema=void 0;var Vn=oe(),IT=fe();function hF(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Vn._)`${t.schemaPath}${(0,Vn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Vn._)`${t.schemaPath}${(0,Vn.getProperty)(e)}${(0,Vn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,IT.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Kr.getSubschema=hF;function gF(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Vn._)`${e.data}${(0,Vn.getProperty)(n)}`,!0);c(p),t.errorPath=(0,Vn.str)`${u}${(0,IT.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Vn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Vn.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]}}Kr.extendSubschemaData=gF;function yF(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Kr.extendSubschemaMode=yF});var Vy=L((n7,NT)=>{"use strict";NT.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var MT=L((r7,DT)=>{"use strict";var Gr=DT.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Il(e,r,o,t,"",t)};Gr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Gr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Gr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Gr.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,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in Gr.arrayKeywords)for(var p=0;p<d.length;p++)Il(t,e,n,d[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in Gr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Il(t,e,n,d[m],o+"/"+l+"/"+_F(m),s,o,l,r,m)}else(l in Gr.keywords||t.allKeys&&!(l in Gr.skipKeywords))&&Il(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function _F(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Za=L(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.getSchemaRefs=Ft.resolveUrl=Ft.normalizeId=Ft._getFullPath=Ft.getFullPath=Ft.inlineRef=void 0;var bF=fe(),xF=Vy(),SF=MT(),vF=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kF(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wy(t):e?jT(t)<=e:!1}Ft.inlineRef=kF;var wF=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wy(t){for(let e in t){if(wF.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Wy)||typeof n=="object"&&Wy(n))return!0}return!1}function jT(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!vF.has(n)&&(typeof t[n]=="object"&&(0,bF.eachItem)(t[n],r=>e+=jT(r)),e===1/0))return 1/0}return e}function LT(t,e="",n){n!==!1&&(e=si(e));let r=t.parse(e);return zT(t,r)}Ft.getFullPath=LT;function zT(t,e){return t.serialize(e).split("#")[0]+"#"}Ft._getFullPath=zT;var EF=/#\/?$/;function si(t){return t?t.replace(EF,""):""}Ft.normalizeId=si;function TF(t,e,n){return n=si(n),t.resolve(e,n)}Ft.resolveUrl=TF;var $F=/^[a-z_][-a-z0-9._]*$/i;function PF(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=si(t[n]||e),s={"":o},i=LT(r,o,!1),a={},c=new Set;return SF(t,{allKeys:!0},(d,p,m,f)=>{if(f===void 0)return;let h=i+p,g=s[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(b){let S=this.opts.uriResolver.resolve;if(b=si(g?S(g,b):b),c.has(b))throw l(b);c.add(b);let T=this.refs[b];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,b):b!==si(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!$F.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,p,m){if(p!==void 0&&!xF(d,p))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ft.getSchemaRefs=PF});var Wa=L(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;var ZT=bT(),HT=Ba(),Gy=zy(),Al=Ba(),RF=TT(),Va=OT(),Ky=AT(),W=oe(),ee=fr(),CF=Za(),mr=fe(),qa=Fa();function OF(t){if(WT(t)&&(KT(t),VT(t))){NF(t);return}qT(t,()=>(0,ZT.topBoolOrEmptySchema)(t))}Jr.validateFunctionCode=OF;function qT({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,W._)`${ee.default.data}, ${ee.default.valCxt}`,r.$async,()=>{t.code((0,W._)`"use strict"; ${UT(n,o)}`),AF(t,o),t.code(s)}):t.func(e,(0,W._)`${ee.default.data}, ${IF(o)}`,r.$async,()=>t.code(UT(n,o)).code(s))}function IF(t){return(0,W._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,W._)`, ${ee.default.dynamicAnchors}={}`:W.nil}}={}`}function AF(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,W._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,W._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,W._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,W._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,W._)`""`),t.var(ee.default.parentData,(0,W._)`undefined`),t.var(ee.default.parentDataProperty,(0,W._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`{}`)})}function NF(t){let{schema:e,opts:n,gen:r}=t;qT(t,()=>{n.$comment&&e.$comment&&JT(t),zF(t),r.let(ee.default.vErrors,null),r.let(ee.default.errors,0),n.unevaluated&&DF(t),GT(t),FF(t)})}function DF(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,W._)`${n}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function UT(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${n} */`:W.nil}function MF(t,e){if(WT(t)&&(KT(t),VT(t))){jF(t,e);return}(0,ZT.boolOrEmptySchema)(t,e)}function VT({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function WT(t){return typeof t.schema!="boolean"}function jF(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&JT(t),HF(t),UF(t);let s=r.const("_errs",ee.default.errors);GT(t,s),r.var(e,(0,W._)`${s} === ${ee.default.errors}`)}function KT(t){(0,mr.checkUnknownRules)(t),LF(t)}function GT(t,e){if(t.opts.jtd)return FT(t,[],!1,e);let n=(0,HT.getSchemaTypes)(t.schema),r=(0,HT.coerceAndCheckDataType)(t,n);FT(t,n,!r,e)}function LF(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,mr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function zF(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,mr.checkStrictMode)(t,"default is ignored in the schema root")}function HF(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,CF.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function UF(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function JT({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,W._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,W.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function FF(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,W._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,W._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,W._)`${r}.errors`,ee.default.vErrors),s.unevaluated&&BF(t),e.return((0,W._)`${ee.default.errors} === 0`))}function BF({gen:t,evaluated:e,props:n,items:r}){n instanceof W.Name&&t.assign((0,W._)`${e}.props`,n),r instanceof W.Name&&t.assign((0,W._)`${e}.items`,r)}function FT(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,mr.schemaHasRulesButRef)(s,l))){o.block(()=>YT(t,"$ref",l.all.$ref.definition));return}c.jtd||ZF(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Gy.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Al.checkDataType)(p.type,i,c.strictNumbers)),BT(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,Al.reportTypeError)(t)),o.endIf()):BT(t,p),a||o.if((0,W._)`${ee.default.errors} === ${r||0}`))}}function BT(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,RF.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,Gy.shouldUseRule)(r,s)&&YT(t,s.keyword,s.definition,e.type)})}function ZF(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qF(t,e),t.opts.allowUnionTypes||VF(t,e),WF(t,t.dataTypes))}function qF(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{XT(t.dataTypes,n)||Jy(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),GF(t,e)}}function VF(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Jy(t,"use allowUnionTypes to allow union type keyword")}function WF(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Gy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>KF(e,i))&&Jy(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function KF(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function XT(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function GF(t,e){let n=[];for(let r of t.dataTypes)XT(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Jy(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,mr.checkStrictMode)(t,e,t.opts.strictTypes)}var Nl=class{constructor(e,n,r){if((0,Va.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,mr.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",QT(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Va.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ee.default.errors))}result(e,n,r){this.failResult((0,W.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,W.not)(e),void 0,n)}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:n}=this;this.fail((0,W._)`${n} !== undefined && (${(0,W.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?qa.reportExtraError:qa.reportError)(this,this.def.error,n)}$dataError(){(0,qa.reportError)(this,this.def.$dataError||qa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,qa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=W.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=W.nil,n=W.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,W.or)((0,W._)`${o} === undefined`,n)),e!==W.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(r.length){if(!(n instanceof W.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,W._)`${(0,Al.checkDataTypes)(c,n,s.opts.strictNumbers,Al.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${n})`}return W.nil}}subschema(e,n){let r=(0,Ky.getSubschema)(this.it,e);(0,Ky.extendSubschemaData)(r,this.it,e),(0,Ky.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return MF(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=mr.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=mr.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,W.Name)),!0}};Jr.KeywordCxt=Nl;function YT(t,e,n,r){let o=new Nl(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Va.funcKeywordCode)(o,n):"macro"in n?(0,Va.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Va.funcKeywordCode)(o,n)}var JF=/^\/(?:[^~]|~0|~1)*$/,XF=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function QT(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!JF.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=XF.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,W._)`${s}${(0,W.getProperty)((0,mr.unescapeJsonPointer)(u))}`,i=(0,W._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Jr.getData=QT});var Dl=L(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var Xy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yy.default=Xy});var Ka=L(t_=>{"use strict";Object.defineProperty(t_,"__esModule",{value:!0});var Qy=Za(),e_=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Qy.resolveUrl)(e,n,r),this.missingSchema=(0,Qy.normalizeId)((0,Qy.getFullPath)(e,this.missingRef))}};t_.default=e_});var jl=L(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.resolveSchema=gn.getCompilingSchema=gn.resolveRef=gn.compileSchema=gn.SchemaEnv=void 0;var En=oe(),YF=Dl(),Qo=fr(),Tn=Za(),e$=fe(),QF=Wa(),ii=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Tn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};gn.SchemaEnv=ii;function r_(t){let e=t$.call(this,t);if(e)return e;let n=(0,Tn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new En.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:YF.default,code:(0,En._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Qo.default.data,parentData:Qo.default.parentData,parentDataProperty:Qo.default.parentDataProperty,dataNames:[Qo.default.data],dataPathArr:[En.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,En.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:En.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,En._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,QF.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Qo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Qo.default.self}`,`${Qo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=u;m.evaluated={props:f instanceof En.Name?void 0:f,items:h instanceof En.Name?void 0:h,dynamicProps:f instanceof En.Name,dynamicItems:h instanceof En.Name},m.source&&(m.source.evaluated=(0,En.stringify)(m.evaluated))}return t.validate=m,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}gn.compileSchema=r_;function eB(t,e,n){var r;n=(0,Tn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=rB.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new ii({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=tB.call(this,s)}gn.resolveRef=eB;function tB(t){return(0,Tn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:r_.call(this,t)}function t$(t){for(let e of this._compilations)if(nB(e,t))return e}gn.getCompilingSchema=t$;function nB(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function rB(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Ml.call(this,t,e)}function Ml(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Tn._getFullPath)(this.opts.uriResolver,n),o=(0,Tn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return n_.call(this,n,t);let s=(0,Tn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ml.call(this,t,i);return typeof a?.schema!="object"?void 0:n_.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||r_.call(this,i),s===(0,Tn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tn.resolveUrl)(this.opts.uriResolver,o,u)),new ii({schema:a,schemaId:c,root:t,baseId:o})}return n_.call(this,n,i)}}gn.resolveSchema=Ml;var oB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function n_(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,e$.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!oB.has(a)&&u&&(e=(0,Tn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,e$.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Tn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=Ml.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new ii({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var n$=L((u7,sB)=>{sB.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 u_=L((l7,u$)=>{"use strict";var iB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),s_=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),aB=RegExp.prototype.test.bind(/^\d*$/u),es=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i_=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o$=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),a_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),cB=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Bt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Bt[e]="%"+t[e>>4]+t[e&15]}function wt(t){return t<2048?Bt[192|t>>6]+Bt[128|t&63]:t<65536?Bt[224|t>>12]+Bt[128|t>>6&63]+Bt[128|t&63]:Bt[240|t>>18]+Bt[128|t>>12&63]+Bt[128|t>>6&63]+Bt[128|t&63]}function uB(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var lB=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),dB=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),pB=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),fB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function mB(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!pB(t[e])){if(t[e]==="%"&&e+2<t.length&&es(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function r$(t){let e=-1,n=0,r=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(r===-1&&(r=a),o++,o>n&&(n=o,e=r)):(r=-1,o=0);if(n<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+n).join(":");return s+"::"+i}function hB(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let n=e===-1?t.split(":"):t.slice(0,e).split(":"),r=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(n.length===1&&n[0]===""&&(n.length=0),r.length===1&&r[0]===""&&(r.length=0));let o=n.concat(r),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&r.length===0||!s_(c))return;s+=2;continue}if(!lB(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:r$(o);if(s>=8)return;let i=o.slice(0,n.length);for(let a=s;a<8;a++)i.push("0");for(let a=n.length;a<o.length;a++)i.push(o[a]);return r$(i)}function o_(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let r=e?t.slice(1,-1):t;if(e&&dB(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(gB(r,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=r.indexOf("%");if(s!==-1){let a=r.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=r.slice(s+a),!mB(o))return{host:t,isIPV6:!1,error:!0};r=r.slice(0,s)}let i=hB(r);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function gB(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function yB(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var _B={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},bB=/[@/?#:]/g,xB=/[@/?#]/g;function s$(t,e){let n=e?xB:bB;return n.lastIndex=0,t.replace(n,r=>_B[r])}function i$(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&i_(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function SB(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&i_(i)?e+=i:e+="%"+s,n+=2;continue}}if(o$(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=c$(o)?r:Bt[o];else if(o<55296||o>57343)e+=wt(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=wt(65536+(o-55296<<10)+(s-56320)),n++):e+=wt(65533)}else e+=wt(65533)}}return e}function vB(t,e=!1){let n="",r=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(es(i)){n+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(r=!1),o$(s)&&(s!==":"||!r))n+=s;else{let i=t.charCodeAt(o);if(i<128)n+=Bt[i];else if(i<55296||i>57343)n+=wt(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(n+=wt(65536+(i-55296<<10)+(a-56320)),o++):n+=wt(65533)}else n+=wt(65533)}}return n}function c_(t,e){let n="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(es(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(e(o))n+=o;else{let s=t.charCodeAt(r);if(s<128)n+=Bt[s];else if(s<55296||s>57343)n+=wt(s);else if(s<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(n+=wt(65536+(s-55296<<10)+(i-56320)),r++):n+=wt(65533)}else n+=wt(65533)}}return n}function a$(t){return c_(t,cB)}function kB(t){return c_(t,a_)}function wB(t){return c_(t,a_)}function c$(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function EB(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(es(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i_(i)?e+=i:e+="%"+s,n+=2;continue}}if(a_(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=c$(o)?r:Bt[o];else if(o<55296||o>57343)e+=wt(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=wt(65536+(o-55296<<10)+(s-56320)),n++):e+=wt(65533)}else e+=wt(65533)}}return e}function TB(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(es(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function $B(t){let e=[];if(t.userinfo!==void 0&&(e.push(a$(t.userinfo)),e.push("@")),t.host!==void 0){let n=t.host;if(!s_(n)){let r=o_(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=i$(n,!0),r=o_(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=s$(n,!1)}e.push(n)}if(typeof t.port=="number"||typeof t.port=="string"){let n=String(t.port);if(!aB(n))throw new TypeError("URI port is malformed.");e.push(":"),e.push(n)}return e.length?e.join(""):void 0}u$.exports={nonSimpleDomain:fB,recomposeAuthority:$B,reescapeHostDelimiters:s$,normalizePercentEncoding:i$,normalizePathEncoding:SB,serializePathEncoding:vB,normalizeQueryFragmentEncoding:EB,encodeUserinfo:a$,encodeQuery:kB,encodeFragment:wB,escapePreservingEscapes:TB,removeDotSegments:yB,isIPv4:s_,isUUID:iB,normalizeIPv6:o_,stringArrayToHexStripped:uB}});var m$=L((d7,f$)=>{"use strict";var{isUUID:PB}=u_(),RB=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,CB=["http","https","ws","wss","urn","urn:uuid"];function OB(t){return CB.indexOf(t)!==-1}function l_(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 l$(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function d$(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 IB(t){return t.secure=l_(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function AB(t){if((t.port===(l_(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),n=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=n&&n!=="/"?n:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function NB(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(RB);if(n&&n[0]===t.path){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=d_(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function DB(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=d_(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function MB(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!PB(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function jB(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var p$={scheme:"http",domainHost:!0,parse:l$,serialize:d$},LB={scheme:"https",domainHost:p$.domainHost,parse:l$,serialize:d$},Ll={scheme:"ws",domainHost:!0,parse:IB,serialize:AB},zB={scheme:"wss",domainHost:Ll.domainHost,parse:Ll.parse,serialize:Ll.serialize},HB={scheme:"urn",parse:NB,serialize:DB,skipNormalize:!0},UB={scheme:"urn:uuid",parse:MB,serialize:jB,skipNormalize:!0},zl={http:p$,https:LB,ws:Ll,wss:zB,urn:HB,"urn:uuid":UB};Object.setPrototypeOf(zl,null);function d_(t){return t&&(zl[t]||zl[t.toLowerCase()])||void 0}f$.exports={wsIsSecure:l_,SCHEMES:zl,isValidSchemeName:OB,getSchemeHandler:d_}});var P$=L((p7,Fl)=>{"use strict";var{normalizeIPv6:b$,removeDotSegments:Ja,recomposeAuthority:FB,normalizePercentEncoding:x$,normalizePathEncoding:BB,serializePathEncoding:h$,normalizeQueryFragmentEncoding:g$,encodeQuery:ZB,encodeFragment:qB,reescapeHostDelimiters:VB,isIPv4:S$,nonSimpleDomain:WB}=u_(),{SCHEMES:v$,getSchemeHandler:p_}=m$(),k$=/^[A-Za-z][A-Za-z0-9+.-]*$/u,w$="URI scheme is malformed.";function y$(t){let e=unescape(String(t));if(!k$.test(e))throw new TypeError(w$);return e}function KB(t,e){return typeof t=="string"?t=n2(t,e):typeof t=="object"&&(t=Ul(ts(t,e),e)),t}function GB(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Hl(t,r),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:m,malformedHost:f,malformedScheme:h}=Hl(e,r);if(s||d||i||p||a||m||c||f||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=E$(o,l,r,!0),y=p_(n&&n.scheme||g.scheme),_=g.host,b=_!==void 0&&_!==""&&(S$(_)||b$(_).isIPV6);T$(g,n||{},y,b);let S=_&&_.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(_);if(g.error&&!S)throw new Error(g.error);return r.skipEscape=!0,ts(g,r)}function E$(t,e,n,r){let o={};return r||(t=Ul(ts(t,n),n),e=Ul(ts(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ja(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=Ja(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ja(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=Ja(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 JB(t,e,n){let r=_$(t,n),o=_$(e,n);return r!==void 0&&o!==void 0&&r===o}function ts(t,e){let n={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:""},r=Object.assign({},e),o=[];n.scheme&&(n.scheme=y$(n.scheme));let s=p_(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r);let i=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,a=!r.skipEscape&&n.scheme===void 0&&!i;n.path!==void 0&&(r.skipEscape?n.path=x$(n.path):n.path=h$(n.path,a)),r.reference!=="suffix"&&n.scheme&&(n.scheme=y$(n.scheme),o.push(n.scheme,":"));let c=FB(n);if(c!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(c),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let u=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(u=Ja(u)),a&&(u=h$(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return n.query!==void 0&&o.push("?",ZB(n.query)),n.fragment!==void 0&&o.push("#",qB(n.fragment)),o.join("")}var XB=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,YB=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,QB=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function e2(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Ga(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function f_(t){return t[0]==="["&&t[t.length-1]==="]"}function t2(t){let e=t[4];return Ga(t[3])||e!==void 0&&!f_(e)&&Ga(e)||Ga(t[6])||Ga(t[7])||Ga(t[8])}function T$(t,e,n,r){if(!e.unicodeSupport&&(!n||!n.unicodeSupport)&&t.host&&!f_(t.host)&&(e.domainHost||n&&n.domainHost)&&r===!1&&WB(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Hl(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let d=t.match(YB);d!==null&&d[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);let p=t.match(QB);if(p!==null){let f=p[1],h=f.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",o=!0):f.length!==h.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(XB);if(m){if(r.scheme=m[1],r.userinfo=m[3],r.host=m[4],r.port=parseInt(m[5],10),r.path=m[6]||"",r.query=m[7],r.fragment=m[8],r.scheme!==void 0){let g=unescape(r.scheme);k$.test(g)?r.scheme=g.toLowerCase():(r.error=r.error||w$,u=!0)}s=t2(m),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=m[5]);let f=e2(r,m);if(f!==void 0&&(r.error=r.error||f,o=!0),r.host)if(S$(r.host)===!1){let y=f_(r.host),_=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,b=b$(r.host);l=b.isIPV6||b.isIPVFuture===!0,c=_&&(!y||b.error===!0),r.host=l?b.host:b.host.toLowerCase(),c&&(r.error=r.error||"URI host is malformed.",o=!0)}else l=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let h=p_(n.scheme||r.scheme);if(c||(a=T$(r,n,h,l)),!h||h&&!h.skipNormalize){if(t.indexOf("%")!==-1&&r.host!==void 0&&!c){let g=l?r.host:x$(r.host,!0);r.host=VB(g,l)}r.path&&(r.path=BB(r.path)),r.query&&(r.query=g$(r.query)),r.fragment&&(r.fragment=g$(r.fragment))}h&&h.parse&&(h.parse(r,n),h===v$.urn&&r.nid===void 0&&(i=!0))}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Ul(t,e){return Hl(t,e).parsed}function n2(t,e){return $$(t,e).normalized}function $$(t,e){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Hl(t,e);return{normalized:r||o||s||i||a?t:ts(n,e),malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function _$(t,e){if(typeof t!="string"&&typeof t!="object")return;let n;try{n=typeof t=="string"?t:ts(t,e)}catch{return}let{normalized:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=$$(n,e);return o||s||i||a||c?void 0:r}var m_={SCHEMES:v$,normalize:KB,resolve:GB,resolveComponent:E$,equal:JB,serialize:ts,parse:Ul};Fl.exports=m_;Fl.exports.default=m_;Fl.exports.fastUri=m_});var C$=L(h_=>{"use strict";Object.defineProperty(h_,"__esModule",{value:!0});var R$=P$();R$.code='require("ajv/dist/runtime/uri").default';h_.default=R$});var L$=L(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.CodeGen=ht.Name=ht.nil=ht.stringify=ht.str=ht._=ht.KeywordCxt=void 0;var r2=Wa();Object.defineProperty(ht,"KeywordCxt",{enumerable:!0,get:function(){return r2.KeywordCxt}});var ai=oe();Object.defineProperty(ht,"_",{enumerable:!0,get:function(){return ai._}});Object.defineProperty(ht,"str",{enumerable:!0,get:function(){return ai.str}});Object.defineProperty(ht,"stringify",{enumerable:!0,get:function(){return ai.stringify}});Object.defineProperty(ht,"nil",{enumerable:!0,get:function(){return ai.nil}});Object.defineProperty(ht,"Name",{enumerable:!0,get:function(){return ai.Name}});Object.defineProperty(ht,"CodeGen",{enumerable:!0,get:function(){return ai.CodeGen}});var o2=Dl(),D$=Ka(),s2=Ly(),Xa=jl(),i2=oe(),Ya=Za(),Bl=Ba(),y_=fe(),O$=n$(),a2=C$(),M$=(t,e)=>new RegExp(t,e);M$.code="new RegExp";var c2=["removeAdditional","useDefaults","coerceTypes"],u2=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),l2={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."},d2={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},I$=200;function p2(t){var e,n,r,o,s,i,a,c,u,l,d,p,m,f,h,g,y,_,b,S,T,D,v,$,P;let A=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,C=R===!0||R===void 0?1:R||0,z=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:M$,B=(o=t.uriResolver)!==null&&o!==void 0?o:a2.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:A)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:A)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:A)!==null&&p!==void 0?p:"log",strictRequired:(f=(m=t.strictRequired)!==null&&m!==void 0?m:A)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:C,regExp:z}:{optimize:C,regExp:z},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:I$,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:I$,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:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(D=t.validateSchema)!==null&&D!==void 0?D:!0,validateFormats:(v=t.validateFormats)!==null&&v!==void 0?v:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(P=t.int32range)!==null&&P!==void 0?P:!0,uriResolver:B}}var Qa=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,...p2(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new i2.ValueScope({scope:{},prefixes:u2,es5:n,lines:r}),this.logger=_2(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,s2.getRules)(),A$.call(this,l2,e,"NOT SUPPORTED"),A$.call(this,d2,e,"DEPRECATED","warn"),this._metaOpts=g2.call(this),e.formats&&m2.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&h2.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),f2.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=O$;r==="id"&&(o={...O$},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);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 D$.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ya.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=N$.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Xa.SchemaEnv({schema:{},schemaId:r});if(n=Xa.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=N$.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ya.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(x2.call(this,r,n),!n)return(0,y_.eachItem)(r,s=>g_.call(this,s)),this;v2.call(this,n);let o={...n,type:(0,Bl.getJSONTypes)(n.type),schemaType:(0,Bl.getJSONTypes)(n.schemaType)};return(0,y_.eachItem)(r,o.type.length===0?s=>g_.call(this,s,o):s=>o.type.forEach(i=>g_.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=j$(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ya.normalizeId)(i||r);let u=Ya.getSchemaRefs.call(this,e,r);return c=new Xa.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):Xa.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Xa.compileSchema.call(this,e)}finally{this.opts=n}}};Qa.ValidationError=o2.default;Qa.MissingRefError=D$.default;ht.default=Qa;function A$(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function N$(t){return t=(0,Ya.normalizeId)(t),this.schemas[t]||this.refs[t]}function f2(){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 m2(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function h2(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function g2(){let t={...this.opts};for(let e of c2)delete t[e];return t}var y2={log(){},warn(){},error(){}};function _2(t){if(t===!1)return y2;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 b2=/^[a-z_$][a-z0-9_$:-]*$/i;function x2(t,e){let{RULES:n}=this;if((0,y_.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!b2.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function g_(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Bl.getJSONTypes)(e.type),schemaType:(0,Bl.getJSONTypes)(e.schemaType)}};e.before?S2.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function S2(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function v2(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=j$(e)),t.validateSchema=this.compile(e,!0))}var k2={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function j$(t){return{anyOf:[t,k2]}}});var z$=L(__=>{"use strict";Object.defineProperty(__,"__esModule",{value:!0});var w2={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};__.default=w2});var B$=L(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.callRef=ns.getValidate=void 0;var E2=Ka(),H$=hn(),Zt=oe(),ci=fr(),U$=jl(),Zl=fe(),T2={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=U$.resolveRef.call(c,u,o,n);if(l===void 0)throw new E2.default(r.opts.uriResolver,o,n);if(l instanceof U$.SchemaEnv)return p(l);return m(l);function d(){if(s===u)return ql(t,i,s,s.$async);let f=e.scopeValue("root",{ref:u});return ql(t,(0,Zt._)`${f}.validate`,u,u.$async)}function p(f){let h=F$(t,f);ql(t,h,f,f.$async)}function m(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Zt.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:Zt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function F$(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Zt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}ns.getValidate=F$;function ql(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ci.default.this:Zt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Zt._)`await ${(0,H$.callValidateCode)(t,e,u)}`),m(e),i||o.assign(f,!0)},h=>{o.if((0,Zt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,H$.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(f){let h=(0,Zt._)`${f}.errors`;o.assign(ci.default.vErrors,(0,Zt._)`${ci.default.vErrors} === null ? ${h} : ${ci.default.vErrors}.concat(${h})`),o.assign(ci.default.errors,(0,Zt._)`${ci.default.vErrors}.length`)}function m(f){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Zl.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,Zt._)`${f}.evaluated.props`);s.props=Zl.mergeEvaluated.props(o,y,s.props,Zt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Zl.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,Zt._)`${f}.evaluated.items`);s.items=Zl.mergeEvaluated.items(o,y,s.items,Zt.Name)}}}ns.callRef=ql;ns.default=T2});var Z$=L(b_=>{"use strict";Object.defineProperty(b_,"__esModule",{value:!0});var $2=z$(),P2=B$(),R2=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",$2.default,P2.default];b_.default=R2});var q$=L(x_=>{"use strict";Object.defineProperty(x_,"__esModule",{value:!0});var Vl=oe(),Xr=Vl.operators,Wl={maximum:{okStr:"<=",ok:Xr.LTE,fail:Xr.GT},minimum:{okStr:">=",ok:Xr.GTE,fail:Xr.LT},exclusiveMaximum:{okStr:"<",ok:Xr.LT,fail:Xr.GTE},exclusiveMinimum:{okStr:">",ok:Xr.GT,fail:Xr.LTE}},C2={message:({keyword:t,schemaCode:e})=>(0,Vl.str)`must be ${Wl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Vl._)`{comparison: ${Wl[t].okStr}, limit: ${e}}`},O2={keyword:Object.keys(Wl),type:"number",schemaType:"number",$data:!0,error:C2,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Vl._)`${n} ${Wl[e].fail} ${r} || isNaN(${n})`)}};x_.default=O2});var V$=L(S_=>{"use strict";Object.defineProperty(S_,"__esModule",{value:!0});var ec=oe(),I2={message:({schemaCode:t})=>(0,ec.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ec._)`{multipleOf: ${t}}`},A2={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:I2,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ec._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ec._)`${i} !== parseInt(${i})`;t.fail$data((0,ec._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};S_.default=A2});var K$=L(v_=>{"use strict";Object.defineProperty(v_,"__esModule",{value:!0});function W$(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}v_.default=W$;W$.code='require("ajv/dist/runtime/ucs2length").default'});var G$=L(k_=>{"use strict";Object.defineProperty(k_,"__esModule",{value:!0});var rs=oe(),N2=fe(),D2=K$(),M2={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,rs.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,rs._)`{limit: ${t}}`},j2={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:M2,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?rs.operators.GT:rs.operators.LT,i=o.opts.unicode===!1?(0,rs._)`${n}.length`:(0,rs._)`${(0,N2.useFunc)(t.gen,D2.default)}(${n})`;t.fail$data((0,rs._)`${i} ${s} ${r}`)}};k_.default=j2});var J$=L(w_=>{"use strict";Object.defineProperty(w_,"__esModule",{value:!0});var L2=hn(),z2=fe(),ui=oe(),H2={message:({schemaCode:t})=>(0,ui.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ui._)`{pattern: ${t}}`},U2={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:H2,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ui._)`new RegExp`:(0,z2.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ui._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ui._)`!${l}`)}else{let c=(0,L2.usePattern)(t,o);t.fail$data((0,ui._)`!${c}.test(${n})`)}}};w_.default=U2});var X$=L(E_=>{"use strict";Object.defineProperty(E_,"__esModule",{value:!0});var tc=oe(),F2={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,tc.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,tc._)`{limit: ${t}}`},B2={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:F2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?tc.operators.GT:tc.operators.LT;t.fail$data((0,tc._)`Object.keys(${n}).length ${o} ${r}`)}};E_.default=B2});var Y$=L(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});var nc=hn(),rc=oe(),Z2=fe(),q2={message:({params:{missingProperty:t}})=>(0,rc.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,rc._)`{missingProperty: ${t}}`},V2={keyword:"required",type:"object",schemaType:"array",$data:!0,error:q2,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of n)if(m?.[h]===void 0&&!f.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,Z2.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(rc.nil,d);else for(let m of n)(0,nc.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>p(m,f)),t.ok(f)}else e.if((0,nc.checkMissingProp)(t,n,m)),(0,nc.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,nc.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function p(m,f){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(f,(0,nc.propertyInData)(e,o,m,a.ownProperties)),e.if((0,rc.not)(f),()=>{t.error(),e.break()})},rc.nil)}}};T_.default=V2});var Q$=L($_=>{"use strict";Object.defineProperty($_,"__esModule",{value:!0});var oc=oe(),W2={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,oc.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,oc._)`{limit: ${t}}`},K2={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:W2,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?oc.operators.GT:oc.operators.LT;t.fail$data((0,oc._)`${n}.length ${o} ${r}`)}};$_.default=K2});var Kl=L(P_=>{"use strict";Object.defineProperty(P_,"__esModule",{value:!0});var eP=Vy();eP.code='require("ajv/dist/runtime/equal").default';P_.default=eP});var tP=L(C_=>{"use strict";Object.defineProperty(C_,"__esModule",{value:!0});var R_=Ba(),gt=oe(),G2=fe(),J2=Kl(),X2={message:({params:{i:t,j:e}})=>(0,gt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,gt._)`{i: ${t}, j: ${e}}`},Y2={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:X2,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,R_.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,gt._)`${i} === false`),t.ok(c);function l(){let f=e.let("i",(0,gt._)`${n}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,gt._)`${f} > 1`,()=>(d()?p:m)(f,h))}function d(){return u.length>0&&!u.some(f=>f==="object"||f==="array")}function p(f,h){let g=e.name("item"),y=(0,R_.checkDataTypes)(u,g,a.opts.strictNumbers,R_.DataType.Wrong),_=e.const("indices",(0,gt._)`{}`);e.for((0,gt._)`;${f}--;`,()=>{e.let(g,(0,gt._)`${n}[${f}]`),e.if(y,(0,gt._)`continue`),u.length>1&&e.if((0,gt._)`typeof ${g} == "string"`,(0,gt._)`${g} += "_"`),e.if((0,gt._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,gt._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,gt._)`${_}[${g}] = ${f}`)})}function m(f,h){let g=(0,G2.useFunc)(e,J2.default),y=e.name("outer");e.label(y).for((0,gt._)`;${f}--;`,()=>e.for((0,gt._)`${h} = ${f}; ${h}--;`,()=>e.if((0,gt._)`${g}(${n}[${f}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};C_.default=Y2});var nP=L(I_=>{"use strict";Object.defineProperty(I_,"__esModule",{value:!0});var O_=oe(),Q2=fe(),eZ=Kl(),tZ={message:"must be equal to constant",params:({schemaCode:t})=>(0,O_._)`{allowedValue: ${t}}`},nZ={keyword:"const",$data:!0,error:tZ,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,O_._)`!${(0,Q2.useFunc)(e,eZ.default)}(${n}, ${o})`):t.fail((0,O_._)`${s} !== ${n}`)}};I_.default=nZ});var rP=L(A_=>{"use strict";Object.defineProperty(A_,"__esModule",{value:!0});var sc=oe(),rZ=fe(),oZ=Kl(),sZ={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,sc._)`{allowedValues: ${t}}`},iZ={keyword:"enum",schemaType:"array",$data:!0,error:sZ,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,rZ.useFunc)(e,oZ.default)),l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);l=(0,sc.or)(...o.map((f,h)=>p(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,sc._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function p(m,f){let h=o[f];return typeof h=="object"&&h!==null?(0,sc._)`${u()}(${n}, ${m}[${f}])`:(0,sc._)`${n} === ${h}`}}};A_.default=iZ});var oP=L(N_=>{"use strict";Object.defineProperty(N_,"__esModule",{value:!0});var aZ=q$(),cZ=V$(),uZ=G$(),lZ=J$(),dZ=X$(),pZ=Y$(),fZ=Q$(),mZ=tP(),hZ=nP(),gZ=rP(),yZ=[aZ.default,cZ.default,uZ.default,lZ.default,dZ.default,pZ.default,fZ.default,mZ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hZ.default,gZ.default];N_.default=yZ});var M_=L(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.validateAdditionalItems=void 0;var os=oe(),D_=fe(),_Z={message:({params:{len:t}})=>(0,os.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,os._)`{limit: ${t}}`},bZ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_Z,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,D_.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}sP(t,r)}};function sP(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,os._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,os._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,D_.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,os._)`${a} <= ${e.length}`);n.if((0,os.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:D_.Type.Num},u),i.allErrors||n.if((0,os.not)(u),()=>n.break())})}}ic.validateAdditionalItems=sP;ic.default=bZ});var j_=L(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});ac.validateTuple=void 0;var iP=oe(),Gl=fe(),xZ=hn(),SZ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return aP(t,"additionalItems",e);n.items=!0,!(0,Gl.alwaysValidSchema)(n,e)&&t.ok((0,xZ.validateArray)(t))}};function aP(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Gl.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,iP._)`${s}.length`);n.forEach((d,p)=>{(0,Gl.alwaysValidSchema)(a,d)||(r.if((0,iP._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:m}=a,f=n.length,h=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Gl.checkStrictMode)(a,g,p.strictTuples)}}}ac.validateTuple=aP;ac.default=SZ});var cP=L(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});var vZ=j_(),kZ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,vZ.validateTuple)(t,"items")};L_.default=kZ});var lP=L(z_=>{"use strict";Object.defineProperty(z_,"__esModule",{value:!0});var uP=oe(),wZ=fe(),EZ=hn(),TZ=M_(),$Z={message:({params:{len:t}})=>(0,uP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,uP._)`{limit: ${t}}`},PZ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:$Z,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,wZ.alwaysValidSchema)(r,e)&&(o?(0,TZ.validateAdditionalItems)(t,o):t.ok((0,EZ.validateArray)(t)))}};z_.default=PZ});var dP=L(H_=>{"use strict";Object.defineProperty(H_,"__esModule",{value:!0});var yn=oe(),Jl=fe(),RZ={message:({params:{min:t,max:e}})=>e===void 0?(0,yn.str)`must contain at least ${t} valid item(s)`:(0,yn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,yn._)`{minContains: ${t}}`:(0,yn._)`{minContains: ${t}, maxContains: ${e}}`},CZ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:RZ,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,yn._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Jl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Jl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Jl.alwaysValidSchema)(s,n)){let h=(0,yn._)`${l} >= ${i}`;a!==void 0&&(h=(0,yn._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,yn._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>f(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Jl.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,yn._)`${h}++`),a===void 0?e.if((0,yn._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,yn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,yn._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};H_.default=CZ});var mP=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.validateSchemaDeps=Wn.validatePropertyDeps=Wn.error=void 0;var U_=oe(),OZ=fe(),cc=hn();Wn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,U_.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,U_._)`{property: ${t},
|
|
497
497
|
missingProperty: ${r},
|
|
498
498
|
depsCount: ${e},
|
|
499
|
-
deps: ${n}}`};var PZ={keyword:"dependencies",type:"object",schemaType:"object",error:Wn.error,code(t){let[e,n]=RZ(t);aP(t,e),cP(t,n)}};function RZ({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function aP(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,sc.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,sc.checkReportMissingProp)(t,u)}):(n.if((0,z_._)`${c} && (${(0,sc.checkMissingProp)(t,a,s)})`),(0,sc.reportMissingProp)(t,s),n.else())}}Wn.validatePropertyDeps=aP;function cP(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,$Z.alwaysValidSchema)(s,e[a])||(n.if((0,sc.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Wn.validateSchemaDeps=cP;Wn.default=PZ});var dP=L(H_=>{"use strict";Object.defineProperty(H_,"__esModule",{value:!0});var lP=oe(),CZ=fe(),OZ={message:"property name must be valid",params:({params:t})=>(0,lP._)`{propertyName: ${t.propertyName}}`},IZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:OZ,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,CZ.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,lP.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};H_.default=IZ});var F_=L(U_=>{"use strict";Object.defineProperty(U_,"__esModule",{value:!0});var Kl=fn(),Tn=oe(),AZ=fr(),Gl=fe(),NZ={message:"must NOT have additional properties",params:({params:t})=>(0,Tn._)`{additionalProperty: ${t.additionalProperty}}`},DZ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:NZ,code(t){let{gen:e,schema:n,parentSchema:r,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,Gl.alwaysValidSchema)(i,n))return;let u=(0,Kl.allSchemaProperties)(r.properties),l=(0,Kl.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Tn._)`${s} === ${AZ.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?f(g):e.if(p(g),()=>f(g))})}function p(g){let y;if(u.length>8){let _=(0,Gl.schemaRefOrVal)(i,r.properties,"properties");y=(0,Kl.isOwnProperty)(e,_,g)}else u.length?y=(0,Tn.or)(...u.map(_=>(0,Tn._)`${g} === ${_}`)):y=Tn.nil;return l.length&&(y=(0,Tn.or)(y,...l.map(_=>(0,Tn._)`${(0,Kl.usePattern)(t,_)}.test(${g})`))),(0,Tn.not)(y)}function m(g){e.code((0,Tn._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){m(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Gl.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Tn.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,Tn.not)(y),()=>e.break()))}}function h(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Gl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};U_.default=DZ});var mP=L(Z_=>{"use strict";Object.defineProperty(Z_,"__esModule",{value:!0});var MZ=Za(),pP=fn(),B_=fe(),fP=F_(),jZ={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&fP.default.code(new MZ.KeywordCxt(s,fP.default,"additionalProperties"));let i=(0,pP.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=B_.mergeEvaluated.props(e,(0,B_.toHash)(i),s.props));let a=i.filter(d=>!(0,B_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,pP.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Z_.default=jZ});var _P=L(q_=>{"use strict";Object.defineProperty(q_,"__esModule",{value:!0});var hP=fn(),Jl=oe(),gP=fe(),yP=fe(),LZ={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,hP.allSchemaProperties)(n),c=a.filter(h=>(0,gP.alwaysValidSchema)(s,n[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Jl.Name)&&(s.props=(0,yP.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,gP.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",r,g=>{e.if((0,Jl._)`${(0,hP.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:yP.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Jl._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Jl.not)(l),()=>e.break())})})}}};q_.default=LZ});var bP=L(V_=>{"use strict";Object.defineProperty(V_,"__esModule",{value:!0});var zZ=fe(),HZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,zZ.alwaysValidSchema)(r,n)){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"}};V_.default=HZ});var xP=L(W_=>{"use strict";Object.defineProperty(W_,"__esModule",{value:!0});var UZ=fn(),FZ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:UZ.validateUnion,error:{message:"must match a schema in anyOf"}};W_.default=FZ});var SP=L(K_=>{"use strict";Object.defineProperty(K_,"__esModule",{value:!0});var Xl=oe(),BZ=fe(),ZZ={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Xl._)`{passingSchemas: ${t.passing}}`},qZ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ZZ,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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,BZ.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Xl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Xl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Xl.Name)})})}}};K_.default=qZ});var vP=L(G_=>{"use strict";Object.defineProperty(G_,"__esModule",{value:!0});var VZ=fe(),WZ={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,VZ.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};G_.default=WZ});var EP=L(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});var Yl=oe(),wP=fe(),KZ={message:({params:t})=>(0,Yl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Yl._)`{failingKeyword: ${t.ifClause}}`},GZ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:KZ,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,wP.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=kP(r,"then"),s=kP(r,"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,Yl.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,Yl._)`${l}`):t.setParams({ifClause:l})}}}};function kP(t,e){let n=t.schema[e];return n!==void 0&&!(0,wP.alwaysValidSchema)(t,n)}J_.default=GZ});var TP=L(X_=>{"use strict";Object.defineProperty(X_,"__esModule",{value:!0});var JZ=fe(),XZ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,JZ.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};X_.default=XZ});var $P=L(Y_=>{"use strict";Object.defineProperty(Y_,"__esModule",{value:!0});var YZ=N_(),QZ=rP(),eq=D_(),tq=sP(),nq=iP(),rq=uP(),oq=dP(),sq=F_(),iq=mP(),aq=_P(),cq=bP(),uq=xP(),lq=SP(),dq=vP(),pq=EP(),fq=TP();function mq(t=!1){let e=[cq.default,uq.default,lq.default,dq.default,pq.default,fq.default,oq.default,sq.default,rq.default,iq.default,aq.default];return t?e.push(QZ.default,tq.default):e.push(YZ.default,eq.default),e.push(nq.default),e}Y_.default=mq});var PP=L(Q_=>{"use strict";Object.defineProperty(Q_,"__esModule",{value:!0});var Ve=oe(),hq={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},gq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hq,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Ve._)`${f}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Ve._)`${h}.type || "string"`).assign(y,(0,Ve._)`${h}.validate`),()=>n.assign(g,(0,Ve._)`"string"`).assign(y,h)),t.fail$data((0,Ve.or)(_(),b()));function _(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function b(){let S=l.$async?(0,Ve._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Ve._)`${y}(${r})`,T=(0,Ve._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${r}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function m(){let f=d.formats[s];if(!f){_();return}if(f===!0)return;let[h,g,y]=b(f);h===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(T){let D=T instanceof RegExp?(0,Ve.regexpCode)(T):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,v=n.scopeValue("formats",{key:s,ref:T,code:D});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Ve._)`${v}.validate`]:["string",T,v]}function S(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${r})`}return typeof g=="function"?(0,Ve._)`${y}(${r})`:(0,Ve._)`${y}.test(${r})`}}}};Q_.default=gq});var RP=L(eb=>{"use strict";Object.defineProperty(eb,"__esModule",{value:!0});var yq=PP(),_q=[yq.default];eb.default=_q});var CP=L(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.contentVocabulary=li.metadataVocabulary=void 0;li.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];li.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var IP=L(tb=>{"use strict";Object.defineProperty(tb,"__esModule",{value:!0});var bq=z$(),xq=Q$(),Sq=$P(),vq=RP(),OP=CP(),kq=[bq.default,xq.default,(0,Sq.default)(),vq.default,OP.metadataVocabulary,OP.contentVocabulary];tb.default=kq});var NP=L(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.DiscrError=void 0;var AP;(function(t){t.Tag="tag",t.Mapping="mapping"})(AP||(Ql.DiscrError=AP={}))});var MP=L(rb=>{"use strict";Object.defineProperty(rb,"__esModule",{value:!0});var di=oe(),nb=NP(),DP=Nl(),wq=qa(),Eq=fe(),Tq={message:({params:{discrError:t,tagName:e}})=>t===nb.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,di._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},$q={keyword:"discriminator",type:"object",schemaType:"object",error:Tq,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,di._)`${n}${(0,di.getProperty)(a)}`);e.if((0,di._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:nb.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,di._)`${u} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:nb.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,di.Name),f}function p(){var m;let f={},h=y(o),g=!0;for(let S=0;S<i.length;S++){let T=i[S];if(T?.$ref&&!(0,Eq.schemaHasRulesButRef)(T,s.self.RULES)){let v=T.$ref;if(T=DP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,v),T instanceof DP.SchemaEnv&&(T=T.schema),T===void 0)throw new wq.default(s.opts.uriResolver,s.baseId,v)}let D=(m=T?.properties)===null||m===void 0?void 0:m[a];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(T)),_(D,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,T){if(S.const)b(S.const,T);else if(S.enum)for(let D of S.enum)b(D,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(S,T){if(typeof S!="string"||S in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[S]=T}}}};rb.default=$q});var jP=L((G7,Pq)=>{Pq.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 sb=L((Ae,ob)=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv=void 0;var Rq=A$(),Cq=IP(),Oq=MP(),LP=jP(),Iq=["/properties"],ed="http://json-schema.org/draft-07/schema",pi=class extends Rq.default{_addVocabularies(){super._addVocabularies(),Cq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Oq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(LP,Iq):LP;this.addMetaSchema(e,ed,!1),this.refs["http://json-schema.org/schema"]=ed}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ed)?ed:void 0)}};Ae.Ajv=pi;ob.exports=Ae=pi;ob.exports.Ajv=pi;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=pi;var Aq=Za();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return Aq.KeywordCxt}});var fi=oe();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return fi._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return fi.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return fi.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return fi.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return fi.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return fi.CodeGen}});var Nq=Il();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return Nq.default}});var Dq=qa();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return Dq.default}})});var VP=L(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.formatNames=Gn.fastFormats=Gn.fullFormats=void 0;function Kn(t,e){return{validate:t,compare:e}}Gn.fullFormats={date:Kn(FP,ub),time:Kn(ab(!0),lb),"date-time":Kn(zP(!0),ZP),"iso-time":Kn(ab(),BP),"iso-date-time":Kn(zP(),qP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Uq,"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:Kq,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:Fq,int32:{type:"number",validate:qq},int64:{type:"number",validate:Vq},float:{type:"number",validate:UP},double:{type:"number",validate:UP},password:!0,binary:!0};Gn.fastFormats={...Gn.fullFormats,date:Kn(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ub),time:Kn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,lb),"date-time":Kn(/^\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,ZP),"iso-time":Kn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,BP),"iso-date-time":Kn(/^\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,qP),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};Gn.formatNames=Object.keys(Gn.fullFormats);function Mq(t){return t%4===0&&(t%100!==0||t%400===0)}var jq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Lq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function FP(t){let e=jq.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&Mq(n)?29:Lq[r])}function ub(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ib=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ab(t){return function(n){let r=ib.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[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 lb(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function BP(t,e){if(!(t&&e))return;let n=ib.exec(t),r=ib.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var cb=/t|\s/i;function zP(t){let e=ab(t);return function(r){let o=r.split(cb);return o.length===2&&FP(o[0])&&e(o[1])}}function ZP(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function qP(t,e){if(!(t&&e))return;let[n,r]=t.split(cb),[o,s]=e.split(cb),i=ub(n,o);if(i!==void 0)return i||lb(r,s)}var zq=/\/|:/,Hq=/^(?:[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 Uq(t){return zq.test(t)&&Hq.test(t)}var HP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Fq(t){return HP.lastIndex=0,HP.test(t)}var Bq=-(2**31),Zq=2**31-1;function qq(t){return Number.isInteger(t)&&t<=Zq&&t>=Bq}function Vq(t){return Number.isInteger(t)}function UP(){return!0}var Wq=/[^\\]\\Z/;function Kq(t){if(Wq.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var WP=L(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.formatLimitDefinition=void 0;var Gq=sb(),$n=oe(),Qr=$n.operators,td={formatMaximum:{okStr:"<=",ok:Qr.LTE,fail:Qr.GT},formatMinimum:{okStr:">=",ok:Qr.GTE,fail:Qr.LT},formatExclusiveMaximum:{okStr:"<",ok:Qr.LT,fail:Qr.GTE},formatExclusiveMinimum:{okStr:">",ok:Qr.GT,fail:Qr.LTE}},Jq={message:({keyword:t,schemaCode:e})=>(0,$n.str)`should be ${td[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$n._)`{comparison: ${td[t].okStr}, limit: ${e}}`};mi.formatLimitDefinition={keyword:Object.keys(td),type:"string",schemaType:"string",$data:!0,error:Jq,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new Gq.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,$n._)`${p}[${c.schemaCode}]`);t.fail$data((0,$n.or)((0,$n._)`typeof ${m} != "object"`,(0,$n._)`${m} instanceof RegExp`,(0,$n._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,$n._)`${i.code.formats}${(0,$n.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,$n._)`${p}.compare(${n}, ${r}) ${td[o].fail} 0`}},dependencies:["format"]};var Xq=t=>(t.addKeyword(mi.formatLimitDefinition),t);mi.default=Xq});var XP=L((ic,JP)=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var hi=VP(),Yq=WP(),db=oe(),KP=new db.Name("fullFormats"),Qq=new db.Name("fastFormats"),pb=(t,e={keywords:!0})=>{if(Array.isArray(e))return GP(t,e,hi.fullFormats,KP),t;let[n,r]=e.mode==="fast"?[hi.fastFormats,Qq]:[hi.fullFormats,KP],o=e.formats||hi.formatNames;return GP(t,o,n,r),e.keywords&&(0,Yq.default)(t),t};pb.get=(t,e="full")=>{let r=(e==="fast"?hi.fastFormats:hi.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function GP(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,db._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}JP.exports=ic=pb;Object.defineProperty(ic,"__esModule",{value:!0});ic.default=pb});function e4(){let t=new YP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,QP.default)(t),t}var YP,QP,nd,eR=x(()=>{YP=$i(sb(),1),QP=$i(XP(),1);nd=class{constructor(e){this._ajv=e??e4()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var rd,tR=x(()=>{Vo();rd=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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},Ra,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},Ys,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function nR(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function rR(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var oR=x(()=>{});var od,sR=x(()=>{Y0();Vo();eR();ya();tR();oR();od=class extends bl{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Pa.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new nd,this.setRequestHandler(Sg,r=>this._oninitialize(r)),this.setNotificationHandler(vg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Rg,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Pa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new rd(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X0(this._capabilities,e)}setRequestHandler(e,n){let o=Fr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Zs(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Ur(Xs,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new q(K.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let f=Ur(Vs,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new q(K.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=Ur(al,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new q(K.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){rR(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nR(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:XE.includes(n)?n:gg,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"},Gu)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},Cg,n):this.request({method:"sampling/createMessage",params:e},Ra,n)}async elicitInput(e,n){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},Ys,n)}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},Ys,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new q(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Og,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 fb(t){return!!t&&typeof t=="object"&&aR in t}function cR(t){return t[aR]?.complete}var aR,iR,uR=x(()=>{aR=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(iR||(iR={}))});var lR=x(()=>{});function n4(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"),!t4.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function r4(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 mb(t){let e=n4(t);return r4(t,e.warnings),e.isValid}var t4,dR=x(()=>{t4=/^[A-Za-z0-9._-]{1,128}$/});var sd,pR=x(()=>{sd=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var id=x(()=>{xu();xu()});function hR(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function gR(t){return"_def"in t||"_zod"in t||hR(t)}function hb(t){return typeof t!="object"||t===null||gR(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(hR)}function fR(t){if(t){if(hb(t))return Zo(t);if(!gR(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function s4(t){let e=Fr(t);return e?Object.entries(e).map(([n,r])=>{let o=vE(r),s=kE(r);return{name:n,description:o,required:!s}}):[]}function eo(t){let n=Fr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Zs(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function mR(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ad,o4,ac,yR=x(()=>{sR();ya();my();Vo();uR();lR();dR();pR();id();ad=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new od(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new sd(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(eo(qo)),this.server.assertCanSetRequestHandler(eo(Xs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(qo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Bs(n.inputSchema);return o?dy(o,{strictUnions:!0,pipeStrategy:"input"}):o4})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Bs(n.outputSchema);o&&(r.outputSchema=dy(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Xs,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new q(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new q(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof q&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Bs(e.inputSchema)??e.inputSchema,i=await Fu(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Bu(a);throw new q(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new q(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Bs(e.outputSchema),s=await Fu(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Bu(i);throw new q(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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 r.taskStore.getTask(c);if(!d)throw new q(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(eo(cl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(cl,async e=>{switch(e.params.ref.type){case"ref/prompt":return f0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return m0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new q(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return ac;let s=Fr(r.argsSchema)?.[e.params.argument.name];if(!fb(s))return ac;let i=cR(s);if(!i)return ac;let a=await i(e.params.argument.value,e.params.context);return mR(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return ac;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ac;let s=await o(e.params.argument.value,e.params.context);return mR(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(eo(Ks)),this.server.assertCanSetRequestHandler(eo(Gs)),this.server.assertCanSetRequestHandler(eo(sl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ks,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Gs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(sl,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new q(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new q(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(eo(Js)),this.server.assertCanSetRequestHandler(eo(il)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Js,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?s4(n.argsSchema):void 0}))})),this.server.setRequestHandler(il,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new q(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Bs(r.argsSchema),s=await Fu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Bu(c);throw new q(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Zo(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=Zo(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 Dt?c._def?.innerType:c;return fb(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){mb(e);let l={title:n,description:r,inputSchema:fR(o),outputSchema:fR(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"&&mb(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=Zo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Zo(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(hb(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!hb(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},o4={type:"object",properties:{}};ac={completion:{values:[],hasMore:!1}}});function a4(t){return s0.parse(JSON.parse(t))}function _R(t){return JSON.stringify(t)+`
|
|
500
|
-
`}var
|
|
501
|
-
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
502
|
-
${t}`}function
|
|
503
|
-
`)}function
|
|
499
|
+
deps: ${n}}`};var IZ={keyword:"dependencies",type:"object",schemaType:"object",error:Wn.error,code(t){let[e,n]=AZ(t);pP(t,e),fP(t,n)}};function AZ({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function pP(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,cc.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,cc.checkReportMissingProp)(t,u)}):(n.if((0,U_._)`${c} && (${(0,cc.checkMissingProp)(t,a,s)})`),(0,cc.reportMissingProp)(t,s),n.else())}}Wn.validatePropertyDeps=pP;function fP(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,OZ.alwaysValidSchema)(s,e[a])||(n.if((0,cc.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}Wn.validateSchemaDeps=fP;Wn.default=IZ});var gP=L(F_=>{"use strict";Object.defineProperty(F_,"__esModule",{value:!0});var hP=oe(),NZ=fe(),DZ={message:"property name must be valid",params:({params:t})=>(0,hP._)`{propertyName: ${t.propertyName}}`},MZ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:DZ,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,NZ.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,hP.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};F_.default=MZ});var Z_=L(B_=>{"use strict";Object.defineProperty(B_,"__esModule",{value:!0});var Xl=hn(),$n=oe(),jZ=fr(),Yl=fe(),LZ={message:"must NOT have additional properties",params:({params:t})=>(0,$n._)`{additionalProperty: ${t.additionalProperty}}`},zZ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:LZ,code(t){let{gen:e,schema:n,parentSchema:r,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,Yl.alwaysValidSchema)(i,n))return;let u=(0,Xl.allSchemaProperties)(r.properties),l=(0,Xl.allSchemaProperties)(r.patternProperties);d(),t.ok((0,$n._)`${s} === ${jZ.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?f(g):e.if(p(g),()=>f(g))})}function p(g){let y;if(u.length>8){let _=(0,Yl.schemaRefOrVal)(i,r.properties,"properties");y=(0,Xl.isOwnProperty)(e,_,g)}else u.length?y=(0,$n.or)(...u.map(_=>(0,$n._)`${g} === ${_}`)):y=$n.nil;return l.length&&(y=(0,$n.or)(y,...l.map(_=>(0,$n._)`${(0,Xl.usePattern)(t,_)}.test(${g})`))),(0,$n.not)(y)}function m(g){e.code((0,$n._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){m(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Yl.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,$n.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,$n.not)(y),()=>e.break()))}}function h(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:Yl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};B_.default=zZ});var bP=L(V_=>{"use strict";Object.defineProperty(V_,"__esModule",{value:!0});var HZ=Wa(),yP=hn(),q_=fe(),_P=Z_(),UZ={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&_P.default.code(new HZ.KeywordCxt(s,_P.default,"additionalProperties"));let i=(0,yP.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=q_.mergeEvaluated.props(e,(0,q_.toHash)(i),s.props));let a=i.filter(d=>!(0,q_.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,yP.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};V_.default=UZ});var kP=L(W_=>{"use strict";Object.defineProperty(W_,"__esModule",{value:!0});var xP=hn(),Ql=oe(),SP=fe(),vP=fe(),FZ={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,xP.allSchemaProperties)(n),c=a.filter(h=>(0,SP.alwaysValidSchema)(s,n[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ql.Name)&&(s.props=(0,vP.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&m(h),s.allErrors?f(h):(e.var(l,!0),f(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,SP.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",r,g=>{e.if((0,Ql._)`${(0,xP.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:vP.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ql._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Ql.not)(l),()=>e.break())})})}}};W_.default=FZ});var wP=L(K_=>{"use strict";Object.defineProperty(K_,"__esModule",{value:!0});var BZ=fe(),ZZ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,BZ.alwaysValidSchema)(r,n)){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"}};K_.default=ZZ});var EP=L(G_=>{"use strict";Object.defineProperty(G_,"__esModule",{value:!0});var qZ=hn(),VZ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qZ.validateUnion,error:{message:"must match a schema in anyOf"}};G_.default=VZ});var TP=L(J_=>{"use strict";Object.defineProperty(J_,"__esModule",{value:!0});var ed=oe(),WZ=fe(),KZ={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ed._)`{passingSchemas: ${t.passing}}`},GZ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:KZ,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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,WZ.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ed._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ed._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,ed.Name)})})}}};J_.default=GZ});var $P=L(X_=>{"use strict";Object.defineProperty(X_,"__esModule",{value:!0});var JZ=fe(),XZ={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,JZ.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};X_.default=XZ});var CP=L(Y_=>{"use strict";Object.defineProperty(Y_,"__esModule",{value:!0});var td=oe(),RP=fe(),YZ={message:({params:t})=>(0,td.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,td._)`{failingKeyword: ${t.ifClause}}`},QZ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:YZ,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,RP.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=PP(r,"then"),s=PP(r,"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,td.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,td._)`${l}`):t.setParams({ifClause:l})}}}};function PP(t,e){let n=t.schema[e];return n!==void 0&&!(0,RP.alwaysValidSchema)(t,n)}Y_.default=QZ});var OP=L(Q_=>{"use strict";Object.defineProperty(Q_,"__esModule",{value:!0});var eq=fe(),tq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,eq.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Q_.default=tq});var IP=L(eb=>{"use strict";Object.defineProperty(eb,"__esModule",{value:!0});var nq=M_(),rq=cP(),oq=j_(),sq=lP(),iq=dP(),aq=mP(),cq=gP(),uq=Z_(),lq=bP(),dq=kP(),pq=wP(),fq=EP(),mq=TP(),hq=$P(),gq=CP(),yq=OP();function _q(t=!1){let e=[pq.default,fq.default,mq.default,hq.default,gq.default,yq.default,cq.default,uq.default,aq.default,lq.default,dq.default];return t?e.push(rq.default,sq.default):e.push(nq.default,oq.default),e.push(iq.default),e}eb.default=_q});var AP=L(tb=>{"use strict";Object.defineProperty(tb,"__esModule",{value:!0});var Ke=oe(),bq={message:({schemaCode:t})=>(0,Ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ke._)`{format: ${t}}`},xq={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:bq,code(t,e){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():m();function p(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Ke._)`${f}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Ke._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Ke._)`${h}.type || "string"`).assign(y,(0,Ke._)`${h}.validate`),()=>n.assign(g,(0,Ke._)`"string"`).assign(y,h)),t.fail$data((0,Ke.or)(_(),b()));function _(){return c.strictSchema===!1?Ke.nil:(0,Ke._)`${i} && !${y}`}function b(){let S=l.$async?(0,Ke._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Ke._)`${y}(${r})`,T=(0,Ke._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${r}))`;return(0,Ke._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function m(){let f=d.formats[s];if(!f){_();return}if(f===!0)return;let[h,g,y]=b(f);h===e&&t.pass(S());function _(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(T){let D=T instanceof RegExp?(0,Ke.regexpCode)(T):c.code.formats?(0,Ke._)`${c.code.formats}${(0,Ke.getProperty)(s)}`:void 0,v=n.scopeValue("formats",{key:s,ref:T,code:D});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Ke._)`${v}.validate`]:["string",T,v]}function S(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ke._)`await ${y}(${r})`}return typeof g=="function"?(0,Ke._)`${y}(${r})`:(0,Ke._)`${y}.test(${r})`}}}};tb.default=xq});var NP=L(nb=>{"use strict";Object.defineProperty(nb,"__esModule",{value:!0});var Sq=AP(),vq=[Sq.default];nb.default=vq});var DP=L(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.contentVocabulary=li.metadataVocabulary=void 0;li.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];li.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var jP=L(rb=>{"use strict";Object.defineProperty(rb,"__esModule",{value:!0});var kq=Z$(),wq=oP(),Eq=IP(),Tq=NP(),MP=DP(),$q=[kq.default,wq.default,(0,Eq.default)(),Tq.default,MP.metadataVocabulary,MP.contentVocabulary];rb.default=$q});var zP=L(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.DiscrError=void 0;var LP;(function(t){t.Tag="tag",t.Mapping="mapping"})(LP||(nd.DiscrError=LP={}))});var UP=L(sb=>{"use strict";Object.defineProperty(sb,"__esModule",{value:!0});var di=oe(),ob=zP(),HP=jl(),Pq=Ka(),Rq=fe(),Cq={message:({params:{discrError:t,tagName:e}})=>t===ob.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,di._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},Oq={keyword:"discriminator",type:"object",schemaType:"object",error:Cq,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,di._)`${n}${(0,di.getProperty)(a)}`);e.if((0,di._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ob.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=p();e.if(!1);for(let f in m)e.elseIf((0,di._)`${u} === ${f}`),e.assign(c,d(m[f]));e.else(),t.error(!1,{discrError:ob.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},f);return t.mergeEvaluated(h,di.Name),f}function p(){var m;let f={},h=y(o),g=!0;for(let S=0;S<i.length;S++){let T=i[S];if(T?.$ref&&!(0,Rq.schemaHasRulesButRef)(T,s.self.RULES)){let v=T.$ref;if(T=HP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,v),T instanceof HP.SchemaEnv&&(T=T.schema),T===void 0)throw new Pq.default(s.opts.uriResolver,s.baseId,v)}let D=(m=T?.properties)===null||m===void 0?void 0:m[a];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(T)),_(D,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,T){if(S.const)b(S.const,T);else if(S.enum)for(let D of S.enum)b(D,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(S,T){if(typeof S!="string"||S in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[S]=T}}}};sb.default=Oq});var FP=L((eQ,Iq)=>{Iq.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 ab=L((Ae,ib)=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv=void 0;var Aq=L$(),Nq=jP(),Dq=UP(),BP=FP(),Mq=["/properties"],rd="http://json-schema.org/draft-07/schema",pi=class extends Aq.default{_addVocabularies(){super._addVocabularies(),Nq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Dq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(BP,Mq):BP;this.addMetaSchema(e,rd,!1),this.refs["http://json-schema.org/schema"]=rd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rd)?rd:void 0)}};Ae.Ajv=pi;ib.exports=Ae=pi;ib.exports.Ajv=pi;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=pi;var jq=Wa();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return jq.KeywordCxt}});var fi=oe();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return fi._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return fi.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return fi.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return fi.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return fi.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return fi.CodeGen}});var Lq=Dl();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return Lq.default}});var zq=Ka();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return zq.default}})});var XP=L(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.formatNames=Gn.fastFormats=Gn.fullFormats=void 0;function Kn(t,e){return{validate:t,compare:e}}Gn.fullFormats={date:Kn(WP,db),time:Kn(ub(!0),pb),"date-time":Kn(ZP(!0),GP),"iso-time":Kn(ub(),KP),"iso-date-time":Kn(ZP(),JP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:qq,"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:Yq,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:Vq,int32:{type:"number",validate:Gq},int64:{type:"number",validate:Jq},float:{type:"number",validate:VP},double:{type:"number",validate:VP},password:!0,binary:!0};Gn.fastFormats={...Gn.fullFormats,date:Kn(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,db),time:Kn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pb),"date-time":Kn(/^\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,GP),"iso-time":Kn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,KP),"iso-date-time":Kn(/^\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,JP),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};Gn.formatNames=Object.keys(Gn.fullFormats);function Hq(t){return t%4===0&&(t%100!==0||t%400===0)}var Uq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Fq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function WP(t){let e=Uq.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&Hq(n)?29:Fq[r])}function db(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cb=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ub(t){return function(n){let r=cb.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[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 pb(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function KP(t,e){if(!(t&&e))return;let n=cb.exec(t),r=cb.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var lb=/t|\s/i;function ZP(t){let e=ub(t);return function(r){let o=r.split(lb);return o.length===2&&WP(o[0])&&e(o[1])}}function GP(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function JP(t,e){if(!(t&&e))return;let[n,r]=t.split(lb),[o,s]=e.split(lb),i=db(n,o);if(i!==void 0)return i||pb(r,s)}var Bq=/\/|:/,Zq=/^(?:[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 qq(t){return Bq.test(t)&&Zq.test(t)}var qP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Vq(t){return qP.lastIndex=0,qP.test(t)}var Wq=-(2**31),Kq=2**31-1;function Gq(t){return Number.isInteger(t)&&t<=Kq&&t>=Wq}function Jq(t){return Number.isInteger(t)}function VP(){return!0}var Xq=/[^\\]\\Z/;function Yq(t){if(Xq.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var YP=L(mi=>{"use strict";Object.defineProperty(mi,"__esModule",{value:!0});mi.formatLimitDefinition=void 0;var Qq=ab(),Pn=oe(),Yr=Pn.operators,od={formatMaximum:{okStr:"<=",ok:Yr.LTE,fail:Yr.GT},formatMinimum:{okStr:">=",ok:Yr.GTE,fail:Yr.LT},formatExclusiveMaximum:{okStr:"<",ok:Yr.LT,fail:Yr.GTE},formatExclusiveMinimum:{okStr:">",ok:Yr.GT,fail:Yr.LTE}},e4={message:({keyword:t,schemaCode:e})=>(0,Pn.str)`should be ${od[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pn._)`{comparison: ${od[t].okStr}, limit: ${e}}`};mi.formatLimitDefinition={keyword:Object.keys(od),type:"string",schemaType:"string",$data:!0,error:e4,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new Qq.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,Pn._)`${p}[${c.schemaCode}]`);t.fail$data((0,Pn.or)((0,Pn._)`typeof ${m} != "object"`,(0,Pn._)`${m} instanceof RegExp`,(0,Pn._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let p=c.schema,m=a.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,Pn._)`${i.code.formats}${(0,Pn.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,Pn._)`${p}.compare(${n}, ${r}) ${od[o].fail} 0`}},dependencies:["format"]};var t4=t=>(t.addKeyword(mi.formatLimitDefinition),t);mi.default=t4});var nR=L((uc,tR)=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var hi=XP(),n4=YP(),fb=oe(),QP=new fb.Name("fullFormats"),r4=new fb.Name("fastFormats"),mb=(t,e={keywords:!0})=>{if(Array.isArray(e))return eR(t,e,hi.fullFormats,QP),t;let[n,r]=e.mode==="fast"?[hi.fastFormats,r4]:[hi.fullFormats,QP],o=e.formats||hi.formatNames;return eR(t,o,n,r),e.keywords&&(0,n4.default)(t),t};mb.get=(t,e="full")=>{let r=(e==="fast"?hi.fastFormats:hi.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function eR(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,fb._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}tR.exports=uc=mb;Object.defineProperty(uc,"__esModule",{value:!0});uc.default=mb});function o4(){let t=new rR.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,oR.default)(t),t}var rR,oR,sd,sR=x(()=>{rR=Ri(ab(),1),oR=Ri(nR(),1);sd=class{constructor(e){this._ajv=e??o4()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var id,iR=x(()=>{Vo();id=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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},Ia,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},Ys,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function aR(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function cR(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var uR=x(()=>{});var ad,lR=x(()=>{rT();Vo();sR();xa();iR();uR();ad=class extends vl{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Oa.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new sd,this.setRequestHandler(kg,r=>this._oninitialize(r)),this.setNotificationHandler(wg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Og,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Oa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new id(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=nT(this._capabilities,e)}setRequestHandler(e,n){let o=Ur(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Zs(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Hr(Xs,c);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new q(K.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let f=Hr(Vs,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new q(K.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let m=Hr(ll,p);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new q(K.InvalidParams,`Invalid tools/call result: ${f}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){cR(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&aR(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:n0.includes(n)?n:_g,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"},Yu)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},Ig,n):this.request({method:"sampling/createMessage",params:e},Ia,n)}async elicitInput(e,n){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},Ys,n)}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},Ys,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new q(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(K.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Ag,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 hb(t){return!!t&&typeof t=="object"&&pR in t}function fR(t){return t[pR]?.complete}var pR,dR,mR=x(()=>{pR=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(dR||(dR={}))});var hR=x(()=>{});function i4(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"),!s4.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function a4(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 gb(t){let e=i4(t);return a4(t,e.warnings),e.isValid}var s4,gR=x(()=>{s4=/^[A-Za-z0-9._-]{1,128}$/});var cd,yR=x(()=>{cd=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}}});var ud=x(()=>{ku();ku()});function xR(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function SR(t){return"_def"in t||"_zod"in t||xR(t)}function yb(t){return typeof t!="object"||t===null||SR(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(xR)}function _R(t){if(t){if(yb(t))return Zo(t);if(!SR(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function u4(t){let e=Ur(t);return e?Object.entries(e).map(([n,r])=>{let o=$E(r),s=PE(r);return{name:n,description:o,required:!s}}):[]}function Qr(t){let n=Ur(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Zs(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function bR(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ld,c4,lc,vR=x(()=>{lR();xa();gy();Vo();mR();hR();gR();yR();ud();ld=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ad(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new cd(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr(qo)),this.server.assertCanSetRequestHandler(Qr(Xs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(qo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Bs(n.inputSchema);return o?fy(o,{strictUnions:!0,pipeStrategy:"input"}):c4})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Bs(n.outputSchema);o&&(r.outputSchema=fy(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Xs,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new q(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new q(K.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof q&&r.code===K.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Bs(e.inputSchema)??e.inputSchema,i=await qu(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Vu(a);throw new q(K.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new q(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Bs(e.outputSchema),s=await qu(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Vu(i);throw new q(K.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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 r.taskStore.getTask(c);if(!d)throw new q(K.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Qr(dl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(dl,async e=>{switch(e.params.ref.type){case"ref/prompt":return _0(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return b0(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new q(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return lc;let s=Ur(r.argsSchema)?.[e.params.argument.name];if(!hb(s))return lc;let i=fR(s);if(!i)return lc;let a=await i(e.params.argument.value,e.params.context);return bR(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return lc;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return lc;let s=await o(e.params.argument.value,e.params.context);return bR(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr(Ks)),this.server.assertCanSetRequestHandler(Qr(Gs)),this.server.assertCanSetRequestHandler(Qr(cl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ks,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Gs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(cl,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new q(K.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new q(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Qr(Js)),this.server.assertCanSetRequestHandler(Qr(ul)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Js,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?u4(n.argsSchema):void 0}))})),this.server.setRequestHandler(ul,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new q(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new q(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Bs(r.argsSchema),s=await qu(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Vu(c);throw new q(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Zo(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=Zo(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 jt?c._def?.innerType:c;return hb(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){gb(e);let l={title:n,description:r,inputSchema:_R(o),outputSchema:_R(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"&&gb(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=Zo(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Zo(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(yb(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!yb(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},c4={type:"object",properties:{}};lc={completion:{values:[],hasMore:!1}}});function d4(t){return l0.parse(JSON.parse(t))}function kR(t){return JSON.stringify(t)+`
|
|
500
|
+
`}var l4,dd,wR=x(()=>{Vo();l4=10*1024*1024,dd=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??l4}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
501
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),d4(n)}clear(){this._buffer=void 0}}});import ER from"node:process";var pd,TR=x(()=>{wR();pd=class{constructor(e=ER.stdin,n=ER.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new dd({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=kR(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var LR={};_e(LR,{PolyglotExecutor:()=>gi,buildPowerShellScriptContent:()=>MR,buildScriptFilename:()=>AR,buildShellScriptContent:()=>DR,buildSpawnOptions:()=>NR,rewriteWindowsBuildTools:()=>jR});import{spawn as $R,execSync as p4,execFileSync as OR}from"node:child_process";import{mkdtempSync as f4,writeFileSync as PR,rmSync as m4,existsSync as RR}from"node:fs";import{join as fd,resolve as IR}from"node:path";import{tmpdir as h4}from"node:os";function AR(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${g4[t]}`}function NR(t){return{windowsHide:t==="win32"}}function y4(t){return`'${t.replace(/'/g,"'\\''")}'`}function DR(t,e,n){return n==="win32"||!e?t:`export PATH=${y4(e)}
|
|
502
|
+
${t}`}function _4(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function MR(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
|
|
503
|
+
`)}function jR(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
|
|
504
504
|
`]),r="",o=!0,s=0;for(;s<t.length;){let i=t[s];if(o&&(i===" "||i===" ")){r+=i,s++;continue}if(o&&t.startsWith("mvn",s)){let a=t[s+3];if(a===void 0||a===" "||a===" "||a===`
|
|
505
|
-
`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function
|
|
505
|
+
`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function CR(t){try{m4(t,{recursive:!0,force:!0,maxRetries:qt?8:2,retryDelay:100})}catch{}}function _b(t){if(qt&&t.pid)try{p4(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var qt,g4,b4,gi,bb=x(()=>{"use strict";as();qt=process.platform==="win32",g4={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};b4=(()=>{if(qt)return process.env.TEMP??process.env.TMP??h4();try{let t=OR(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:IR(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();gi=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??oo()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(qt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=f4(fd(b4,".ctx-mode-"));try{let c=this.#a(a,r,n),u=yp(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||CR(a),d}catch(c){throw CR(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=IR(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
|
|
506
506
|
|
|
507
507
|
import "fmt"
|
|
508
508
|
|
|
@@ -510,12 +510,12 @@ func main() {
|
|
|
510
510
|
${n}
|
|
511
511
|
}
|
|
512
512
|
`),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
|
|
513
|
-
${n}`),r==="elixir"&&
|
|
513
|
+
${n}`),r==="elixir"&&RR(fd(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(fd(this.#s,"_build/dev/lib"))}, "*/ebin"))
|
|
514
514
|
|> Enum.each(&Code.prepend_path/1)
|
|
515
515
|
|
|
516
|
-
${n}`);let o=
|
|
517
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=
|
|
518
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:T,exitCode:p?1:b??1,timedOut:p})}),d.on("error",b=>{clearTimeout(f),!m&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",
|
|
516
|
+
${n}`);let o=fd(e,AR(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=jR(n,process.platform),a=qt&&_4(s)?MR(i):i;PR(o,DR(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else PR(o,n,"utf-8");return o}async#c(e,n,r){let o=qt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{OR("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
517
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=qt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;qt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=qt?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!qt,...NR(process.platform)},d;if(a){let b=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");d=$R(b,[],{...l,shell:!0})}else d=$R(c,u,{...l,shell:!1});let p=!1,m=!1,f=o===void 0?void 0:setTimeout(()=>{if(p=!0,s){m=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let b=Buffer.concat(h).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else _b(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?h.push(b):_||(_=!0,_b(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,_b(d))}),d.on("close",b=>{if(clearTimeout(f),m)return;let S=Buffer.concat(h).toString("utf-8"),T=Buffer.concat(g).toString("utf-8");_&&(T+=`
|
|
518
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:T,exitCode:p?1:b??1,timedOut:p})}),d.on("error",b=>{clearTimeout(f),!m&&i({stdout:"",stderr:b.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",qt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=qt?"":"/usr/local/bin:/usr/bin:/bin"),qt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}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=qt?[]:["/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(RR(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
|
|
519
519
|
const file_path = FILE_CONTENT_PATH;
|
|
520
520
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
521
521
|
${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
|
|
@@ -573,7 +573,7 @@ file_content = File.read!(file_content_path)
|
|
|
573
573
|
${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
|
|
574
574
|
var file_path = FILE_CONTENT_PATH;
|
|
575
575
|
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
576
|
-
${r}`}}}});import{cpus as
|
|
576
|
+
${r}`}}}});import{cpus as x4}from"node:os";async function xb(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,x4().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let m=l++;if(m>=t.length)return;try{let f=await t[m].run();u[m]={status:"fulfilled",value:f}}catch(f){u[m]={status:"rejected",reason:f}}o?.(m,u[m])}}let p=[];for(let m=0;m<a;m++)p.push(d());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var zR=x(()=>{"use strict"});function Sb(t,e){return t===void 0?e:`${t}::${e}`}var HR=x(()=>{"use strict"});function UR(t){try{let e=new URL(t);return e.hash="",e.toString()}catch{return t}}function FR(t){try{return new URL(t).host.toLowerCase()}catch{return""}}var md,vb=x(()=>{"use strict";er();md=class{#e;constructor(e){let n=Xe();vr(e),this.#e=new n(e,{timeout:3e4}),so(this.#e),this.#e.exec(`
|
|
577
577
|
CREATE TABLE IF NOT EXISTS pages (
|
|
578
578
|
page_key TEXT PRIMARY KEY,
|
|
579
579
|
host TEXT NOT NULL,
|
|
@@ -605,31 +605,31 @@ ${r}`}}}});import{cpus as g4}from"node:os";async function _b(t,e){let{concurrenc
|
|
|
605
605
|
ON CONFLICT(page_key) DO UPDATE SET
|
|
606
606
|
host = excluded.host, url = excluded.url, source_label = excluded.source_label,
|
|
607
607
|
route = excluded.route, provisional = excluded.provisional,
|
|
608
|
-
fetched_at = excluded.fetched_at, full_text = excluded.full_text`),o=this.#e.prepare("DELETE FROM page_blocks WHERE page_key = ?"),s=this.#e.prepare("INSERT INTO page_blocks (page_key, ordinal, hash, kind, raw, text) VALUES (?, ?, ?, ?, ?, ?)"),i=this.#e.transaction(()=>{r.run(e.pageKey,e.host,e.url,e.sourceLabel,e.route,e.provisional?1:0,e.fullText),o.run(e.pageKey);for(let a of n)s.run(e.pageKey,a.ordinal,a.hash,a.kind,a.raw,a.text)});
|
|
609
|
-
FROM pages WHERE host = ? AND provisional = 1 AND page_key <> ?`).all(e,n).map(o=>({pageKey:String(o.page_key),host:String(o.host),url:String(o.url),sourceLabel:String(o.source_label),route:String(o.route),provisional:Number(o.provisional)===1,fullText:String(o.full_text)}))}blocksOf(e){return this.#e.prepare("SELECT ordinal, hash, kind, raw, text FROM page_blocks WHERE page_key = ? ORDER BY ordinal").all(e).map(r=>({ordinal:Number(r.ordinal),hash:String(r.hash),kind:String(r.kind)==="template"?"template":"content",raw:String(r.raw),text:String(r.text)}))}fullTextOf(e){let n=this.#e.prepare("SELECT full_text FROM pages WHERE page_key = ?").get(e);return n?n.full_text:null}close(){try{this.#e.close()}catch{}}}});import{createHash as
|
|
610
|
-
`||t==="\r"||t==="\f"||t==="\v"}function
|
|
611
|
-
`&&(e.push(t.substring(n,r+1)),n=r+1);return n<t.length&&e.push(t.substring(n)),e}function
|
|
608
|
+
fetched_at = excluded.fetched_at, full_text = excluded.full_text`),o=this.#e.prepare("DELETE FROM page_blocks WHERE page_key = ?"),s=this.#e.prepare("INSERT INTO page_blocks (page_key, ordinal, hash, kind, raw, text) VALUES (?, ?, ?, ?, ?, ?)"),i=this.#e.transaction(()=>{r.run(e.pageKey,e.host,e.url,e.sourceLabel,e.route,e.provisional?1:0,e.fullText),o.run(e.pageKey);for(let a of n)s.run(e.pageKey,a.ordinal,a.hash,a.kind,a.raw,a.text)});ze(()=>i())}relabelPage(e,n,r){let o=this.#e.prepare("UPDATE page_blocks SET kind = ? WHERE page_key = ? AND ordinal = ?"),s=this.#e.prepare("UPDATE pages SET provisional = ? WHERE page_key = ?"),i=this.#e.transaction(()=>{for(let a of n)o.run(a.kind,e,a.ordinal);s.run(r?1:0,e)});ze(()=>i())}provisionalPages(e,n){return this.#e.prepare(`SELECT page_key, host, url, source_label, route, provisional, full_text
|
|
609
|
+
FROM pages WHERE host = ? AND provisional = 1 AND page_key <> ?`).all(e,n).map(o=>({pageKey:String(o.page_key),host:String(o.host),url:String(o.url),sourceLabel:String(o.source_label),route:String(o.route),provisional:Number(o.provisional)===1,fullText:String(o.full_text)}))}blocksOf(e){return this.#e.prepare("SELECT ordinal, hash, kind, raw, text FROM page_blocks WHERE page_key = ? ORDER BY ordinal").all(e).map(r=>({ordinal:Number(r.ordinal),hash:String(r.hash),kind:String(r.kind)==="template"?"template":"content",raw:String(r.raw),text:String(r.text)}))}fullTextOf(e){let n=this.#e.prepare("SELECT full_text FROM pages WHERE page_key = ?").get(e);return n?n.full_text:null}close(){try{this.#e.close()}catch{}}}});import{createHash as S4}from"node:crypto";function kb(t,e){return t.lastIndexOf(e,0)===0}function wb(t){return t===" "||t===" "||t===`
|
|
610
|
+
`||t==="\r"||t==="\f"||t==="\v"}function Eb(t){let e=0,n=t.length;for(;e<n&&wb(t.charAt(e));)e++;for(;n>e&&wb(t.charAt(n-1));)n--;return e===0&&n===t.length?t:t.substring(e,n)}function v4(t){let e=[],n=0;for(let r=0;r<t.length;r++)t.charAt(r)===`
|
|
611
|
+
`&&(e.push(t.substring(n,r+1)),n=r+1);return n<t.length&&e.push(t.substring(n)),e}function BR(t){let e=[];if(t.length===0)return e;let n=v4(t),r=[],o=!1,s=!1,i=!1,a=()=>{if(r.length===0)return;let c=r.join(""),u=Eb(c);e.push({ordinal:e.length,raw:c,text:u,hash:w4(u)}),r=[],o=!1};for(let c of n){let u=Eb(c),l=kb(u,"```")||kb(u,"~~~"),d=!s&&u.length===0,p=!s&&!l&&kb(u,"#");!d&&(i||p)&&o&&(a(),i=!1),l&&(s=!s),r.push(c),d||(o=!0),d&&(i=!0)}return a(),e}function k4(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t.charAt(r);if(wb(o)){n=!0;continue}n&&e.length>0&&(e+=" "),n=!1,e+=o}return e.toLowerCase()}function w4(t){return S4("sha256").update(k4(t),"utf-8").digest("hex")}function Tb(t){let{blocks:e,otherPageCount:n,hostPageCount:r,authored:o}=t,s=!o&&r<1,i=[],a=0,c=0,u=!1,l=!1;for(let d of e){let p=d.text.length>0;p&&(l=!0);let f=p&&!o&&!s&&n(d.hash)>=1?"template":"content";f==="content"?(p&&(u=!0),a+=Buffer.byteLength(d.text,"utf-8")):c+=Buffer.byteLength(d.text,"utf-8"),i.push({...d,kind:f})}return{blocks:i,provisional:s,allTemplate:l&&!u,contentBytes:a,templateBytes:c}}function $b(t){let e="";for(let n of t)n.kind==="content"&&(e+=n.raw);return Eb(e)}var ZR=x(()=>{"use strict"});function qR(t){return t==="json"||t==="text"}function VR(t){let{url:e,sourceLabel:n,document:r,route:o,store:s}=t,i=UR(e),a=FR(e),c=Buffer.byteLength(r,"utf-8"),u=BR(r),l=o==="markdown",d=s.hostPageCount(a,i),p=l?new Map:s.otherPageCounts(a,i,u.map(h=>h.hash)),m=Tb({blocks:u,otherPageCount:h=>p.get(h)??0,hostPageCount:d,authored:l});if(s.recordPage({pageKey:i,host:a,url:e,sourceLabel:n,route:o,provisional:m.provisional,fullText:r},m.blocks),m.allTemplate)return{kind:"refuse",storedBytes:c,route:o,reason:`every block of this page is byte-identical to blocks already seen on other pages of ${a}, so the response carried the site shell rather than this page \u2014 its content is rendered client-side by JavaScript and an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered). Retrying this URL returns the same shell; look for this site's llms.txt, a raw .md source, an OpenAPI spec, or a repository README instead.`};let f=[];if(!m.provisional)for(let h of s.provisionalPages(a,i)){let g=s.blocksOf(h.pageKey),y=s.otherPageCounts(a,h.pageKey,g.map(b=>b.hash)),_=Tb({blocks:g.map(b=>({ordinal:b.ordinal,raw:b.raw,text:b.text,hash:b.hash})),otherPageCount:b=>y.get(b)??0,hostPageCount:s.hostPageCount(h.host,h.pageKey),authored:h.route==="markdown"});_.allTemplate||(s.relabelPage(h.pageKey,_.blocks,_.provisional),_.templateBytes>0&&f.push({sourceLabel:h.sourceLabel,url:h.url,indexText:$b(_.blocks),templateBytes:_.templateBytes}))}return{kind:"index",indexText:$b(m.blocks),storedBytes:c,contentBytes:m.contentBytes,templateBytes:m.templateBytes,templateBlocks:E4(m.blocks),totalBlocks:m.blocks.length,provisional:m.provisional,route:o,relabelled:f}}function E4(t){let e=0;for(let n of t)n.kind==="template"&&e++;return e}var WR=x(()=>{"use strict";ZR();vb()});function Pb(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
|
|
612
612
|
|
|
613
613
|
stdout:
|
|
614
614
|
${r}
|
|
615
615
|
|
|
616
616
|
stderr:
|
|
617
|
-
${o}`}}var
|
|
618
|
-
`),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}var
|
|
619
|
-
`)}for(let h of f){if(s.length>=e)break;try{let g;try{if(g=
|
|
617
|
+
${o}`}}var KR=x(()=>{"use strict"});import{execFileSync as T4}from"node:child_process";function $4(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=T4("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function P4(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??$4,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}function C4(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function O4(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function I4(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}function Rb(){dc=Date.now()}function GR(){hd++,dc=Date.now()}function JR(){hd>0&&hd--,dc=Date.now()}function XR(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{Rb()}catch{}return e(n,r)})}function YR(t){let e=t.checkIntervalMs??C4(),n=t.isParentAlive??R4,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??O4(),u;return c>0&&(dc=Date.now(),u=setInterval(()=>{hd===0&&Date.now()-dc>=c&&(process.stderr.write(I4(c)+`
|
|
618
|
+
`),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}var R4,dc,hd,QR=x(()=>{"use strict";R4=P4();dc=Date.now(),hd=0});function eC(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}var tC=x(()=>{"use strict"});import{existsSync as Cb,unlinkSync as A4}from"node:fs";import{join as pc}from"node:path";function Ob(t,e){try{return A4(t),e.push(t),!0}catch{return!1}}function gd(t,e){let n=!1;for(let r of N4)Ob(`${t}${r}`,e)&&r===""&&(n=!0);return n}function nC(t){let{projectDir:e,sessionsDir:n,storePath:r,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 b=Ui(e),S=st(e),T=jn(e),D=S===T?[S]:[S,T],v=!1;for(let A of D){let R=pc(n,`${A}${b}.db`);if(!Cb(R))continue;let C=null;try{C=new nn({dbPath:R});let z=C.getEvents(a).length;C.deleteSession(a),z>0&&(v=!0)}catch{}finally{try{C?.close()}catch{}}}v&&u.push(`session rows for ${a}`);let $=[];if(r&&Cb(r)&&$.push(r),o){let A=st(e),R=jn(e),C=A===R?[A]:[A,R];for(let z of C){let B=pc(o,`${z}.db`);Cb(B)&&!$.includes(B)&&$.push(B)}}let P=!1;for(let A of $)try{let R=Xe(),C=new R(A,{timeout:3e4});try{let z=C.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;C.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),C.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),z>0&&(P=!0)}finally{try{C.close()}catch{}}}catch{}return P&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let p=!1;if(r&&gd(r,l)&&(p=!0),o){let b=st(e),S=jn(e),T=b===S?[b]:[b,S];for(let D of T){let v=pc(o,`${D}.db`);gd(v,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 b=pc(s,`${i}.db`);gd(b,l)}let m=Ui(e),f=st(e),h=jn(e),g=f===h?[f]:[f,h],y=!1,_=!1;for(let b of g){let S=pc(n,`${b}${m}`);gd(`${S}.db`,l)&&(y=!0),Ob(`${S}-events.md`,l)&&(_=!0),Ob(`${S}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}var N4,rC=x(()=>{"use strict";er();rn();N4=["","-wal","-shm"]});import{existsSync as D4}from"node:fs";function Ib(t,e){try{if(!D4(t))return;let n=new nn({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function oC(t){Ib(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 sC(t){Ib(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 iC(t){Ib(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 aC=x(()=>{"use strict";rn()});import{existsSync as cC}from"node:fs";function uC(t,e,n){try{if(!cC(t))return;let r=new nn({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function lC(t){try{if(!cC(t))return null;let e=new nn({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);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 dC=x(()=>{"use strict";rn()});import{existsSync as Ab,readFileSync as M4,readdirSync as j4,statSync as L4}from"node:fs";import{join as yi,isAbsolute as z4}from"node:path";function mC(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?fC(n,a):null)??r??Ze(),l=o?.getMemoryDir(n),d=yi(u,"memory"),p=n?yi(d,st(n)):d,m=l?fC(n,l):p,f=[];if(n)for(let h of i){let g=yi(n,h);Ab(g)&&f.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=yi(u,h);Ab(g)&&f.push({path:g,label:`user/${h}`})}if(m&&Ab(m))try{let h=j4(m).filter(g=>g.endsWith(".md"));for(let g of h)f.push({path:yi(m,g),label:`memory/${g}`})}catch(h){pC&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
|
|
619
|
+
`)}for(let h of f){if(s.length>=e)break;try{let g;try{if(g=L4(h.path),g.size>1e6)continue}catch{continue}let y=M4(h.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let T=b.toLowerCase().split(/\s+/).filter(v=>v.length>=3);if(T.some(v=>{try{return new RegExp(`\\b${v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(v)}})){let v=T.reduce((z,B)=>{let ge=_.indexOf(B);return ge>=0&&(z<0||ge<z)?ge:z},-1),$=Math.max(0,v-200),P=Math.min(y.length,v+500),A=y.lastIndexOf(`
|
|
620
620
|
|
|
621
621
|
`,$),R=y.indexOf(`
|
|
622
622
|
|
|
623
|
-
`,P);A>=0&&($=A+2),R>=0&&(P=R);let C=y.slice($,P).trim();s.push({title:`[auto-memory] ${h.label}`,content:C,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){
|
|
624
|
-
`)}}return s.slice(0,e)}function
|
|
625
|
-
`)}try{let h=r.searchWithFallback(e,n,s,i,"like",f);p.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||m,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){
|
|
626
|
-
`)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);p.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){
|
|
627
|
-
`)}try{let h=
|
|
628
|
-
`)}}for(let h of p)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var
|
|
629
|
-
`).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{
|
|
630
|
-
`).slice(0,10))if(m.trim())try{let f=JSON.parse(m),h=f?.meta?.cwd??(f?.type==="session_meta"?f?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return
|
|
631
|
-
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function
|
|
632
|
-
FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function
|
|
623
|
+
`,P);A>=0&&($=A+2),R>=0&&(P=R);let C=y.slice($,P).trim();s.push({title:`[auto-memory] ${h.label}`,content:C,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){pC&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
624
|
+
`)}}return s.slice(0,e)}function fC(t,e){return e?z4(e)||!t?e:yi(t,e):t??""}var pC,hC=x(()=>{"use strict";Pr();rn();pC=process.env.DEBUG?.includes("context-mode")});function gC(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,p=[],m=new Date().toISOString(),f;if(typeof d=="string"&&a)try{f=new Set(a.getSessionIdsForProject(d))}catch(h){yd&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
|
|
625
|
+
`)}try{let h=r.searchWithFallback(e,n,s,i,"like",f);p.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||m,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){yd&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
|
|
626
|
+
`)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);p.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){yd&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
|
|
627
|
+
`)}try{let h=mC([e],n,c,u,l);p.push(...h)}catch(h){yd&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
|
|
628
|
+
`)}}for(let h of p)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&p.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),p.slice(0,n)}var yd,yC=x(()=>{"use strict";hC();yd=process.env.DEBUG?.includes("context-mode")});function H4(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function _C(t){let e=t?{project:j.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 j.object({queries:j.preprocess(H4,j.array(j.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:j.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:j.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:j.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:j.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 bC(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var Nb,xC=x(()=>{"use strict";ud();Nb=!!process.env.CONTEXT_MODE_PROJECT_DIR});var _d,SC=x(()=>{"use strict";_d=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}}});import*as Qe from"node:fs";import*as vC from"node:os";import*as _i from"node:path";function bd(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function B4(t){if(!Qe.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Qe.readdirSync(t.projectsRoot)){let o=_i.join(t.projectsRoot,r),s;try{s=Qe.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Qe.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=_i.join(o,a);try{let u=Qe.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Qe.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Qe.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
|
|
629
|
+
`).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{Qe.closeSync(r)}}catch{}}function Z4(t){let e=t?.codexHome??process.env.CODEX_HOME??_i.join(vC.homedir(),".codex"),n=_i.join(e,"sessions");if(!Qe.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Qe.readdirSync(u)}catch{return}d.sort().reverse();for(let p of d){if(s>=o)return;s++;let m=_i.join(u,p),f;try{f=Qe.statSync(m)}catch{continue}if(f.isDirectory()){l<r&&c(m,l+1);continue}if(!f.isFile()||!p.endsWith(".jsonl"))continue;let h=f.mtimeMs;h>a&&(a=h,i=m)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Qe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Qe.readSync(u,l,0,l.length,0),p=l.subarray(0,d).toString("utf-8");for(let m of p.split(`
|
|
630
|
+
`).slice(0,10))if(m.trim())try{let f=JSON.parse(m),h=f?.meta?.cwd??(f?.type==="session_meta"?f?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return bd(h)?null:h}catch{return null}}finally{Qe.closeSync(u)}}catch{return null}return null}function kC(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...Of(a),...U4]:F4;for(let l of u){let d=e[l];if(d&&!bd(d))return d}if(o){let l=B4({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!bd(l))return l}if(a==="codex"){let l=Z4({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!bd(r)?r:n}var U4,F4,wC=x(()=>{"use strict";_o();U4=["CONTEXT_MODE_PROJECT_DIR"],F4=["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 q4}from"node:child_process";import{existsSync as hr,readdirSync as bi,statSync as V4}from"node:fs";import{homedir as wd}from"node:os";import{join as Yt,sep as W4}from"node:path";function IC(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function G4(t){let e=t?.home??wd();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=Yt(e,...o,"context-mode");return{name:r,sessionsDir:Yt(s,"sessions"),contentDir:Yt(s,"content")}})}function J4(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function fc(t){let e=Ze(),n=t?.sessionsDir??Yt(e,"context-mode","sessions"),r=t?.memoryRoot??Yt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(hr(n)){let m=[];try{m=bi(n).filter(f=>f.endsWith(".db"))}catch{}if(m.length>0){let f=null;try{f=t?.loadDatabase?t.loadDatabase():Xe()}catch{}if(f)for(let h of m){let g=Yt(n,h);try{let y=new f(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),b=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=b?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let T of S)T.category&&(u[T.category]=(u[T.category]??0)+(T.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let T=S.t.endsWith("Z")?S.t:S.t+"Z",D=Date.parse(T);Number.isFinite(D)&&D<a&&(a=D)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let T of S)T.p&&c.add(T.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,p={};if(hr(r)){let m=[];try{m=bi(r).filter(f=>{try{return V4(Yt(r,f)).isDirectory()}catch{return!1}})}catch{}for(let f of m){let h=Yt(r,f,"memory");if(!hr(h))continue;let g=[];try{g=bi(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=J4(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 AC(t){let e=t.sessionsDir??Yt(wd(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!hr(e))return r;let o=[];try{o=bi(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():Xe()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,p=0,m=0,f=new Map,h=b=>Math.floor(b/864e5)*864e5;for(let b of o){let S=Yt(e,b),T=!1;try{let D=new s(S,{readonly:!0});try{let v=D.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let P of v)P.category&&(i[P.category]=(i[P.category]??0)+(P.cnt??0),a+=P.cnt??0,T=!0);let $=D.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if($?.mn){let P=Date.parse($.mn+($.mn.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P<d&&(d=P)}if($?.mx){let P=Date.parse($.mx+($.mx.endsWith("Z")?"":"Z"));Number.isFinite(P)&&P>p&&(p=P)}try{let P=D.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let A of P){if(!A.sec)continue;let R=parseInt(A.sec,10)*1e3;if(!Number.isFinite(R))continue;let C=h(R),z=f.get(C)??{count:0,rescueBytes:0};z.count+=A.cnt??0,f.set(C,z)}}catch{}try{let P=D.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(n);if(P?.bytes&&(u+=P.bytes),P?.n&&(l+=P.n),P?.lastSec){let A=parseInt(P.lastSec,10)*1e3;if(Number.isFinite(A)&&A>m&&(m=A),Number.isFinite(A)&&(P?.bytes??0)>0){let R=h(A),C=f.get(R)??{count:0,rescueBytes:0};C.rescueBytes=Math.max(C.rescueBytes,P.bytes),f.set(R,C)}}}catch{}}finally{D.close()}}catch{}T&&c++}let g=d<p?(p-d)/864e5:0,y=Object.entries(i).filter(([,b])=>b>0).map(([b,S])=>({category:b,count:S,label:Sd[b]||b})).sort((b,S)=>S.count-b.count),_=[...f.entries()].sort((b,S)=>b[0]-S[0]).map(([b,S])=>({ms:b,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:p>0?p:0,lastRescueMs:m>0?m:void 0,byDay:_}}function X4(t,e,n){if(!t||!e||!hr(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():Xe()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
631
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function NC(t,e){if(!t||!hr(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():Xe()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
632
|
+
FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function mc(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??Yt(wd(),".claude","context-mode","sessions");if(!hr(n))return e;let r=[];try{r=bi(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():Xe()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let p=Yt(n,d);Ep(p,o);try{let m=new o(p,{readonly:!0});try{if(t.sessionId){let f=m.prepare(`SELECT
|
|
633
633
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
634
634
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
635
635
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
@@ -655,49 +655,49 @@ ${o}`}}var BR=x(()=>{"use strict"});import{execFileSync as v4}from"node:child_pr
|
|
|
655
655
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
656
656
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
657
657
|
FROM session_events`).get();f&&(s+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}try{let h=m.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
|
|
658
|
-
WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=W4(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 G4(t,e,n){let r={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(!hr(t.sessionsDir))return r;let o=[];try{o=bi(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=Jt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let m=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();m&&(r.eventCount+=Number(m.cnt??0),r.dataBytes+=Number(m.bytes??0));try{let f=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(f?.cnt??0)}catch{}try{let f=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();f?.bytes&&(r.rescueBytes+=Number(f.bytes))}catch{}try{let f=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(f?.mn){let h=Date.parse(f.mn+(f.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<r.firstMs&&(r.firstMs=h)}if(f?.mx){let h=Date.parse(f.mx+(f.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>r.lastMs&&(r.lastMs=h)}}catch{}try{let f=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of f)h.p&&i.add(h.p)}catch{}try{let f=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of f)h.s&&a.add(h.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function vd(t){let e=q4({home:t?.home}),n=t?.loadDatabase??Je,r={...K4,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!hr(c.sessionsDir))continue;let u=G4(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function bd(t){return J4[t]??t}function mt(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function X4(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function yd(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function Y4(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!yd(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=U4("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!yd(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!yd(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return yd(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function xC(t){let e=Sd();return e?t===e?"~":t.startsWith(e+B4)?"~"+t.slice(e.length):t:t}function Q4(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*pc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),m=(e*1/1e6).toFixed(2),f=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return f&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):f?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${mt(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.`)),f||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function eV(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*EC,m=Math.round((e.snapshotBytes??0)/4),f=p+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(f,h),y=(n?.totalEvents??0)*EC,_=Math.round((n?.rescueBytes??0)/4),b=y+_,S=o?.lifetime?.totalSavedTokens??0,T=Math.max(b,S),D=o?.lifetime?.bytesReturned??0,v=o?.lifetime?.bytesAvoided??0,$=D+v>0?Math.max(1,Math.floor(D/4)):Math.max(1,Math.round(T*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:T*4,A=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`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,z=C>0?Math.max(1,Math.round((c-C)/864e5)):0,B=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Fe=>Fe.isReal).length??0,Le;if(r&&ge>=2)Le=`across ${ge} AI tools`;else if(r&&ge===1){let Fe=r.perAdapter.find(gn=>gn.isReal);Le=`in ${Fe?bd(Fe.name):"Claude Code"}`}else Le="in Claude Code";z>0?d.push(` Across ${z} days you ran ${Pn(B)} conversations ${Le}.`):d.push(` You ran ${Pn(B)} conversations ${Le}.`);let it=z>0?P/z:0;d.push(` context-mode kept ${mt(P)} out of your context window \u2014 about ${mt(it)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let In=e.firstEventMs&&e.firstEventMs>0?SC(e.firstEventMs,i,a):"";if(In?d.push(` This conversation started ${In} in ${xC(s)}.`):d.push(` This conversation lives in ${xC(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Fe=e.lastRescueMs&&e.lastRescueMs>0?SC(e.lastRescueMs,i,a):"",gn=Math.round(e.snapshotBytes/1024);Fe?d.push(` On ${Fe}, /compact fired \u2014 ${gn} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${gn} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let wc=o?.conversation,Ec=wc?.bytesAvoided??0,Wd=wc?.bytesReturned??0;if(Ec+Wd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Fe=Ec+Wd,gn=Math.max(1,Wd),yn=Math.max(1,Math.floor(Fe/4)),Qn=Math.max(1,Math.floor(gn/4)),Kd=to(yn,yn,32),YO=to(Qn,yn,32),QO=(1-Qn/yn)*100,eI=Math.max(1,Math.round(yn/Qn));d.push(` Without context-mode ${mt(Fe).padStart(8)} ${Kd} ${Pn(yn).padStart(7)} tokens`),d.push(` With context-mode ${mt(gn).padStart(8)} ${YO} ${Pn(Qn).padStart(7)} tokens`),d.push(` ${QO.toFixed(1)}% kept out of context \xB7 your AI ran ${eI}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Fe=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${mt(A)} built up \u2014 ${Fe} days, ${e.byDay.length} active:`),d.push(""),d.push(...nV(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 KO=e.byCategory.reduce((Fe,gn)=>Fe+gn.count,0).toLocaleString(i);d.push(` ${KO} things \u2014 files, errors, decisions, agent runs:`),d.push("");let GO=e.byCategory[0]?.count??1;for(let Fe of e.byCategory)d.push(` ${Fe.label.padEnd(26)} ${String(Fe.count).padStart(5)} ${to(Fe.count,GO,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let tx=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",nx=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",rx=n?.distinctProjects??0,JO=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${mt(A)} kept out \xB7 ${e.events.toLocaleString(i)} captures${tx?` \xB7 started ${tx}`:""}.`),d.push(` All your work: ${mt(P)} kept out \xB7 ${JO.toLocaleString(i)} captures across ${rx} project${rx===1?"":"s"}${nx?` \xB7 since ${nx}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...Q4(P,T,z)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Fe=Object.entries(n.autoMemoryByPrefix).sort((yn,Qn)=>Qn[1]-yn[1]),gn=Fe.length>0?Fe[0][1]:1;for(let[yn,Qn]of Fe){let Kd=CC[yn]??yn;d.push(` ${Kd.padEnd(26)} ${String(Qn).padStart(2)} ${to(Qn,gn,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 XO=u?`v${u}`:"context-mode";return d.push(` ${XO}`),u&&l&&l!=="unknown"&&$C(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),tV(d)}function tV(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function nV(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,m)=>p.ms-m.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let m=Math.round((p.ms-o.ms)/i*(c-1)),f="\u25CF";p===a&&(f="\u2588"),(p.rescueBytes??0)>0&&(f="\u25C6"),u[m]=f}let l=p=>{let m=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),f=(m.find(g=>g.type==="month")?.value??"").toLowerCase(),h=m.find(g=>g.type==="day")?.value??"";return`${f} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let m=l(p.ms).padEnd(7),f=`${p.count} captures`,h=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${m} ${f}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function SC(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),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} (${n})`}function Pn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function pc(){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 5/1e6}function xd(t){return`$${((Number.isFinite(t)&&t>0?t:0)*pc()).toFixed(2)}`}function to(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function vC(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.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 h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${Pn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${Pn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${Pn(h)} sessions`,y=a*256+n;o.push(` ${Pn(a)} events \xB7 ${g} \xB7 ~${xd(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:_d[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let p=d.slice(0,r),m=p.length>0?p[0].count:1;for(let h of p)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${to(h.count,m,30)}`);let f=Math.max(0,d.length-r);return f>0&&o.push(` ... ${f} more categor${f===1?"y":"ies"}`),o}function kC(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=CC[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${to(s,r,20)}`)}return e}function wC(t,e){let n=[],r=xd(t),o=(e?.totalEvents??0)*256+t,s=xd(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function TC(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?Pn(u.eventCount):"\u2014",p=mt(u.dataBytes),m=mt(l);r.push(` ${bd(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${m.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>bd(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function kd(t,e,n,r){let o=[],s=X4(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(D=>D.isReal).length??0;if(l&&d>0){let D=l.totalSessions||i?.totalSessions||0,v=i?.firstEventMs??0,$=v>0?Math.max(1,Math.round((Date.now()-v)/864e5)):0,P=$>0?`Across ${$} day${$===1?"":"s"} `:"",A=D>0?`you ran ${Pn(D)} conversation${D===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(z=>z.isReal);R=`in ${C?bd(C.name):"Claude Code"}`}o.push(`${P}${A}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let D=Y4(),v=r?.cwd??process.cwd(),$=r?.now??Date.now(),P=r?.locale??D.locale,A=r?.tz??D.tz;return o.push(...eV({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:v,locale:P,tz:A,now:$,version:e,latestVersion:n})),o.join(`
|
|
659
|
-
`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),m=t.savings.total_bytes_returned,f=t.savings.total_calls,h=p+m,g=h>0?p/h*100:0,y=Math.round(p/4),_=m>0?Math.max(1,Math.round(h/Math.max(m,1))):0;if(p===0){o.push(`context-mode ${s} ${f} calls`),o.push(""),f===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${
|
|
660
|
-
`)}o.push(`${
|
|
661
|
-
`)}var
|
|
662
|
-
`)}function
|
|
658
|
+
WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=X4(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 Q4(t,e,n){let r={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(!hr(t.sessionsDir))return r;let o=[];try{o=bi(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=Yt(t.sessionsDir,l);try{let p=new s(d,{readonly:!0});try{let m=p.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();m&&(r.eventCount+=Number(m.cnt??0),r.dataBytes+=Number(m.bytes??0));try{let f=p.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.sessionCount+=Number(f?.cnt??0)}catch{}try{let f=p.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();f?.bytes&&(r.rescueBytes+=Number(f.bytes))}catch{}try{let f=p.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(f?.mn){let h=Date.parse(f.mn+(f.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<r.firstMs&&(r.firstMs=h)}if(f?.mx){let h=Date.parse(f.mx+(f.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>r.lastMs&&(r.lastMs=h)}}catch{}try{let f=p.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of f)h.p&&i.add(h.p)}catch{}try{let f=p.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of f)h.s&&a.add(h.s)}catch{}}finally{p.close()}}catch{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function Ed(t){let e=G4({home:t?.home}),n=t?.loadDatabase??Xe,r={...Y4,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!hr(c.sessionsDir))continue;let u=Q4(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function vd(t){return eV[t]??t}function yt(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function tV(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function xd(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function nV(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!xd(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=q4("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!xd(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!xd(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return xd(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function EC(t){let e=wd();return e?t===e?"~":t.startsWith(e+W4)?"~"+t.slice(e.length):t:t}function rV(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*hc(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),p=(e*1.25/1e6).toFixed(2),m=(e*1/1e6).toFixed(2),f=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return f&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):f?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${yt(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.`)),f||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function oV(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],p=e.events*CC,m=Math.round((e.snapshotBytes??0)/4),f=p+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(f,h),y=(n?.totalEvents??0)*CC,_=Math.round((n?.rescueBytes??0)/4),b=y+_,S=o?.lifetime?.totalSavedTokens??0,T=Math.max(b,S),D=o?.lifetime?.bytesReturned??0,v=o?.lifetime?.bytesAvoided??0,$=D+v>0?Math.max(1,Math.floor(D/4)):Math.max(1,Math.round(T*.02)),P=r?.totalBytes&&r.totalBytes>0?r.totalBytes:T*4,A=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`,C=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,z=C>0?Math.max(1,Math.round((c-C)/864e5)):0,B=r?.totalSessions??n?.totalSessions??1,ge=r?.perAdapter.filter(Be=>Be.isReal).length??0,Le;if(r&&ge>=2)Le=`across ${ge} AI tools`;else if(r&&ge===1){let Be=r.perAdapter.find(_n=>_n.isReal);Le=`in ${Be?vd(Be.name):"Claude Code"}`}else Le="in Claude Code";z>0?d.push(` Across ${z} days you ran ${Rn(B)} conversations ${Le}.`):d.push(` You ran ${Rn(B)} conversations ${Le}.`);let ut=z>0?P/z:0;d.push(` context-mode kept ${yt(P)} out of your context window \u2014 about ${yt(ut)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let In=e.firstEventMs&&e.firstEventMs>0?TC(e.firstEventMs,i,a):"";if(In?d.push(` This conversation started ${In} in ${EC(s)}.`):d.push(` This conversation lives in ${EC(s)}.`),d.push(` ${R}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Be=e.lastRescueMs&&e.lastRescueMs>0?TC(e.lastRescueMs,i,a):"",_n=Math.round(e.snapshotBytes/1024);Be?d.push(` On ${Be}, /compact fired \u2014 ${_n} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${_n} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let Tc=o?.conversation,$c=Tc?.bytesAvoided??0,Xd=Tc?.bytesReturned??0;if($c+Xd===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Be=$c+Xd,_n=Math.max(1,Xd),bn=Math.max(1,Math.floor(Be/4)),Qn=Math.max(1,Math.floor(_n/4)),Yd=eo(bn,bn,32),rI=eo(Qn,bn,32),oI=(1-Qn/bn)*100,sI=Math.max(1,Math.round(bn/Qn));d.push(` Without context-mode ${yt(Be).padStart(8)} ${Yd} ${Rn(bn).padStart(7)} tokens`),d.push(` With context-mode ${yt(_n).padStart(8)} ${rI} ${Rn(Qn).padStart(7)} tokens`),d.push(` ${oI.toFixed(1)}% kept out of context \xB7 your AI ran ${sI}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Be=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${yt(A)} built up \u2014 ${Be} days, ${e.byDay.length} active:`),d.push(""),d.push(...iV(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 QO=e.byCategory.reduce((Be,_n)=>Be+_n.count,0).toLocaleString(i);d.push(` ${QO} things \u2014 files, errors, decisions, agent runs:`),d.push("");let eI=e.byCategory[0]?.count??1;for(let Be of e.byCategory)d.push(` ${Be.label.padEnd(26)} ${String(Be.count).padStart(5)} ${eo(Be.count,eI,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let rx=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",ox=C>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(C)):"",sx=n?.distinctProjects??0,tI=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${yt(A)} kept out \xB7 ${e.events.toLocaleString(i)} captures${rx?` \xB7 started ${rx}`:""}.`),d.push(` All your work: ${yt(P)} kept out \xB7 ${tI.toLocaleString(i)} captures across ${sx} project${sx===1?"":"s"}${ox?` \xB7 since ${ox}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...rV(P,T,z)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Be=Object.entries(n.autoMemoryByPrefix).sort((bn,Qn)=>Qn[1]-bn[1]),_n=Be.length>0?Be[0][1]:1;for(let[bn,Qn]of Be){let Yd=DC[bn]??bn;d.push(` ${Yd.padEnd(26)} ${String(Qn).padStart(2)} ${eo(Qn,_n,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 nI=u?`v${u}`:"context-mode";return d.push(` ${nI}`),u&&l&&l!=="unknown"&&IC(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),sV(d)}function sV(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function iV(t,e,n){if(t.length===0)return[];let r=[...t].sort((p,m)=>p.ms-m.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let p of r)p.count>a.count&&(a=p);let c=56,u=Array.from({length:c},()=>"\u2500");for(let p of r){let m=Math.round((p.ms-o.ms)/i*(c-1)),f="\u25CF";p===a&&(f="\u2588"),(p.rescueBytes??0)>0&&(f="\u25C6"),u[m]=f}let l=p=>{let m=new Intl.DateTimeFormat(e,{timeZone:n,month:"short",day:"numeric"}).formatToParts(new Date(p)),f=(m.find(g=>g.type==="month")?.value??"").toLowerCase(),h=m.find(g=>g.type==="day")?.value??"";return`${f} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let p of r){let m=l(p.ms).padEnd(7),f=`${p.count} captures`,h=p===a?" \u2190 peak":"",g=(p.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((p.rescueBytes??0)/1024)} KB`:"";d.push(` ${m} ${f}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function TC(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),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} (${n})`}function Rn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function hc(){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 5/1e6}function kd(t){return`$${((Number.isFinite(t)&&t>0?t:0)*hc()).toFixed(2)}`}function eo(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function $C(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.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 h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${Rn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${Rn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${Rn(h)} sessions`,y=a*256+n;o.push(` ${Rn(a)} events \xB7 ${g} \xB7 ~${kd(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Sd[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let p=d.slice(0,r),m=p.length>0?p[0].count:1;for(let h of p)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${eo(h.count,m,30)}`);let f=Math.max(0,d.length-r);return f>0&&o.push(` ... ${f} more categor${f===1?"y":"ies"}`),o}function PC(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=DC[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${eo(s,r,20)}`)}return e}function RC(t,e){let n=[],r=kd(t),o=(e?.totalEvents??0)*256+t,s=kd(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}function OC(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?Rn(u.eventCount):"\u2014",p=yt(u.dataBytes),m=yt(l);r.push(` ${vd(u.name).padEnd(o)}${d.padStart(s)}${p.padStart(i)}${m.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>vd(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function Td(t,e,n,r){let o=[],s=tV(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(D=>D.isReal).length??0;if(l&&d>0){let D=l.totalSessions||i?.totalSessions||0,v=i?.firstEventMs??0,$=v>0?Math.max(1,Math.round((Date.now()-v)/864e5)):0,P=$>0?`Across ${$} day${$===1?"":"s"} `:"",A=D>0?`you ran ${Rn(D)} conversation${D===1?"":"s"} `:"you ran ",R;if(d>=2)R=`across ${d} AI tools`;else{let C=l.perAdapter.find(z=>z.isReal);R=`in ${C?vd(C.name):"Claude Code"}`}o.push(`${P}${A}${R}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let D=nV(),v=r?.cwd??process.cwd(),$=r?.now??Date.now(),P=r?.locale??D.locale,A=r?.tz??D.tz;return o.push(...oV({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:v,locale:P,tz:A,now:$,version:e,latestVersion:n})),o.join(`
|
|
659
|
+
`)}let p=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),m=t.savings.total_bytes_returned,f=t.savings.total_calls,h=p+m,g=h>0?p/h*100:0,y=Math.round(p/4),_=m>0?Math.max(1,Math.round(h/Math.max(m,1))):0;if(p===0){o.push(`context-mode ${s} ${f} calls`),o.push(""),f===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${yt(m)} entered context | 0 tokens saved`),o.push(...$C(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...OC(l)),o.push(...PC(i)),o.push(...RC(0,i)),o.push("");let D=e?`v${e}`:"context-mode";return o.push(D),e&&n&&n!=="unknown"&&IC(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
660
|
+
`)}o.push(`${Rn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${kd(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${eo(h,h)}| ${yt(h)}`),o.push(`With context-mode |${eo(m,h)}| ${yt(m)}`),o.push(""),_>=2?o.push(`${yt(p)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${yt(p)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${f} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${yt(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let S=t.savings.by_tool.filter(D=>D.calls>0);if(S.length>=2){o.push("");let D=S.map(v=>{let $=v.context_kb*1024,P=g<100?$/(1-g/100):$,A=Math.max(0,P-$);return{...v,returnedBytes:$,estimatedSaved:A}}).sort((v,$)=>$.estimatedSaved-v.estimatedSaved);for(let v of D){let $=v.tool.length>22?v.tool.slice(0,19)+"...":v.tool;o.push(` ${$.padEnd(22)} ${String(v.calls).padStart(4)} calls ${yt(v.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let D=a.filter(v=>v.median_concurrency!=null&&(v.max_concurrency??1)>1);if(D.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 v of D){let $=v.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${$.padEnd(22)} ${v.calls} batches \xB7 ${v.median_concurrency} typical, ${v.max_concurrency} peak`)}}}o.push(...$C(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...OC(l)),o.push(...PC(i)),o.push(...RC(y,i)),o.push("");let T=e?`v${e}`:"context-mode";return o.push(T),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
|
|
661
|
+
`)}var Sd,K4,xi,Y4,DC,eV,Aee,CC,MC=x(()=>{"use strict";er();rn();Pr();Sd={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"},K4={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"},xi=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=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=n.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)}n.set(i,a)}let r=[];for(let[o,s]of n){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]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=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((C,z)=>C+z,0),s=Object.values(e.calls).reduce((C,z)=>C+z,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(C=>({tool:C,calls:e.calls[C]||0,context_kb:Math.round((e.bytesReturned[C]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[C]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),f,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let C=a+e.cacheBytesSaved,z=C/Math.max(o,1),B=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ge=e.cacheHits+h,Le=ge>0?e.cacheHits/ge:0;f={hits:e.cacheHits,misses:h,hit_rate:Le,bytes_saved:e.cacheBytesSaved,ttl_hours_left:B,total_with_cache:C,total_savings_ratio:z}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,S=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),T=S?!S.consumed:!1,D=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),v=new Map;for(let C of D){v.has(C.category)||v.set(C.category,new Set);let z=v.get(C.category);if(z.size<5){let B=C.data;C.category==="file"?B=C.data.split("/").pop()||C.data:(C.category==="prompt"||C.category==="user-prompt")&&(B=B.length>50?B.slice(0,47)+"...":B),B.length>40&&(B=B.slice(0,37)+"..."),z.add(B)}}let $=y.map(C=>({category:C.category,count:C.cnt,label:Sd[C.category]||C.category,preview:v.get(C.category)?Array.from(v.get(C.category)).join(", "):"",why:K4[C.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(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:Sd[C.category]||C.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:f,session:{id:r,uptime_min:m},continuity:{total_events:g,by_category:$,compact_count:b,resume_ready:T},projectMemory:{total_events:P.cnt,session_count:P.sessions,by_category:R}}}};Y4={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};DC={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},eV={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Aee=5/1e6;CC=256});var vO={};_e(vO,{AGY_DEFAULT_EXEC_TIMEOUT_MS:()=>fO,REGISTERED_CTX_TOOLS:()=>eO,__resetSuppressionDiagnosticForTests:()=>vV,browserOpenArgv:()=>bO,buildBatchNodeOptionsPrefix:()=>dO,buildFetchCode:()=>yO,classifyExtraction:()=>zd,classifyIp:()=>bc,currentAttribution:()=>_r,describeRung:()=>gc,emitSuppressionDiagnostic:()=>rO,extractSnippet:()=>Wb,formatBatchQueryResults:()=>lO,getProjectDir:()=>Et,installStrictClientSchemaCompat:()=>sO,killProcessOnPort:()=>SO,openBrowserSync:()=>xO,parseLadderTried:()=>_O,positionsFromHighlight:()=>uO,registerEmptyToolsListHandler:()=>oO,resolveExecTimeout:()=>Fd,resolveSessionIdFromSessionDB:()=>iO,runBatchCommands:()=>hO,sanitizeSchemaForStrictClients:()=>Dd,server:()=>Ce,shouldSuppressMcpToolsForNativePluginHost:()=>tO,withProjectDirOverride:()=>EV});import{createRequire as WC}from"node:module";import{existsSync as qe,unlinkSync as ki,readdirSync as aV,readFileSync as xc,writeFileSync as Ad,writeSync as cV,renameSync as uV,rmSync as KC,mkdirSync as lV,statSync as GC,symlinkSync as dV,lstatSync as JC,realpathSync as XC}from"node:fs";import{spawnSync as Nd}from"node:child_process";import{join as Vt,dirname as Ti,resolve as Nt,sep as pV,isAbsolute as fV}from"node:path";import{fileURLToPath as mV}from"node:url";import{homedir as wi,tmpdir as Zb,cpus as hV}from"node:os";import{request as gV}from"node:https";import{AsyncLocalStorage as yV}from"node:async_hooks";function YC(){return qe(Nt(Cd,"package.json"))?Cd:Ti(Cd)}function _V(t){try{let e=process.platform==="win32"?Nd("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):Nd("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=Xc(String(e.stdout));if(n&&qe(Nt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function QC(t){let e=YC();return t==="codex"?_V(e):e}function tO(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??tt().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??bV(n);return xV(r)&&SV(r)}function bV(t){let e=t==="kilo"?"kilo":"opencode",n=[Nt(`${e}.json`),Nt(`${e}.jsonc`),Nt(`.${e}`,`${e}.json`),Nt(`.${e}`,`${e}.jsonc`),Vt(wi(),".config",e,`${e}.json`),Vt(wi(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!qe(r))continue;return JSON.parse(qi(xc(r,"utf8")))}catch{}return null}function xV(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function SV(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function rO(t={}){if(Hb)return;Hb=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["${Kt}"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
662
|
+
`)}function vV(){Hb=!1}function oO(t=Ce){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(qo,async()=>({tools:[]}))}function wV(t,e){return async n=>{GR();try{return await e(n)}catch(r){let o=CV(r);if(o)try{return X(t,o)}catch(s){if(s instanceof tn)return o;throw s}throw r}finally{JR()}}}async function EV(t,e){let n=typeof t=="string"?{projectDir:t}:t;return qb.run(n,e)}function Dd(t){if(Array.isArray(t))return t.map(Dd);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=Dd(r)}return e}function sO(t=Ce){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(qo,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=Dd(i.inputSchema)}catch{}}return s})}catch{}}function _r(){let t=qb.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??iO();if(e)return{sessionId:e}}function iO(t){let e=Date.now();if(!t?.bypassCache&&$d&&e-$d.checkedAt<2e3)return $d.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??Ge(),o=ys({projectDir:n,sessionsDir:r});if(!qe(o))return;let s=Xe(),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&&($d={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function TV(t){try{let e=Ge();if(!qe(e))return;let n=Bc({projectDir:Et(),sessionsDir:e,ext:"-events.md"});if(!qe(n))return;try{t.index({path:n,source:"session-events",attribution:_r()}),ki(n)}catch{}}catch{}}async function $V(){if(Cn)return Cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(_o(),If)),e=tt();return await t(e.platform)}catch{return null}}function Si(){if(Cn)return Cn.getSessionDir();try{let t=tt(),e=Yi(t.platform);if(e)return Fc({configDir:Vt(...e),configDirEnv:PV(e)})}catch{}return Fc({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function PV(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Ge(){return Tr(Er(Si))}function Et(){let t=qb.getStore();if(t)return t.projectDir;let e,n,r;try{let o=tt().platform;n=o,o==="claude-code"&&(e=Vt(wi(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??Vt(wi(),".codex"))}catch{}return kC({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function RV(t){return fV(t)?t:Nt(Et(),t)}function _c(){return ys({projectDir:Et(),sessionsDir:Ge()})}function Ud(){let t=Tr(io(Si));return kp({projectDir:Et(),contentDir:t})}function Jn(){let t=Ud(),e=Ei.get(t);if(!e){e=new Rs(t),Ei.set(t,e);let n=Et();e.setDenyChecker(r=>{try{let o=xo("Read",n);return Ar(r,o,process.platform==="win32",n).denied}catch{return!0}});try{e.cleanupStaleSources(14)}catch{}if(!jC){jC=!0;try{let r=Vt(wi(),".context-mode","content");qe(r)&&vk(r,0)}catch{}jf()}}return TV(e),e}function CV(t){return t instanceof tn?{content:[{type:"text",text:gs(t)}],isError:!0}:null}async function zC(){return new Promise(t=>{let e=gV(Kc,{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function AV(){let t=Cn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g @mxalbert/context-mode"}function NV(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function DV(){return!yr||yr==="unknown"?!1:NV(yr,gr)}function MV(){if(!DV())return!1;let t=Date.now();if(Pd>=OV){if(t-LC<IV)return!1;Pd=0}return Pd===0&&(LC=t),Pd++,!0}function jV(){if(!HC){HC=!0;try{let t=Ze(),e=Nt(t,"plugins","installed_plugins.json");if(!qe(e))return;let n=JSON.parse(xc(e,"utf-8")),r=Nt(t,"plugins","cache"),o;try{o=XC(r)}catch{o=r}let s=YC();for(let[i,a]of Object.entries(n.plugins??{}))if(i===it)for(let c of a){let u=c.installPath;if(!u||qe(u)||!Nt(u).startsWith(o+pV))continue;try{JC(u).isSymbolicLink()&&ki(u)}catch{}let l=Ti(u);qe(l)||lV(l,{recursive:!0}),qe(s)&&dV(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function X(t,e){if(Rb(),jV(),MV()&&e.content.length>0){let r=AV();e.content[0].text=`\u26A0\uFE0F context-mode v${gr} outdated \u2192 v${yr} available. Upgrade: ${r}
|
|
663
663
|
|
|
664
|
-
`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,
|
|
664
|
+
`+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ie.calls[t]=(ie.calls[t]||0)+1,ie.bytesReturned[t]=(ie.bytesReturned[t]||0)+n,Md(),setImmediate(()=>uC(_c(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>oC({sessionDbPath:_c(),toolName:t,bytesReturned:n})),e}function On(t,e="unknown"){ie.bytesIndexed+=t,Md(),t>0&&setImmediate(()=>sC({sessionDbPath:_c(),source:e,bytesAvoided:t}))}function BV(t){return FV.test(t)?t:`pid-${process.ppid}`}function aO(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=BV(t),n=Tr(hs(Si));return Vt(n,`stats-${e}.json`)}function Md(){let t=Date.now();if(!(t-Ub<LV)){Ub=t;try{let e=Object.values(ie.bytesReturned).reduce((d,p)=>d+p,0),n=Object.values(ie.calls).reduce((d,p)=>d+p,0),r=ie.bytesIndexed+ie.bytesSandboxed+ie.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=Rd?.tokens??0;if(!Rd||t-Rd.computedAt>HV)try{a=(fc({sessionsDir:Ge()})?.totalEvents??0)*UV,Rd={tokens:a,computedAt:t}}catch{}let c={schemaVersion:zV,version:gr,updated_at:t,session_start:ie.sessionStart,uptime_ms:t-ie.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ie.bytesIndexed,bytes_sandboxed:ie.bytesSandboxed,cache_hits:ie.cacheHits,cache_bytes_saved:ie.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*hc()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*hc()).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=aO(),l=`${u}.tmp`;Ad(l,JSON.stringify(c)),uV(l,u)}catch{}}}function Vb(t,e){try{let n=Uf(process.env.CLAUDE_PROJECT_DIR),r=Bf(t,n);if(r.decision==="deny")return X(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function cO(t,e,n){try{let r=Ik(t,e);if(r.length===0)return null;let o=Uf(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=Bf(s,o);if(i.decision==="deny")return X(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function ZV(t,e){try{let n=Et(),r=Ff("Read","allow",n);return Ok(t,n,r).allowed?null:X(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function Fb(t,e){try{let n=Et(),r=xo("Read",n),o=Ar(t,r,process.platform==="win32",n);if(o.denied)return X(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function uO(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===WV){for(e.push(n),r++;r<t.length&&t[r]!==KV;)n++,r++;r<t.length&&r++}else n++,r++;return e}function Wb(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of uO(r))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,n)+`
|
|
665
665
|
\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>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
|
|
666
666
|
|
|
667
|
-
`)}function
|
|
667
|
+
`)}function lO(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
|
|
668
668
|
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
|
|
669
|
-
`);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=
|
|
670
|
-
> **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
|
|
671
|
-
\u2026 (truncated)`}function
|
|
669
|
+
`);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=Wb(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(`
|
|
670
|
+
> **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 GV(t){return`'${t.replace(/'/g,"'\\''")}'`}function JV(t){return`'${t.replace(/'/g,"''")}'`}function dO(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${JV(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${GV(n)} `}function pO(t){let e=t.replace(/\s+/g," ").trim();return e.length<=UC?e:e.slice(0,UC)+"\u2026"}function Fd(t){if(t!==void 0)return t;if(tt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:fO}function XV(t){return t.length<=FC?t:t.slice(0,FC)+`
|
|
671
|
+
\u2026 (truncated)`}function mO(t,e,n){let r=n?`path=${n}
|
|
672
672
|
`:"",o=`\`\`\`${t}
|
|
673
|
-
${
|
|
673
|
+
${XV(e)}
|
|
674
674
|
\`\`\``;return`${r}${o}
|
|
675
675
|
|
|
676
|
-
`}function
|
|
676
|
+
`}function BC(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=pO(e);return`# ${t}
|
|
677
677
|
|
|
678
678
|
$ ${a}
|
|
679
679
|
|
|
680
680
|
${o}
|
|
681
|
-
`}function
|
|
681
|
+
`}function ZC(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
|
|
682
682
|
`)?"":`
|
|
683
|
-
`}${n}`:n:e}async function
|
|
683
|
+
`}${n}`:n:e}async function hO(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let p=[],m=Date.now(),f=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let b=Date.now()-m,S=r-b;if(S<=0){p.push(`# ${g.label}
|
|
684
684
|
|
|
685
685
|
(skipped \u2014 batch timeout exceeded)
|
|
686
|
-
`),f=!0;continue}y=S}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(p.push(
|
|
686
|
+
`),f=!0;continue}y=S}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(p.push(BC(g.label,g.command,ZC(_),a)),_.timedOut){f=!0;for(let b=h+1;b<t.length;b++)p.push(`# ${t[b].label}
|
|
687
687
|
|
|
688
688
|
(skipped \u2014 batch timeout exceeded)
|
|
689
|
-
`);break}}return{outputs:p,timedOut:f}}let c=t.map(p=>({run:async()=>{let m=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),f=
|
|
689
|
+
`);break}}return{outputs:p,timedOut:f}}let c=t.map(p=>({run:async()=>{let m=await n.execute({language:"shell",code:`${s}${p.command}`,timeout:r,cwd:i}),f=BC(p.label,p.command,ZC(m),a);return{output:m.timedOut?f.replace(/\n$/,"")+`
|
|
690
690
|
(timed out after ${r??"?"}ms)
|
|
691
|
-
`:f,timedOut:!!m.timedOut}}})),{settled:u}=await
|
|
691
|
+
`:f,timedOut:!!m.timedOut}}})),{settled:u}=await xb(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let p=0;p<u.length;p++){let m=u[p];if(m.status==="fulfilled")l[p]=m.value.output,m.value.timedOut&&(d=!0);else{let f=m.reason instanceof Error?m.reason.message:String(m.reason);l[p]=`# ${t[p].label}
|
|
692
692
|
|
|
693
693
|
(executor error: ${f})
|
|
694
|
-
`}}return{outputs:l,timedOut:d}}function
|
|
694
|
+
`}}return{outputs:l,timedOut:d}}function gO(t,e){let n=Jn();On(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:_r()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
|
|
695
695
|
Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}function vi(t,e,n,r=5){let o=t.split(`
|
|
696
696
|
`).length,s=Buffer.byteLength(t),i=Jn(),a=i.indexPlainText(t,n,void 0,_r()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" 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(`
|
|
697
697
|
`)}let l=[`Indexed ${a.totalChunks} sections from "${n}" 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(`
|
|
698
698
|
`)[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(`
|
|
699
|
-
`)}function
|
|
700
|
-
var classifyIp = ${i};`,c=
|
|
699
|
+
`)}function Kb(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}function e9(){try{return _r()?.sessionId??"__default__"}catch{return"__default__"}}function Gb(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function Jb(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function t9(t){let e=Gb(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}function n9(){return Db||(Db=WC(import.meta.url).resolve("turndown")),Db}function r9(){return Mb||(Mb=WC(import.meta.url).resolve("turndown-plugin-gfm")),Mb}function yO(t,e){let n=JSON.stringify(n9()),r=JSON.stringify(r9()),o=JSON.stringify(e),s=bc.toString(),i=bc.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
|
|
700
|
+
var classifyIp = ${i};`,c=zd.toString(),u=zd.name||"classifyExtraction",l=u==="classifyExtraction"?`var classifyExtraction = ${c};`:`var ${u} = ${c};
|
|
701
701
|
var classifyExtraction = ${u};`,d=process.env.CTX_FETCH_STRICT==="1";return`
|
|
702
702
|
const TurndownService = require(${n});
|
|
703
703
|
const { gfm } = require(${r});
|
|
@@ -1161,15 +1161,15 @@ async function main() {
|
|
|
1161
1161
|
emit('text', text, Buffer.byteLength(text, 'utf-8'), 'text', '1-text-passthrough', []);
|
|
1162
1162
|
}
|
|
1163
1163
|
main();
|
|
1164
|
-
`}function
|
|
1165
|
-
`),u=(c[0]||"").trim(),l=Number.parseInt((c[1]||"").trim(),10),d=
|
|
1164
|
+
`}function s9(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}function zd(t,e){if(!Number.isFinite(e)||e<=0)return{kind:"ok"};if(!Number.isFinite(t)||t>=200)return{kind:"ok"};let o=t/e;return o>=.02?{kind:"ok"}:{kind:"shell",textBytes:t,sourceBytes:e,yieldPct:(o*100).toFixed(2)}}async function i9(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 n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=bc(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"&&n)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(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),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 bc(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?bc(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.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 a9(t,e,n,r){let o=await i9(t);if(o)return o;if(!n&&r!==0){let i=Jn(),a=Sb(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??o9;if(l<d){let p=Math.floor(l/36e5),m=Math.floor(l/(60*1e3)),f=p>0?`${p}h ago`:m>0?`${m}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:f,ttlStr:s9(d)}}}}let s=Vt(Zb(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=yO(t,s),a=await Sc.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let g=a.stderr||a.stdout||"unknown error",_=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(g)?" \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:`${g}${_}`,reason:"exit"}}let c=(a.stdout||"").trim().split(`
|
|
1165
|
+
`),u=(c[0]||"").trim(),l=Number.parseInt((c[1]||"").trim(),10),d=c9((c[2]||"").trim()),p=(c[3]||"").trim()||"unreported",m=_O(c[4]||""),f;try{let y=GC(s).size;if(y>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${y} bytes exceeds cap 52428800`,reason:"read"};f=xc(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}if(f.length===0)return{kind:"fetch_error",url:t,error:"empty content",reason:"empty"};let h=zd(f.length,l);if(h.kind==="shell"){let g=m.length>0?` The ladder was climbed first and every rung came back empty: ${m.join(", ")}.`:"";return{kind:"fetch_error",url:t,error:`extracted only ${h.textBytes} bytes of text from ${h.sourceBytes} bytes received (${h.yieldPct}% yield) \u2014 the response was a shell whose content is rendered client-side by JavaScript, so an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered).${g} Retrying this URL returns the same shell. Fetch this page's source instead: its repository README or raw doc file on GitHub, its OpenAPI or JSON schema endpoint, or a sibling page of the same host that is server-rendered.`,reason:"shell"}}return{kind:"fetched",url:t,source:e,markdown:f,header:u,route:d,rung:p}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{KC(s)}catch{}}}function c9(t){return t==="markdown"?"markdown":t==="json"?"json":t==="text"?"text":"html"}function _O(t){let e=t.trim();if(e.length===0)return[];let n;try{n=JSON.parse(e)}catch{return[]}if(!Array.isArray(n))return[];let r=[];for(let o of n)typeof o=="string"&&o.length>0&&r.push(o);return r}function gc(t){return t==="1-accept-markdown"?"rung 1 \u2014 the site served markdown to the Accept header on the request we were already making":t==="1-html-converted"?"rung 1 \u2014 the site served HTML and it converted to an article":t==="1-json-passthrough"?"rung 1 \u2014 JSON response, indexed as-is":t==="1-text-passthrough"?"rung 1 \u2014 plain-text response, indexed as-is":t==="2a-md-sibling"?"rung 2a \u2014 rung 1 returned a JavaScript shell, and the page's .md sibling carried the article":t==="2b-llms-txt"?"rung 2b \u2014 rung 1 returned a JavaScript shell, and this host's llms.txt named the article elsewhere":t==="ladder-exhausted"?"ladder exhausted \u2014 every rung came back empty":t==="unreported"?"rung not reported (older fetch bundle)":`rung ${t}`}function u9(){return jb||(jb=new md(Vt(Ti(Ud()),"fetch-pages.db"))),jb}function l9(t){let e=Jn(),n=Sb(t.source,t.url),r=_r(),o=t.route??"html",s=t.rung??"unreported",i=t.markdown,a,c=[];if(!qR(o))try{let d=VR({url:t.url,sourceLabel:n,document:t.markdown,route:o,store:u9()});if(d.kind==="refuse")return{label:n,totalChunks:0,totalBytes:d.storedBytes,preview:"",refusal:`${gc(s)}; ${d.reason}`};i=d.indexText,c=d.relabelled,o==="markdown"?a=`${gc(s)}; site-authored markdown (${d.storedBytes} B) \u2014 no extraction needed`:d.provisional?a=`${gc(s)}; rung 4 (block classification) \u2014 first page seen from this host, so all ${d.totalBlocks} blocks were indexed as content (PROVISIONAL); they are re-classified automatically when a second page of this host is fetched`:a=`${gc(s)}; rung 4 (block classification) \u2014 ${d.totalBlocks-d.templateBlocks}/${d.totalBlocks} blocks indexed as content (${d.contentBytes} B); ${d.templateBlocks} blocks (${d.templateBytes} B) were seen on other pages of this host, so they are labelled template \u2014 stored whole, kept out of the index`}catch(d){a=`extraction unavailable (${d instanceof Error?d.message:String(d)}) \u2014 indexed the full document`,i=t.markdown}let u;t.header==="__CM_CT__:json"?u=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?u=e.indexPlainText(t.markdown,n,void 0,r):u=e.index({content:i,source:n,attribution:r});for(let d of c)try{e.index({content:d.indexText,source:d.sourceLabel,attribution:r})}catch{}c.length>0&&(a=(a?a+"; ":"")+`re-classified ${c.length} earlier page(s) of this host now that a second page exists`),On(Buffer.byteLength(t.markdown));let l=i.length>qC?eC(i,qC)+`
|
|
1166
1166
|
|
|
1167
|
-
\u2026[preview window only \u2014 the full document is stored; use ctx_search() to retrieve any section]`:i;return{label:u.label,totalChunks:u.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:l,extraction:a}}function
|
|
1168
|
-
${
|
|
1169
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var
|
|
1170
|
-
`)}),process.on("uncaughtException",t=>{try{
|
|
1171
|
-
`)}finally{process.exit(1)}}));ss=
|
|
1172
|
-
`);process.on("exit",()=>{try{ki(
|
|
1167
|
+
\u2026[preview window only \u2014 the full document is stored; use ctx_search() to retrieve any section]`:i;return{label:u.label,totalChunks:u.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:l,extraction:a}}function Lb(t,e){if(!qe(e))return;let n=0;try{for(let r of aV(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(xc(Vt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function VC(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function bO(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 xO(t,e=process.platform,n=Nd){let r=bO(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:yc});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 SO(t,e=process.platform,n=Nd){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:yc});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;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],m=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(p!=="0.0.0.0:0"&&p!=="[::]:0"||/^\d+$/.test(m)&&i.add(m))}for(let a of i){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:yc});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:yc});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:yc});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}async function d9(){let t=jf();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Zb():"/tmp",n=Vt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{Sc.cleanupBackgrounded();for(let a of Ei.values())try{a.close()}catch{}Ei.clear();try{ki(Hd)}catch{}try{ki(n)}catch{}r&&clearInterval(r)},s=async()=>{try{Ub=0,Md()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),YR({onShutdown:()=>s()});let i=new pd;await Ce.connect(i),XR(i);try{Ad(n,String(process.pid))}catch{}r=setInterval(()=>{try{Ad(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(_o(),If)),u=Ce.server.getClientVersion(),l=a(u??void 0);Cn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=lC(_c());if(a){for(let[c,u]of Object.entries(a.calls))ie.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ie.bytesReturned[c]=u;a.sessionStart>0&&(ie.sessionStart=a.sessionStart)}}catch{}zC().then(a=>{a!=="unknown"&&(yr=a)}),setInterval(()=>{zC().then(a=>{a!=="unknown"&&(yr=a)})},3600*1e3).unref(),setInterval(()=>Md(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${gr} running on stdio`),console.error(`Detected runtimes:
|
|
1168
|
+
${Ni(ss)}`),Sr()||(console.error(`
|
|
1169
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Cd,gr,ss,Od,Ce,eO,nO,Hb,kV,qb,Sc,Hd,Ei,jC,$d,Cn,ie,yr,Pd,LC,OV,IV,HC,LV,zV,HV,UV,Ub,Rd,FV,qV,VV,WV,KV,UC,fO,FC,jd,Ld,YV,Bb,Id,QV,Db,Mb,o9,qC,jb,yc,zb,kO=x(()=>{"use strict";vR();TR();ud();bb();zR();Lf();HR();vb();WR();Zf();as();KR();QR();tC();rn();rC();Zi();aC();dC();yC();xC();SC();Nn();_o();Wp();_p();Vi();Pr();wC();er();MC();Vo();Cd=Ti(mV(import.meta.url)),gr=(()=>{for(let t of["../package.json","./package.json"]){let e=Nt(Cd,t);if(qe(e))try{return JSON.parse(xc(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}
|
|
1170
|
+
`)}),process.on("uncaughtException",t=>{try{cV(2,`[context-mode] uncaughtException: ${t?.message??t}
|
|
1171
|
+
`)}finally{process.exit(1)}}));ss=oo(),Od=Di(ss),Ce=new ld({name:"context-mode",version:gr}),eO=[];nO=tO(),Hb=!1;kV=Ce.registerTool.bind(Ce);Ce.registerTool=(...t)=>{let[e,n,r]=t;if(nO){rO();return}let o=wV(e,r);return eO.push({name:e,config:n,handler:o}),t[2]=o,kV(...t)};nO&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&oO(Ce);qb=new yV;Ce.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ce.server.setRequestHandler(Js,async()=>({prompts:[]}));Ce.server.setRequestHandler(Ks,async()=>({resources:[]}));Ce.server.setRequestHandler(Gs,async()=>({resourceTemplates:[]}));Sc=new gi({runtimes:ss,projectRoot:()=>Et()}),Hd=Vt(Zb(),`cm-fs-preload-${process.pid}.js`);Ad(Hd,`(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){}})();
|
|
1172
|
+
`);process.on("exit",()=>{try{ki(Hd)}catch{}});Ei=new Map,jC=!1;Cn=null;ie={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};yr=null,Pd=0,LC=0,OV=3,IV=3600*1e3;HC=!1;LV=500,zV=2,HV=3e4,UV=256,Ub=0,FV=/^[A-Za-z0-9._-]+$/;qV=Od.join(", "),VV=Sr()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",WV="",KV="";UC=500;fO=12e4;FC=2e3;Ce.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${VV} Languages: ${qV}.
|
|
1173
1173
|
|
|
1174
1174
|
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.
|
|
1175
1175
|
|
|
@@ -1200,9 +1200,9 @@ RETURNS:
|
|
|
1200
1200
|
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.
|
|
1201
1201
|
|
|
1202
1202
|
EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))")
|
|
1203
|
-
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:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.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:j.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:j.preprocess(
|
|
1203
|
+
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:j.object({language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.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:j.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:j.preprocess(Jb,j.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."),cwd:j.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),intent:j.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'.
|
|
1204
1204
|
|
|
1205
|
-
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=
|
|
1205
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=Vb(e,"execute");if(i)return i}else{let i=cO(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
|
|
1206
1206
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
1207
1207
|
let __cm_fs=0;
|
|
1208
1208
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -1261,14 +1261,14 @@ ${e}
|
|
|
1261
1261
|
}
|
|
1262
1262
|
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
|
|
1263
1263
|
setInterval(()=>{},2147483647);`:""}
|
|
1264
|
-
})(typeof require!=='undefined'?require:null);`);let a=
|
|
1264
|
+
})(typeof require!=='undefined'?require:null);`);let a=Fd(n),c=await Sc.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=mO(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ie.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ie.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let m=c.stdout?.trim();return c.backgrounded&&m?X("ctx_execute",{content:[{type:"text",text:`${u}${m}
|
|
1265
1265
|
|
|
1266
1266
|
_(process backgrounded after ${a}ms \u2014 still running)_`}]}):m?X("ctx_execute",{content:[{type:"text",text:`${u}${m}
|
|
1267
1267
|
|
|
1268
1268
|
_(timed out after ${a}ms \u2014 partial output shown above)_`}]}):X("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
|
|
1269
1269
|
|
|
1270
1270
|
stderr:
|
|
1271
|
-
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:f}=
|
|
1271
|
+
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:f}=Pb({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(f)>jd?(On(Buffer.byteLength(f)),X("ctx_execute",{content:[{type:"text",text:`${u}${vi(f,s,m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):Buffer.byteLength(f)>Ld?(On(Buffer.byteLength(f)),X("ctx_execute",{content:[{type:"text",text:`${u}${vi(f,"errors failures exceptions",m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):X("ctx_execute",{content:[{type:"text",text:`${u}${f}`}],isError:m})}let p=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(p)>jd)return On(Buffer.byteLength(p)),X("ctx_execute",{content:[{type:"text",text:`${u}${vi(p,s,`execute:${t}`)}`}]});if(Buffer.byteLength(p)>Ld){let m=gO(p,`execute:${t}`),f={...m,content:m.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return X("ctx_execute",f)}return X("ctx_execute",{content:[{type:"text",text:`${u}${p}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});jd=5e3,Ld=102400;Ce.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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.
|
|
1272
1272
|
|
|
1273
1273
|
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.
|
|
1274
1274
|
|
|
@@ -1287,7 +1287,7 @@ RETURNS:
|
|
|
1287
1287
|
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.
|
|
1288
1288
|
|
|
1289
1289
|
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'))")
|
|
1290
|
-
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:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.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:j.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:n,timeout:r,intent:o})=>{let s=
|
|
1290
|
+
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:j.object({path:j.string().describe("Absolute file path or relative to project root"),language:j.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:j.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:j.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:j.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:n,timeout:r,intent:o})=>{let s=ZV(t,"ctx_execute_file");if(s)return s;let i=Fb(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=Vb(n,"execute_file");if(a)return a}else{let a=cO(n,e,"execute_file");if(a)return a}try{let a=Fd(r),c=await Sc.executeFile({path:t,language:e,code:n,timeout:a}),u=mO(e,n,t);if(c.timedOut)return X("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:p}=Pb({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(p)>jd?(On(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${vi(p,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(p)>Ld?(On(Buffer.byteLength(p)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${vi(p,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):X("ctx_execute_file",{content:[{type:"text",text:`${u}${p}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>jd)return On(Buffer.byteLength(l)),X("ctx_execute_file",{content:[{type:"text",text:`${u}${vi(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Ld){let d=gO(l,`file:${t}`),p={...d,content:d.content.map((m,f)=>f===0&&m.type==="text"?{...m,text:`${u}${m.text}`}:m)};return X("ctx_execute_file",p)}return X("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return X("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Ce.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},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.
|
|
1291
1291
|
|
|
1292
1292
|
WHEN:
|
|
1293
1293
|
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
@@ -1305,22 +1305,22 @@ RETURNS:
|
|
|
1305
1305
|
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.
|
|
1306
1306
|
|
|
1307
1307
|
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
1308
|
-
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:j.object({content:j.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:j.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:j.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:j.array(j.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:j.array(j.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:j.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:j.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:j.array(j.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:j.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:j.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return X("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=
|
|
1308
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:j.object({content:j.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:j.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:j.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:j.array(j.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:j.array(j.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:j.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:j.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:j.array(j.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:j.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:j.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return X("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=Fb(e,"ctx_index");if(l)return l}try{let l=e?RV(e):void 0;if(l&&qe(l)&&JC(l).isSymbolicLink()){let f;try{f=XC(l)}catch{return X("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(f!==l){let h=Fb(f,"ctx_index");if(h)return h}}if(l&&qe(l)&&GC(l).isDirectory()){let m=Jn(),f=Et(),h=xo("Read",f),g=process.platform==="win32",y=D=>{try{return Ar(D,h,g,f).denied}catch{return!1}},_=m.indexDirectory({path:l,source:n??l,attribution:_r(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),b=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",S=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",T=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return X("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${b}${S}${T}
|
|
1309
1309
|
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)On(Buffer.byteLength(t));else if(l)try{let m=await import("fs");On(m.readFileSync(l).byteLength)}catch{}let p=Jn().index({content:t,path:l,source:n??l,attribution:_r()});return X("ctx_index",{content:[{type:"text",text:`Indexed ${p.totalChunks} sections (${p.codeChunks} with code) from: ${p.label}
|
|
1310
|
-
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 X("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});
|
|
1310
|
+
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 X("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});YV=Kb("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),Bb=Kb("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),Id=Kb("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),QV=new _d({windowMs:YV,softCapAfter:Bb,blockAfter:Id});Ce.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:_C(Nb)},async t=>{try{let e=Jn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return X("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
1311
1311
|
|
|
1312
1312
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
1313
1313
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
1314
1314
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
1315
1315
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
1316
1316
|
|
|
1317
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return X("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=
|
|
1317
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return X("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=bC(c,Nb,()=>Et()),l=Date.now(),d=QV.record(e9(),l),p=d.count;if(d.blocked)return X("ctx_search",{content:[{type:"text",text:`BLOCKED: ${p} search calls in ${Math.round((l-d.windowStart)/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 m=d.softCapped?1:Math.min(s,2),f=40*1024,h=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let $=Ge(),P=Et(),A=ys({projectDir:P,sessionsDir:$});qe(A)&&(y=new nn({dbPath:A}))}catch{}let b;if(typeof u=="string"&&y)try{b=new Set(y.getSessionIdsForProject(u))}catch{}let S=Cn?.getConfigDir()??Ze();try{for(let $ of o){if(h>f){g.push(`## ${$}
|
|
1318
1318
|
(output cap reached)
|
|
1319
|
-
`);continue}let P;if(n==="timeline"?P=
|
|
1320
|
-
No results found.`);continue}let A=P.map((R,C)=>{let z=R.origin||"current-session",B=R.timestamp?R.timestamp.slice(0,16).replace("T"," "):"",ge=`--- [${z}${B?" | "+B:""} | ${R.source}] ---`,Le=`### ${R.title}`,
|
|
1319
|
+
`);continue}let P;if(n==="timeline"?P=gC({query:$,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Et(),configDir:S,adapter:Cn??void 0,projectScope:u}):P=e.searchWithFallback($,m,i,a,"like",b),P.length===0){g.push(`## ${$}
|
|
1320
|
+
No results found.`);continue}let A=P.map((R,C)=>{let z=R.origin||"current-session",B=R.timestamp?R.timestamp.slice(0,16).replace("T"," "):"",ge=`--- [${z}${B?" | "+B:""} | ${R.source}] ---`,Le=`### ${R.title}`,ut=Wb(R.content,$,1500,R.highlighted);return`${ge}
|
|
1321
1321
|
${Le}
|
|
1322
1322
|
|
|
1323
|
-
${
|
|
1323
|
+
${ut}`}).join(`
|
|
1324
1324
|
|
|
1325
1325
|
`);g.push(`## ${$}
|
|
1326
1326
|
|
|
@@ -1330,12 +1330,12 @@ ${A}`),h+=A.length}}finally{try{y?.close()}catch{}}let T=g.join(`
|
|
|
1330
1330
|
|
|
1331
1331
|
`);e.lastRefreshCount>0&&(T=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
1332
1332
|
|
|
1333
|
-
`+T);let D=Math.max(0,
|
|
1333
|
+
`+T);let D=Math.max(0,Id-p),v=Math.max(0,Bb-p);if(p>=Bb?T+=`
|
|
1334
1334
|
|
|
1335
|
-
\u26A0 search call #${p}/${
|
|
1335
|
+
\u26A0 search call #${p}/${Id} in this window. Results limited to ${m}/query. ${D} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:T+=`
|
|
1336
1336
|
|
|
1337
|
-
> Throttle: call #${p}/${
|
|
1338
|
-
Indexed sources: ${$.map(A=>`"${A.label}" (${A.chunkCount} sections)`).join(", ")}`:"";return X("ctx_search",{content:[{type:"text",text:`No results found.${P}`}]})}return X("ctx_search",{content:[{type:"text",text:T}]})}catch(e){let n=e instanceof Error?e.message:String(e);return X("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});
|
|
1337
|
+
> Throttle: call #${p}/${Id} in this window. ${v} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,T.trim().length===0){let $=e.listSources(),P=$.length>0?`
|
|
1338
|
+
Indexed sources: ${$.map(A=>`"${A.label}" (${A.chunkCount} sections)`).join(", ")}`:"";return X("ctx_search",{content:[{type:"text",text:`No results found.${P}`}]})}return X("ctx_search",{content:[{type:"text",text:T}]})}catch(e){let n=e instanceof Error?e.message:String(e);return X("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});Db=null,Mb=null;o9=1440*60*1e3,qC=3072;jb=null;Ce.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},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.
|
|
1339
1339
|
|
|
1340
1340
|
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.
|
|
1341
1341
|
|
|
@@ -1357,14 +1357,14 @@ RETURNS:
|
|
|
1357
1357
|
EXAMPLE: ctx_fetch_and_index(
|
|
1358
1358
|
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1359
1359
|
concurrency: 5
|
|
1360
|
-
)`,inputSchema:j.object({url:j.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:j.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:j.preprocess(
|
|
1360
|
+
)`,inputSchema:j.object({url:j.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:j.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:j.preprocess(Gb,j.array(j.object({url:j.string().describe("URL to fetch"),source:j.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:j.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:j.preprocess(Jb,j.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:j.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:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return X("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=!n&&i.length===1,c=r??1,u=i.map(R=>({run:()=>a9(R.url,R.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:p}=await xb(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let R=0;R<l.length;R++){let C=l[R];if(C.status==="rejected"){let B=C.reason instanceof Error?C.reason.message:String(C.reason);m.push({kind:"job_error",url:i[R].url,error:B});continue}let z=C.value;if(z.kind==="cached"){ie.cacheHits++,ie.cacheBytesSaved+=z.estimatedBytes;let B=z.estimatedBytes,ge=z.label;setImmediate(()=>iC({sessionDbPath:_c(),source:ge,bytesAvoided:B})),m.push({kind:"cached",label:z.label,chunkCount:z.chunkCount,ageStr:z.ageStr,ttlStr:z.ttlStr})}else if(z.kind==="fetch_error")m.push({kind:"fetch_error",url:z.url,error:z.error,reason:z.reason});else{ie.cacheMisses++;let B=l9(z);B.refusal?m.push({kind:"fetch_error",url:z.url,error:B.refusal,reason:"shell"}):m.push({kind:"fetched",indexed:B})}}if(a){let R=m[0];if(R.kind==="cached")return X("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: ${R.ttlStr}).
|
|
1361
1361
|
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
1362
1362
|
|
|
1363
1363
|
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1364
1364
|
Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let C=(R.indexed.totalBytes/1024).toFixed(1),z=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${C}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,...R.indexed.extraction?[R.indexed.extraction]:[],"","---","",R.indexed.preview].join(`
|
|
1365
1365
|
`);return X("ctx_fetch_and_index",{content:[{type:"text",text:z}]})}if(R.kind==="fetch_error"){let C=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="shell"?`Fetched ${R.url} but ${R.error}`: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 X("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return X("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let f=384,h=[],g=0,y=0,_=0,b=0,S=0,T=[];for(let R of m)if(R.kind==="cached")_++,h.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr}, TTL: ${R.ttlStr})`);else if(R.kind==="fetched"){b++,g+=R.indexed.totalChunks,y+=R.indexed.totalBytes;let C=(R.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${C}KB)`);let z=R.indexed.preview.length>f?R.indexed.preview.slice(0,f).trimEnd()+"\u2026":R.indexed.preview;T.push(`### ${R.indexed.label}
|
|
1366
1366
|
|
|
1367
|
-
${z}`)}else S++,h.push(`- [err] ${R.url}: ${R.error}`);let D=(y/1024).toFixed(1),v=p?` cap=${d}/${
|
|
1367
|
+
${z}`)}else S++,h.push(`- [err] ${R.url}: ${R.error}`);let D=(y/1024).toFixed(1),v=p?` cap=${d}/${hV().length}cpu`:"",$=(R,C,z)=>`${R} ${R===1?C:z}`,A=[`fetched ${i.length} c=${d}${v}. ok=${b} cache=${_} err=${S}. ${$(g,"section","sections")} ${D}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...T.length>0?["","---","",...T]:[]].join(`
|
|
1368
1368
|
`);return X("ctx_fetch_and_index",{content:[{type:"text",text:A}],isError:S===i.length})});Ce.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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.
|
|
1369
1369
|
|
|
1370
1370
|
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).
|
|
@@ -1390,13 +1390,13 @@ EXAMPLE: ctx_batch_execute(
|
|
|
1390
1390
|
],
|
|
1391
1391
|
queries: ["root cause", "proposed fix"],
|
|
1392
1392
|
concurrency: 2
|
|
1393
|
-
)`,inputSchema:j.object({commands:j.preprocess(
|
|
1393
|
+
)`,inputSchema:j.object({commands:j.preprocess(t9,j.array(j.object({label:j.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:j.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:j.preprocess(Gb,j.array(j.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:j.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:j.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."),cwd:j.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:j.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:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=Vb(i.command,"batch_execute");if(a)return a}try{let i=dO(ss.shell,Hd),a=Fd(n),{outputs:c,timedOut:u}=await hO(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:v=>{ie.bytesSandboxed+=v}},Sc),l=c.join(`
|
|
1394
1394
|
`),d=Buffer.byteLength(l),p=l.split(`
|
|
1395
|
-
`).length;if(u&&c.length===0)return X("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});On(d);let m=Jn(),f=`batch:${t.map(v=>v.label).join(",").slice(0,80)}`,h=m.index({content:l,source:f,attribution:_r()}),g=["## Commands",""];for(let v of t)g.push(`- ${v.label}: \`${
|
|
1395
|
+
`).length;if(u&&c.length===0)return X("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});On(d);let m=Jn(),f=`batch:${t.map(v=>v.label).join(",").slice(0,80)}`,h=m.index({content:l,source:f,attribution:_r()}),g=["## Commands",""];for(let v of t)g.push(`- ${v.label}: \`${pO(v.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],b=[];for(let v of y){let $=Buffer.byteLength(v.content);_.push(`- ${v.title} (${($/1024).toFixed(1)}KB)`),b.push(v.title)}let S=lO(m,e,f,void 0,s),T=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],D=[`Executed ${t.length} commands (${p} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...S,T.length>0?`
|
|
1396
1396
|
Searchable terms for follow-up: ${T.join(", ")}`:""].join(`
|
|
1397
|
-
`);return X("ctx_batch_execute",{content:[{type:"text",text:D}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});Ce.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:j.object({})},async()=>{let t;try{let e=
|
|
1398
|
-
`)}]})});Ce.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:j.object({})},async()=>{let t="",e,n;try{let c=Ce.server.getClientVersion(),u=
|
|
1399
|
-
`),l=
|
|
1397
|
+
`);return X("ctx_batch_execute",{content:[{type:"text",text:D}]})}catch(i){let a=i instanceof Error?i.message:String(i);return X("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});Ce.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:j.object({})},async()=>{let t;try{let e=Et(),n=st(e),r=ys({projectDir:e,sessionsDir:Ge()});if(qe(r)){let o=Xe(),s=new o(r,{readonly:!0});try{let i=new xi(s),a=i.queryAll(ie),c=i.getMcpToolUsage(),u=fc({sessionsDir:Ge()}),l;try{l=Ed()}catch{}let d,p;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){d=AC({sessionId:f,sessionsDir:Ge(),worktreeHash:n});let h=Ud(),g;try{let S=Xe(),T=(await import("node:fs")).readdirSync(Ge()).filter(v=>v.endsWith(".db")&&(!n||v.startsWith(n))),D;for(let v of T)try{let $=new S((await import("node:path")).join(Ge(),v),{readonly:!0});try{let P=$.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(f);if(P?.project_dir){D=P.project_dir;break}}finally{$.close()}}catch{}g=D?mc({projectDir:D,sessionsDir:Ge(),worktreeHash:n,contentDbPath:h}):mc({sessionId:f,sessionsDir:Ge(),worktreeHash:n,contentDbPath:h})}catch{g=mc({sessionId:f,sessionsDir:Ge(),worktreeHash:n,contentDbPath:h})}let y=mc({sessionsDir:Ge()}),_=NC(h),b={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};p={conversation:g,lifetime:b}}}catch{}Cn?.name==="Pi"&&Lb(u,Ge());let m;try{m=Jn().getIndexState()}catch{}t=Td(a,gr,yr,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:p,indexState:m,cwd:e})}finally{s.close()}}else{let s=new xi(VC()).queryAll(ie),i=fc({sessionsDir:Ge()});Cn?.name==="Pi"&&Lb(i,Ge());let a;try{a=Ed()}catch{}let c;try{c=Jn().getIndexState()}catch{}t=Td(s,gr,yr,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new xi(VC()).queryAll(ie),r;try{r=fc({sessionsDir:Ge()})}catch{}Cn?.name==="Pi"&&r&&Lb(r,Ge());let o;try{o=Ed()}catch{}t=Td(n,gr,yr,r||o?{lifetime:r,multiAdapter:o}:void 0)}return X("ctx_stats",{content:[{type:"text",text:t}]})});Ce.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:j.object({})},async()=>{let t=["context-mode doctor",""],e;try{e=tt(Ce.server.getClientVersion()??void 0).platform}catch{e=tt().platform}let n=QC(e),r=11,o=(Od.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Od.length}/${r} (${o}%) \u2014 ${Od.join(", ")}`),Sr()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=Er(Si),i=io(Si),a=hs(Si);t.push(`[OK] Storage sessions: ${s.path} (${Hi(s)})`),t.push(`[OK] Storage content: ${i.path} (${Hi(i)})`),t.push(`[OK] Storage stats: ${a.path} (${Hi(a)})`);{let u=new gi({runtimes:ss});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=Xe();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await $V();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",p=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${p}`)}let u=Nc(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=Nt(n,l);qe(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${gr}`),X("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1398
|
+
`)}]})});Ce.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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:j.object({})},async()=>{let t="",e,n;try{let c=Ce.server.getClientVersion(),u=tt(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=ro(u.platform)&&ss.javascript?{platform:u.platform,jsRuntime:ss.javascript}:void 0}catch{try{n=tt().platform}catch{}}let r=QC(n),o=Nt(r,"cli.bundle.mjs"),s=Nt(r,"build","cli.js");try{let c=Ge(),u=Vt(Ti(c),"insight-cache");qe(u)&&(SO(4747),KC(u,{recursive:!0,force:!0}))}catch{}let i;if(qe(o))i=`${Ii(o,e)} upgrade${t}`;else if(qe(s))i=`${Ii(s,e)} upgrade${t}`;else{let u=['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(r)};`,'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/mxalbert1996/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(`
|
|
1399
|
+
`),l=Nt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=Ii(l,e)}let a=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",i,"```","","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(`
|
|
1400
1400
|
`);return X("ctx_upgrade",{content:[{type:"text",text:a}]})});Ce.registerTool("ctx_purge",{title:"Purge Knowledge Base",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
|
|
1401
1401
|
|
|
1402
1402
|
WHEN:
|
|
@@ -1421,59 +1421,59 @@ RETURNS:
|
|
|
1421
1421
|
A summary of removed rows + the resolved scope.
|
|
1422
1422
|
|
|
1423
1423
|
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1424
|
-
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:j.object({confirm:j.preprocess(
|
|
1425
|
-
Open Insight manually: ${
|
|
1426
|
-
`,"utf-8")}catch{return"noop"}return"healed"}function
|
|
1427
|
-
${e}`,"utf-8"),(
|
|
1428
|
-
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(r+=p,l)l=!1;else if(l=p>="\uD800"&&p<="\uDBFF",l)continue;if(p===
|
|
1429
|
-
`){s&&(r+=
|
|
1430
|
-
`&&(o&&
|
|
1431
|
-
`)}var
|
|
1424
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:j.object({confirm:j.preprocess(Jb,j.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:j.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:j.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:n})=>{if(e&&n==="project")return X("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 X("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!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=Ud()}catch{}if(o){let c=Ei.get(o);if(c){try{c.cleanup()}catch{}Ei.delete(o)}}let s=o?Ti(o):void 0,{deleted:i}=nC({projectDir:Et(),sessionsDir:Ge(),storePath:o,contentDir:s,legacyContentDir:Vt(wi(),".context-mode","content"),contentHash:jn(Et()),scope:r,sessionId:e});if(r==="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=aO();qe(c)&&ki(c)}catch{}}let a=r==="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 X("ctx_purge",{content:[{type:"text",text:a}]})});yc=5e3;zb="https://context-mode.com/insight";Ce.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:j.object({})},async()=>{let t=xO(zb),e=t.ok?`Opening Insight in your browser: ${zb}`:`Could not auto-open your browser (${t.reason}).
|
|
1425
|
+
Open Insight manually: ${zb}`;return X("ctx_insight",{content:[{type:"text",text:e}]})});sO();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&d9().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var OO={};_e(OO,{needsHookNormalization:()=>kc,normalizeHooksJson:()=>PO,normalizeHooksJsonOnly:()=>CO,normalizeHooksOnStartup:()=>p9,normalizePluginJson:()=>RO});import{existsSync as wO,readFileSync as EO,writeFileSync as TO}from"node:fs";import{resolve as $O}from"node:path";function to(t){return String(t).replace(/\\/g,"/")}function Xb(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(to(t));return e?e[1]:null}function Yb(t,e){if(!e||!t||typeof t!="string")return!1;let n=to(t);Bd.lastIndex=0;let r;for(;(r=Bd.exec(n))!==null;)if(r[1]!==e)return!0;return!1}function kc(t,e){return!t||typeof t!="string"?!1:t.includes(vc)?!0:Yb(t,Xb(e))}function PO(t,e,n){if(!kc(t,n))return t;let r=to(e),o=to(n),s=Xb(n),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 m of p){if(typeof m?.command!="string")continue;let f=m.command.includes(vc),h=Yb(m.command,s);if(!f&&!h)continue;let g=m.command;f&&(g=g.replaceAll(vc,o),g=g.replace(/^\s*node\s+/,`"${r}" `)),h&&(g=to(g).replace(Bd,`context-mode/context-mode/${s}`)),m.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function RO(t,e,n){if(!kc(t,n))return t;let r=to(e),o=to(n),s=Xb(n),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(m=>{if(typeof m!="string")return m;let f=m;return f.includes(vc)&&(f=f.replaceAll(vc,o)),Yb(f,s)&&(f=to(f).replace(Bd,`context-mode/context-mode/${s}`)),f});p.some((m,f)=>m!==d[f])&&(l.args=p,c=!0)}l.command==="node"&&c&&(l.command=r)}}return c?JSON.stringify(i,null,2):t}function CO({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){let o=n||e;if(!(r!=="win32"&&r!=="linux"&&!(n&&n!==e))&&!(!t||!o))try{let a=$O(t,"hooks","hooks.json");if(wO(a)){let c=EO(a,"utf-8");if(kc(c,t)){let u=PO(c,o,t);u!==c&&TO(a,u,"utf-8")}}}catch{}}function p9({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}){if(CO({pluginRoot:t,nodePath:e,jsRuntimePath:n,platform:r}),!(r!=="win32"&&r!=="linux")&&!(!t||!e))try{let o=$O(t,".claude-plugin","plugin.json");if(wO(o)){let s=EO(o,"utf-8");if(kc(s,t)){let i=RO(s,e,t);i!==s&&TO(o,i,"utf-8")}}}catch{}}var vc,Bd,IO=x(()=>{"use strict";vc="${CLAUDE_PLUGIN_ROOT}",Bd=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});var HO={};_e(HO,{buildHookCommand:()=>jO,ensureShebangAndExecBit:()=>zO,extractNodePath:()=>DO,isStaleNodePath:()=>MO,rewriteShellSnapshots:()=>LO,selfHealCacheHealHook:()=>_9,selfHealShellSnapshots:()=>b9});import{existsSync as wc,readFileSync as Qb,writeFileSync as ex,chmodSync as f9,statSync as NO,readdirSync as m9,renameSync as h9,unlinkSync as g9}from"node:fs";import{join as y9}from"node:path";function AO(t){return String(t).replace(/\\/g,"/")}function DO(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e)return null;let n;if(e.startsWith('"')){let o=e.indexOf('"',1);if(o===-1)return null;n=e.slice(1,o)}else{let o=e.search(/\s/);n=o===-1?e:e.slice(0,o)}if(!n)return null;let r=n.split(/[\\/]/).pop()??"";return/^node(\.exe)?$/i.test(r)?n:null}function MO(t){let e=DO(t);if(!e)return!1;try{return!wc(e)}catch{return!1}}function jO({scriptPath:t,platform:e,nodePath:n}){if(!t||typeof t!="string")throw new TypeError("buildHookCommand: scriptPath is required");let r=AO(t);if(e==="win32"){if(!n||typeof n!="string")throw new TypeError("buildHookCommand: nodePath is required on win32");return`"${AO(n)}" "${r}"`}return`"${r}"`}function _9({settingsPath:t,scriptPath:e,platform:n,nodePath:r}){if(!t||!wc(t))return"missing-settings";let o;try{o=Qb(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")&&MO(d.command)&&(d.command=jO({scriptPath:e,platform:n,nodePath:r}),c=!0)}if(!c)return"noop";if(n!=="win32"&&e&&wc(e))try{zO(e)}catch{}try{ex(t,JSON.stringify(s,null,2)+`
|
|
1426
|
+
`,"utf-8")}catch{return"noop"}return"healed"}function LO({snapshotsDir:t,currentVersion:e}){let n={rewritten:[]};if(!t||typeof t!="string"||!e||typeof e!="string")return n;let r;try{if(!wc(t))return n;r=m9(t)}catch{return n}let o=/(context-mode[/\\]context-mode[/\\])([^/\\]+)([/\\]bin)/g;for(let s of r){if(!s.endsWith(".sh"))continue;let i=y9(t,s),a;try{if(!NO(i).isFile())continue;a=Qb(i,"utf-8")}catch{continue}let c=!1,u=a.replace(o,(d,p,m,f)=>m===e?d:(c=!0,`${p}${e}${f}`));if(!c)continue;let l=`${i}.tmp-${process.pid}-${Date.now()}`;try{ex(l,u,"utf-8"),h9(l,i),n.rewritten.push(i)}catch{try{g9(l)}catch{}}}return n}function b9({snapshotsDir:t,pluginCacheRoot:e,currentVersion:n}){return LO({snapshotsDir:t,currentVersion:n})}function zO(t){if(!(!t||!wc(t)))try{let e=Qb(t,"utf-8");e.startsWith("#!")||ex(t,`#!/usr/bin/env node
|
|
1427
|
+
${e}`,"utf-8"),(NO(t).mode&511)!==493&&f9(t,493)}catch{}}var UO=x(()=>{"use strict"});import{stdout as $I,stdin as PI}from"node:process";import*as br from"node:readline";var ix=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let n=0;for(t.lastIndex=0;t.test(e);)n+=1;return e.length-n}})(),ax=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,cx=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||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>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var pI=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,fI=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ux=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,mI=/\t{1,1000}/y,lx=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"),hI=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,gI=new RegExp("\\p{M}+","gu"),yI={limit:1/0,ellipsis:""},dx=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?dx(o,yI,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,u=n.emojiWidth??2,l=2,d=n.regularWidth??1,p=n.wideWidth??l,m=[[hI,d],[pI,i],[fI,a],[mI,c],[lx,u],[ux,p]],f=0,h=0,g=t.length,y=0,_=!1,b=g,S=Math.max(0,r-s),T=0,D=0,v=0,$=0;e:for(;;){if(D>T||h>=g&&h>f){let P=t.slice(T,D)||t.slice(f,h);y=0;for(let A of P.replaceAll(gI,"")){let R=A.codePointAt(0)||0;if(ax(R)?$=l:cx(R)?$=p:$=d,v+$>S&&(b=Math.min(b,Math.max(T,f)+y)),v+$>r){_=!0;break e}y+=A.length,v+=$}T=D=0}if(h>=g)break e;for(let P=0,A=m.length;P<A;P++){let[R,C]=m[P];if(R.lastIndex=h,R.test(t)){if(y=R===ux?ix(t.slice(h,R.lastIndex)):R===lx?1:R.lastIndex-h,$=y*C,v+$>S&&(b=Math.min(b,h+Math.floor((S-v)/C))),v+$>r){_=!0;break e}v+=$,T=f,D=h,h=f=R.lastIndex;continue e}}h+=1}return{width:_?S:v,index:_?b:g,truncated:_,ellipsed:_&&r>=s}},px=dx;var _I={limit:1/0,ellipsis:"",ellipsisWidth:0},bI=(t,e={})=>px(t,_I,e).width,Tt=bI;var Pc="\x1B",yx="\x9B",xI=39,tp="\x07",_x="[",SI="]",bx="m",np=`${SI}8;;`,fx=new RegExp(`(?:\\${_x}(?<code>\\d+)m|\\${np}(?<uri>.*)${tp})`,"y"),mx=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=>`${Pc}${_x}${t}${bx}`,gx=t=>`${Pc}${np}${t}${tp}`,ep=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:Tt(i),c=r.next(),u=r.next(),l=0;for(;!c.done;){let d=c.value,p=Tt(d);a+p<=n?t[t.length-1]+=d:(t.push(d),a=0),(d===Pc||d===yx)&&(o=!0,s=e.startsWith(np,l+1)),o?s?d===tp&&(o=!1,s=!1):d===bx&&(o=!1):(a+=p,a===n&&!u.done&&(t.push(""),a=0)),c=u,u=r.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},vI=t=>{let e=t.split(" "),n=e.length;for(;n&&!Tt(e[n-1]);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},kI=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let f=a.at(-1)??"",h=f.trimStart();f.length!==h.length&&(a[a.length-1]=h,c=Tt(h))}d!==0&&(c>=e&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),c=0),(c||n.trim===!1)&&(a[a.length-1]+=" ",c++));let m=Tt(p);if(n.hard&&m>e){let f=e-c,h=1+Math.floor((m-f-1)/e);Math.floor((m-1)/e)<h&&a.push(""),ep(a,p,e),c=Tt(a.at(-1)??"");continue}if(c+m>e&&c&&m){if(n.wordWrap===!1&&c<e){ep(a,p,e),c=Tt(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>e&&n.wordWrap===!1){ep(a,p,e),c=Tt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=m}n.trim!==!1&&(a=a.map(d=>vI(d)));let u=a.join(`
|
|
1428
|
+
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(r+=p,l)l=!1;else if(l=p>="\uD800"&&p<="\uDBFF",l)continue;if(p===Pc||p===yx){fx.lastIndex=d+1;let f=fx.exec(u)?.groups;if(f?.code!==void 0){let h=Number.parseFloat(f.code);o=h===xI?void 0:h}else f?.uri!==void 0&&(s=f.uri.length===0?void 0:f.uri)}if(u[d+1]===`
|
|
1429
|
+
`){s&&(r+=gx(""));let m=o?mx(o):void 0;o&&m&&(r+=hx(m))}else p===`
|
|
1430
|
+
`&&(o&&mx(o)&&(r+=hx(o)),s&&(r+=gx(s)))}return r},wI=/\r?\n/;function is(t,e,n){return String(t).normalize().split(wI).map(r=>kI(r,e,n)).join(`
|
|
1431
|
+
`)}var Ci=Ri(op(),1);import{ReadStream as Sx}from"node:tty";var RI=["up","down","left","right","space","enter","cancel"],CI=["January","February","March","April","May","June","July","August","September","October","November","December"],An={actions:new Set(RI),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:[...CI],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 vx(t,e){if(typeof t=="string")return An.aliases.get(t)===e;for(let n of t)if(n!==void 0&&vx(n,e))return!0;return!1}var OI=globalThis.process.platform.startsWith("win");function kx({input:t=PI,output:e=$I,overwrite:n=!0,hideCursor:r=!0}={}){let o=br.createInterface({input:t,output:e,prompt:"",tabSize:1});br.emitKeypressEvents(t,o),t instanceof Sx&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(vx([u,a,c],"cancel")){r&&e.write(Ci.cursor.show),process.exit(0);return}if(!n)return;br.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{br.clearLine(e,1,()=>{t.once("keypress",s)})})};return r&&e.write(Ci.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),r&&e.write(Ci.cursor.show),t instanceof Sx&&t.isTTY&&!OI&&t.setRawMode(!1),o.terminal=!1,o.close()}}var sp=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as xe,stripVTControlCharacters as TW}from"node:util";import Qt from"node:process";var Oi=Ri(op(),1);function AI(){return Qt.platform!=="win32"?Qt.env.TERM!=="linux":!!Qt.env.CI||!!Qt.env.WT_SESSION||!!Qt.env.TERMINUS_SUBLIME||Qt.env.ConEmuTask==="{cmd::Cmder}"||Qt.env.TERM_PROGRAM==="Terminus-Sublime"||Qt.env.TERM_PROGRAM==="vscode"||Qt.env.TERM==="xterm-256color"||Qt.env.TERM==="alacritty"||Qt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ip=AI(),NI=()=>process.env.CI==="true";var Se=(t,e)=>ip?t:e,CW=Se("\u25C6","*"),DI=Se("\u25A0","x"),MI=Se("\u25B2","x"),ap=Se("\u25C7","o"),jI=Se("\u250C","T"),xr=Se("\u2502","|"),LI=Se("\u2514","\u2014"),OW=Se("\u2510","T"),IW=Se("\u2518","\u2014"),AW=Se("\u25CF",">"),NW=Se("\u25CB"," "),DW=Se("\u25FB","[\u2022]"),MW=Se("\u25FC","[+]"),jW=Se("\u25FB","[ ]"),LW=Se("\u25AA","\u2022"),wx=Se("\u2500","-"),zI=Se("\u256E","+"),HI=Se("\u251C","+"),UI=Se("\u256F","+"),FI=Se("\u2570","+"),zW=Se("\u256D","+"),BI=Se("\u25CF","\u2022"),ZI=Se("\u25C6","*"),qI=Se("\u25B2","!"),VI=Se("\u25A0","x");var HW=[`${xe("dim","\u2191/\u2193")} to navigate`,`${xe("dim","Space:")} select`,`${xe("dim","Enter:")} confirm`];var O={message:(t=[],{symbol:e=xe("gray",xr),secondarySymbol:n=xe("gray",xr),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??An.withGuide,c=a?n:"",u=a?`${e} `:"",l=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
1432
1432
|
`);if(d.length>0){let[p,...m]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let f of m)f.length>0?i.push(`${l}${f}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
1433
1433
|
`)}
|
|
1434
|
-
`)},info:(t,e)=>{O.message(t,{...e,symbol:xe("blue",
|
|
1435
|
-
`)}
|
|
1436
|
-
${xe("gray",
|
|
1434
|
+
`)},info:(t,e)=>{O.message(t,{...e,symbol:xe("blue",BI)})},success:(t,e)=>{O.message(t,{...e,symbol:xe("green",ZI)})},step:(t,e)=>{O.message(t,{...e,symbol:xe("green",ap)})},warn:(t,e)=>{O.message(t,{...e,symbol:xe("yellow",qI)})},warning:(t,e)=>{O.warn(t,e)},error:(t,e)=>{O.message(t,{...e,symbol:xe("red",VI)})}};var cp=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??An.withGuide?`${xe("gray",jI)} `:"";n.write(`${r}${t}
|
|
1435
|
+
`)},Rc=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??An.withGuide?`${xe("gray",xr)}
|
|
1436
|
+
${xe("gray",LI)} `:"";n.write(`${r}${t}
|
|
1437
1437
|
|
|
1438
|
-
`)};var
|
|
1439
|
-
`),s=o.reduce((c,u)=>Math.max(
|
|
1440
|
-
`).map(s),""],a=
|
|
1438
|
+
`)};var WI=t=>t,KI=(t,e,n)=>{let r={hard:!0,trim:!1},o=is(t,e,r).split(`
|
|
1439
|
+
`),s=o.reduce((c,u)=>Math.max(Tt(u),c),0),i=o.map(n).reduce((c,u)=>Math.max(Tt(u),c),0),a=e-(i-s);return is(t,a,r)},Cc=(t="",e="",n)=>{let r=n?.output??Qt.stdout,o=n?.withGuide??An.withGuide,s=n?.format??WI,i=["",...KI(t,sp(r)-6,s).split(`
|
|
1440
|
+
`).map(s),""],a=Tt(e),c=Math.max(i.reduce((p,m)=>{let f=Tt(m);return f>p?f:p},0),a)+2,u=i.map(p=>`${xe("gray",xr)} ${p}${" ".repeat(c-Tt(p))}${xe("gray",xr)}`).join(`
|
|
1441
1441
|
`),l=o?`${xe("gray",xr)}
|
|
1442
|
-
`:"",d=o?
|
|
1442
|
+
`:"",d=o?HI:FI;r.write(`${l}${xe("green",ap)} ${xe("reset",e)} ${xe("gray",wx.repeat(Math.max(c-a-1,1))+zI)}
|
|
1443
1443
|
${u}
|
|
1444
|
-
${xe("gray",d+
|
|
1445
|
-
`)};var
|
|
1446
|
-
`);let B=
|
|
1447
|
-
`);B.length>1&&n.write(
|
|
1448
|
-
`);let ge=0,Le=0;D(),d=setInterval(()=>{if(u&&f===h)return;$(),h=f;let
|
|
1449
|
-
`):n.write(`${
|
|
1450
|
-
`)),v(),l()};return{start:C,stop:(B="")=>z(B,0),message:(B="")=>{f=P(B??f)},cancel:(B="")=>z(B,1),error:(B="")=>z(B,2),clear:()=>z("",0,!0),get isCancelled(){return m}}},
|
|
1451
|
-
`)}catch{}return null}return i[1]}catch{return null}}_o();Nn();function
|
|
1452
|
-
`))}if(
|
|
1453
|
-
Could not auto-open browser. Open manually: ${t}`),s=
|
|
1454
|
-
`),"Storage paths"),n+=
|
|
1444
|
+
${xe("gray",d+wx.repeat(c+2)+UI)}
|
|
1445
|
+
`)};var GI=t=>xe("magenta",t),up=({indicator:t="dots",onCancel:e,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:s=ip?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=ip?80:120,signal:a,...c}={})=>{let u=NI(),l,d,p=!1,m=!1,f="",h,g=performance.now(),y=sp(n),_=c?.styleFrame??GI,b=B=>{let ge=B>1?o??An.messages.error:r??An.messages.cancel;m=B===1,p&&(z(ge,B),m&&typeof e=="function"&&e())},S=()=>b(2),T=()=>b(1),D=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",b),a&&a.addEventListener("abort",T)},v=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",b),a&&a.removeEventListener("abort",T)},$=()=>{if(h===void 0)return;u&&n.write(`
|
|
1446
|
+
`);let B=is(h,y,{hard:!0,trim:!1}).split(`
|
|
1447
|
+
`);B.length>1&&n.write(Oi.cursor.up(B.length-1)),n.write(Oi.cursor.to(0)),n.write(Oi.erase.down())},P=B=>B.replace(/\.+$/,""),A=B=>{let ge=(performance.now()-B)/1e3,Le=Math.floor(ge/60),ut=Math.floor(ge%60);return Le>0?`[${Le}m ${ut}s]`:`[${ut}s]`},R=c.withGuide??An.withGuide,C=(B="")=>{p=!0,l=kx({output:n}),f=P(B),g=performance.now(),R&&n.write(`${xe("gray",xr)}
|
|
1448
|
+
`);let ge=0,Le=0;D(),d=setInterval(()=>{if(u&&f===h)return;$(),h=f;let ut=_(s[ge]),In;if(u)In=`${ut} ${f}...`;else if(t==="timer")In=`${ut} ${f} ${A(g)}`;else{let $c=".".repeat(Math.floor(Le)).slice(0,3);In=`${ut} ${f}${$c}`}let Tc=is(In,y,{hard:!0,trim:!1});n.write(Tc),ge=ge+1<s.length?ge+1:0,Le=Le<4?Le+.125:0},i)},z=(B="",ge=0,Le=!1)=>{if(!p)return;p=!1,clearInterval(d),$();let ut=ge===0?xe("green",ap):ge===1?xe("red",DI):xe("red",MI);f=B??f,Le||(t==="timer"?n.write(`${ut} ${f} ${A(g)}
|
|
1449
|
+
`):n.write(`${ut} ${f}
|
|
1450
|
+
`)),v(),l()};return{start:C,stop:(B="")=>z(B,0),message:(B="")=>{f=P(B??f)},cancel:(B="")=>z(B,1),error:(B="")=>z(B,2),clear:()=>z("",0,!0),get isCancelled(){return m}}},UW={light:Se("\u2500","-"),heavy:Se("\u2501","="),block:Se("\u2588","#")};var FW=[`${xe("dim","\u2191/\u2193")} to navigate`,`${xe("dim","Enter:")} confirm`];var BW=`${xe("gray",xr)} `;var k=Ri($x(),1);as();_p();Pr();rn();Lf();Zf();import{execFileSync as $i,execSync as x9,execFile as S9}from"node:child_process";import{readFileSync as Xn,cpSync as FO,accessSync as qO,existsSync as Ve,readdirSync as v9,rmSync as Zd,closeSync as k9,openSync as w9,chmodSync as E9,lstatSync as T9,realpathSync as Wd,statSync as VO,constants as WO}from"node:fs";import{request as $9}from"node:https";import{resolve as Q,dirname as KO,join as Ec,sep as Yn,basename as P9,isAbsolute as R9}from"node:path";import{tmpdir as C9,devNull as O9,homedir as Kd}from"node:os";import{fileURLToPath as I9,pathToFileURL as Gd}from"node:url";import{execFileSync as RM}from"node:child_process";var CM="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",OM=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,IM=(t,e)=>RM(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),AM=t=>{try{return process.kill(t,0),!0}catch{return!1}},NM=(t,e)=>{process.kill(t,e)};function DM(t){let e=new Set;for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||!/^\d+$/.test(r))continue;let o=Number.parseInt(r,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Ak(t){let e=t.platform??process.platform,n=t.runCommand??IM,r="";try{e==="win32"?r=n("powershell",["-NoProfile","-Command",OM]):r=n("pgrep",["-f",CM])}catch{return[]}return DM(r).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function MM(t){return new Promise(e=>{setTimeout(e,t)})}async function Nk(t){let e=t.timeoutMs??1500,n=t.pollIntervalMs??100,r=t.isAlive??AM,o=t.sendSignal??NM,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){r(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 MM(n);for(let d of[...a])r(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}}Vf();Zi();import{existsSync as qM}from"node:fs";import{execSync as VM,execFileSync as O5,spawnSync as I5}from"node:child_process";function Lk({platform:t=process.platform,existsSync:e=qM,exec:n=VM,now:r=()=>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=n(`"${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=r()+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.
|
|
1451
|
+
`)}catch{}return null}return i[1]}catch{return null}}_o();Nn();function A9(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 N9={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs",stop:"hooks/stop.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"},"copilot-cli":{pretooluse:"hooks/copilot-cli/pretooluse.mjs",posttooluse:"hooks/copilot-cli/posttooluse.mjs",precompact:"hooks/copilot-cli/precompact.mjs",sessionstart:"hooks/copilot-cli/sessionstart.mjs",userpromptsubmit:"hooks/copilot-cli/userpromptsubmit.mjs",stop:"hooks/copilot-cli/stop.mjs"},"antigravity-cli":{pretooluse:"hooks/antigravity-cli/pretooluse.mjs",posttooluse:"hooks/antigravity-cli/posttooluse.mjs",stop:"hooks/antigravity-cli/stop.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 D9(t,e){try{k9(2),w9(O9,"w")}catch{process.stderr.write=(()=>!0)}let n=N9[t]?.[e];n||process.exit(0);let r=Pi();await import(Gd(Ec(r,n)).href)}var _t=process.argv.slice(2);function M9(){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(`
|
|
1452
|
+
`))}if(_t[0]==="--help"||_t[0]==="-h"||_t[0]==="help")M9();else if(_t[0]==="index")Z9(_t.slice(1)).then(t=>process.exit(t));else if(_t[0]==="search")q9(_t.slice(1)).then(t=>process.exit(t));else if(_t[0]==="doctor")V9().then(t=>process.exit(t));else if(_t[0]==="upgrade"){let t=_t.indexOf("--platform"),e=t>=0&&_t[t+1]?_t[t+1]:void 0;K9(e?{platform:e}:void 0).catch(n=>{let r=n instanceof Error?n.message:String(n);O.error(k.default.red(r)),process.exit(1)})}else _t[0]==="hook"?D9(_t[1],_t[2]):_t[0]==="insight"?W9():_t[0]==="statusline"?G9():Promise.resolve().then(()=>(kO(),vO));function Wte(t){return t.replace(/\\/g,"/")}var Jd=process.platform==="win32";function qd(t,e={}){$i(Jd?"npm.cmd":"npm",t,{...e,...Jd?{shell:!0}:{}})}function Kte(t,e={}){let n={...e,...Jd?{shell:!0}:{}};x9(Jd?t.replace(/^npm /,"npm.cmd "):t,n)}function j9(t,e=process.platform,n=S9){let r={stdio:"ignore"},o=()=>console.error(`
|
|
1453
|
+
Could not auto-open browser. Open manually: ${t}`),s=A9(t,e),i=!1;for(let{cmd:a,args:c}of s)try{n(a,c,r),i=!0;break}catch{}i||o()}function L9(){let t=I9(import.meta.url),e=KO(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?Q(e,".."):e}function z9(t){let e=vS();if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;return n?Q(n,t,...e):Q(Kd(),"AppData","Local",t,...e)}return Q(Kd(),".cache",t,...e)}function Pi(){let t=tt().platform;return ro(t)?z9(t):L9()}function GO(){try{return JSON.parse(Xn(Q(Pi(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function H9(){return new Promise(t=>{let e=$9(Kc,{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Vd(t){return t.envVar?t.envVar:"adapter default"}function JO(t){let e=[],n={};for(let r=0;r<t.length;r++){let o=t[r];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[r+1],l=c!==void 0?c:u&&!u.startsWith("--")?(r++,u):!0;if(a==="include"||a==="exclude"){let d=n[a];n[a]=Array.isArray(d)?[...d,String(l)]:[String(l)]}else n[a]=l}return{positional:e,flags:n}}function no(t,e){let n=t[e];if(typeof n=="string"&&n.length>0)return n}function BO(t,e){return t[e]===!0||t[e]==="true"}function ZO(t,e){let n=t[e];if(Array.isArray(n))return n.filter(Boolean);if(typeof n=="string"&&n.length>0)return[n]}function nx(t,e,n={}){let r=no(t,e);if(!r)return;let o=Number(r),s=n.min??1;if(!Number.isInteger(o)||o<s)throw new Error(`--${e} must be an integer >= ${s}`);return o}function U9(t){let e=no(t,"ext")??no(t,"extensions");if(!e)return;let n=e.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith(".")?r:`.${r}`);return n.length>0?n:void 0}function XO(t,e){return t?Q(t):Q(e)}async function YO(t){let e=await Qi(tt().platform),n=io(()=>e.getSessionDir()),r=Tr(n),{resolveContentStorePath:o}=await Promise.resolve().then(()=>(rn(),sS)),s=o({projectDir:t,contentDir:r});return{store:new Rs(s),dbPath:s,contentDir:r}}function F9(t){try{if(VO(t).isDirectory())return`project:${P9(t)||t}`}catch{}return t}function B9(t,e){let n=xo("Read",e);if(Ar(t,n,process.platform==="win32",e).denied)throw new Error(`Read denied by policy: ${t}`)}async function Z9(t){try{let e=JO(t),n=e.positional[0];if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode index <path> [--source label] [--project path] [--max-files n] [--max-depth n] [--ext .ts,.md]"),n?0:1;let r=R9(n)?Q(n):Q(process.cwd(),n);if(!Ve(r))throw new Error(`Path does not exist: ${r}`);let o=VO(r),s=XO(no(e.flags,"project"),o.isDirectory()?r:KO(r)),i=no(e.flags,"source")??F9(r),{store:a,dbPath:c}=await YO(s);try{if(B9(r,s),o.isDirectory()){let u=xo("Read",s),l=a.indexDirectory({path:r,source:i,include:ZO(e.flags,"include"),exclude:ZO(e.flags,"exclude"),maxDepth:nx(e.flags,"max-depth",{min:0}),maxFiles:nx(e.flags,"max-files"),extensions:U9(e.flags),respectGitignore:!BO(e.flags,"no-gitignore"),followSymlinks:BO(e.flags,"follow-symlinks"),perFileDeny:f=>{try{return Ar(f,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`:"",m=l.failed>0?`; ${l.failed} failed`:"";console.log(`Indexed ${l.filesIndexed} files (${l.totalChunks} sections) from ${r}${d}${p}${m}`)}else{let u=a.index({path:r,source:i});console.log(`Indexed ${u.totalChunks} sections (${u.codeChunks} with code) from ${r}`)}return console.log(`Source: ${i}`),console.log(`Project: ${s}`),console.log(`DB: ${c}`),0}finally{a.close()}}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`context-mode index: ${n}`),1}}async function q9(t){try{let e=JO(t),n=e.positional.join(" ").trim();if(!n||n==="-h"||n==="--help")return console.log("Usage: context-mode search <query...> [--source label] [--project path] [--limit n] [--type code|prose]"),n?0:1;let r=XO(no(e.flags,"project"),process.cwd()),{store:o,dbPath:s}=await YO(r);try{let i=nx(e.flags,"limit")??3,a=no(e.flags,"type");if(a&&a!=="code"&&a!=="prose")throw new Error("--type must be code or prose");let c=o.searchWithFallback(n,i,no(e.flags,"source"),a);if(c.length===0)return console.log(`No matches for: ${n}`),console.log(`Project: ${r}`),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 n=e instanceof Error?e.message:String(e);return console.error(`context-mode search: ${n}`),1}}function tx(t){try{return Tr(t),O.success(k.default.green(`Storage ${t.kind}: PASS`)+k.default.dim(` \u2014 ${t.path} (${Vd(t)})`)),0}catch(e){if(e instanceof tn)return O.error(k.default.red(`Storage ${t.kind}: FAIL`)+k.default.dim(` \u2014 ${gs(e)}`)),1;throw e}}async function V9(){process.stdout.isTTY&&console.clear();let t=tt(),e=await Qi(t.platform);cp(k.default.bgMagenta(k.default.white(" context-mode doctor "))),O.info(`Platform: ${k.default.cyan(e.name)}`+k.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let n=0;try{let y=Er(()=>e.getSessionDir()),_=io(()=>y.path),b=hs(()=>y.path);Cc([`sessions: ${y.path} (${Vd(y)})`,`content: ${_.path} (${Vd(_)})`,`stats: ${b.path} (${Vd(b)})`].join(`
|
|
1454
|
+
`),"Storage paths"),n+=tx(y),n+=tx(_),n+=tx(b)}catch(y){if(y instanceof tn)n++,O.error(k.default.red(`Storage ${y.kind}: FAIL`)+k.default.dim(` \u2014 ${gs(y)}`));else throw y}let r=up();r.start("Running diagnostics");let o,s;try{o=oo(),s=Di(o)}catch{return r.stop("Diagnostics partial"),O.warn(k.default.yellow("Could not detect runtimes")+k.default.dim(" \u2014 module may be missing, restart session after upgrade")),Rc(k.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}r.stop("Diagnostics complete"),Cc(Ni(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(er(),Sp));process.platform==="linux"&&!y()&&!Sr()&&(n++,O.error(k.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+k.default.dim(`
|
|
1455
1455
|
context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
|
|
1456
1456
|
V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
|
|
1457
1457
|
Refs: https://github.com/nodejs/node/issues/62515
|
|
1458
1458
|
https://github.com/mksglu/context-mode/issues/564
|
|
1459
1459
|
Fix: nvm install 22.5 && nvm use 22.5 && npm install -g @mxalbert/context-mode
|
|
1460
|
-
Or: curl -fsSL https://bun.sh/install | bash && bun add -g @mxalbert/context-mode`)))}Sr()?O.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):O.warn(k.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?(n++,O.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):O.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),O.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(
|
|
1460
|
+
Or: curl -fsSL https://bun.sh/install | bash && bun add -g @mxalbert/context-mode`)))}Sr()?O.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):O.warn(k.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?(n++,O.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):O.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),O.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(bb(),LR)),b=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(b.exitCode===0&&b.stdout.trim()==="ok")O.success(k.default.green("Server test: PASS"));else{n++;let S=b.stderr?.trim()?` (${b.stderr.trim().slice(0,200)})`:"";O.error(k.default.red("Server test: FAIL")+` \u2014 exit ${b.exitCode}${S}`)}}catch(y){let _=y instanceof Error?y.message:String(y);_.includes("Cannot find module")||_.includes("MODULE_NOT_FOUND")?O.warn(k.default.yellow("Server test: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(n++,O.error(k.default.red("Server test: FAIL")+` \u2014 ${_}`))}O.step(`Checking ${e.name} hooks configuration...`);let c=Pi(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?O.success(k.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?O.warn(k.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1461
1461
|
Run: ${y.fix}`):"")):O.error(k.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1462
|
-
Run: ${y.fix}`):""));O.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?O.success(k.default.green(`${y.name}: PASS`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):"")):O.error(k.default.red(`${y.name}: FAIL`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):""))}else{let y=
|
|
1462
|
+
Run: ${y.fix}`):""));O.step("Checking hook scripts...");let l=e.getHealthChecks?.(c)??[];if(l.length>0)for(let y of l){let _=y.check();_.status==="OK"?O.success(k.default.green(`${y.name}: PASS`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):"")):O.error(k.default.red(`${y.name}: FAIL`)+(_.detail?k.default.dim(` \u2014 ${_.detail}`):""))}else{let y=Nc(e,c);if(y.length===0)O.success(k.default.green("Hook scripts: PASS")+k.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let _ of y){let b=Q(c,_);try{qO(b,WO.R_OK),O.success(k.default.green("Hook script exists: PASS")+k.default.dim(` \u2014 ${b}`))}catch{O.error(k.default.red("Hook script exists: FAIL")+k.default.dim(` \u2014 not found at ${b}`))}}}O.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?O.success(k.default.green("Plugin enabled: PASS")+k.default.dim(` \u2014 ${d.message}`)):O.warn(k.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),O.step("Checking team-shared hook configs in your workspace...");{let T=function(v){return!!(v.startsWith("/")||/^[A-Za-z]:[/\\]/.test(v)||v.includes("\\\\")||v.includes("fnm_multishells")||v.includes("process.execPath"))},D=function(v,$){if(typeof v=="string")$(v);else if(Array.isArray(v))for(let P of v)D(P,$);else if(v&&typeof v=="object")for(let P of Object.values(v))D(P,$)};var h=T,g=D;let y=process.cwd(),_=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],b=0,S=0;for(let v of _){let $=Q(y,v);if(Ve($)){S++;try{let P=JSON.parse(Xn($,"utf-8")),A=[];if(D(P,R=>{T(R)&&A.push(R)}),A.length>0){n++,b++;let R=A[0].length>100?A[0].slice(0,97)+"...":A[0];O.error(k.default.red("Hook config: FAIL")+` \u2014 ${v} has your machine's local paths baked in`+k.default.dim(`
|
|
1463
1463
|
This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
|
|
1464
1464
|
Found ${A.length} hard-coded path(s), e.g.: ${R}
|
|
1465
1465
|
Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
|
|
1466
1466
|
Details: https://github.com/mksglu/context-mode/issues/613`))}else O.success(k.default.green("Hook config: PASS")+k.default.dim(` \u2014 ${v} is portable (no hard-coded paths)`))}catch(P){let A=P instanceof Error?P.message:String(P);O.warn(k.default.yellow("Hook config: WARN")+` \u2014 ${v} is not valid JSON`+k.default.dim(`
|
|
1467
1467
|
Doctor cannot scan it for portability issues until the file parses.
|
|
1468
1468
|
Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
|
|
1469
|
-
Parser said: ${A.slice(0,160)}`))}}}S===0&&O.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}O.step("Checking for leftover .mcp.json files from older versions...");{let y=
|
|
1469
|
+
Parser said: ${A.slice(0,160)}`))}}}S===0&&O.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}O.step("Checking for leftover .mcp.json files from older versions...");{let y=Ec(Kd(),".claude","plugins","cache","context-mode","context-mode");if(!Ve(y))O.info(k.default.dim("Leftover .mcp.json check: SKIP \u2014 no plugin cache exists yet (Claude Code has not installed context-mode here)"));else{let _=0,b=[];try{let S=v9(y);for(let T of S){let D=Ec(y,T,".mcp.json");Ve(D)&&(_++,b.length<5&&b.push(T))}}catch(S){let T=S instanceof Error?S.message:String(S);O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+k.default.dim(`
|
|
1470
1470
|
Path: ${y}
|
|
1471
1471
|
Reason: ${T.slice(0,160)}
|
|
1472
1472
|
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),_=0}_===0?O.success(k.default.green("Leftover .mcp.json check: PASS")+k.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):O.warn(k.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${_} old .mcp.json file(s) left over from previous context-mode versions`+k.default.dim(`
|
|
1473
1473
|
These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
|
|
1474
1474
|
Versions affected: ${b.join(", ")}${_>b.length?", ...":""}
|
|
1475
1475
|
Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
|
|
1476
|
-
Details: https://github.com/mksglu/context-mode/issues/609`))}}O.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(er(),
|
|
1476
|
+
Details: https://github.com/mksglu/context-mode/issues/609`))}}O.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(er(),Sp))).loadDatabase(),_=new y(":memory:");_.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),_.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let b=_.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();_.close(),b&&b.content==="hello world"?O.success(k.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(n++,O.error(k.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let _=y instanceof Error?y.message:String(y),b=Pi(),S=Q(b,"node_modules","better-sqlite3");!Ve(S)?(n++,O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+k.default.dim(" \u2014 package-missing")+k.default.dim(`
|
|
1477
1477
|
Path: ${S}
|
|
1478
1478
|
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).
|
|
1479
1479
|
Try (primary): cd "${b}" && npm install better-sqlite3 --no-optional
|
|
@@ -1481,15 +1481,15 @@ Could not auto-open browser. Open manually: ${t}`),s=P9(t,e),i=!1;for(let{cmd:a,
|
|
|
1481
1481
|
Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
|
|
1482
1482
|
Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
|
|
1483
1483
|
Try (fallback): npm rebuild better-sqlite3`)):O.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${_}`+k.default.dim(`
|
|
1484
|
-
Try: npm rebuild better-sqlite3`)))}O.step("Checking versions...");let p=
|
|
1484
|
+
Try: npm rebuild better-sqlite3`)))}O.step("Checking versions...");let p=GO(),m=await H9(),f=e.getInstalledVersion();return m==="unknown"?O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===m?O.success(k.default.green("npm (MCP): PASS")+` \u2014 v${p}`):O.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${m}`+k.default.dim(`
|
|
1485
1485
|
Run: /context-mode:ctx-upgrade`)),f==="standalone"?O.info(k.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):f==="not installed"?O.info(k.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):m!=="unknown"&&f===m?O.success(k.default.green(`${e.name}: PASS`)+` \u2014 v${f}`):m!=="unknown"?O.warn(k.default.yellow(`${e.name}: WARN`)+` \u2014 v${f}, latest v${m}`+k.default.dim(`
|
|
1486
|
-
Run: /context-mode:ctx-upgrade`)):O.info(`${e.name}: v${f}`+k.default.dim(" \u2014 could not verify against npm registry")),n>0?(
|
|
1486
|
+
Run: /context-mode:ctx-upgrade`)):O.info(`${e.name}: v${f}`+k.default.dim(" \u2014 could not verify against npm registry")),n>0?(Rc(k.default.red(`Diagnostics failed \u2014 ${n} critical issue(s) found`)),1):(Rc(s.length>=4?k.default.green("Diagnostics complete!"):k.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function W9(){let t="https://context-mode.com/insight";console.log(`
|
|
1487
1487
|
context-mode Insight
|
|
1488
1488
|
${t}
|
|
1489
|
-
`),
|
|
1490
|
-
Try manually: cd "${r}" && npm rebuild better-sqlite3`))}let $=Q(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!
|
|
1489
|
+
`),j9(t)}async function K9(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:tt(),n=await Qi(e.platform);cp(k.default.bgCyan(k.default.black(" context-mode upgrade "))),O.info(`Platform: ${k.default.cyan(n.name)}`+k.default.dim(` (${e.confidence} confidence)`));let r=Pi(),o=[],s=up(),i=Q(Ze(),"plugins","marketplaces","context-mode");if(Ve(Ec(i,".git"))){s.start("Syncing marketplace clone");try{$i("git",["-C",i,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(k.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),O.info(k.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):($i("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),$i("git",["-C",i,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(k.default.green("Marketplace clone synced")),o.push("Marketplace clone updated to upstream"))}catch(p){let m=p instanceof Error?p.message:String(p);s.stop(k.default.yellow("Marketplace sync skipped")),O.warn(k.default.yellow("git refresh on marketplace failed")+` \u2014 ${m}`),O.info(k.default.dim(" Continuing \u2014 cache dir update will still happen."))}}O.step("Pulling latest from GitHub...");let a=GO(),c=Ec(C9(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{$i("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let p=c,f=JSON.parse(Xn(Q(p,"package.json"),"utf-8")).version??"unknown";if(f===a)O.success(k.default.green("Already on latest")+` \u2014 v${a}`),Zd(c,{recursive:!0,force:!0});else{O.info(`Update available: ${k.default.yellow("v"+a)} \u2192 ${k.default.green("v"+f)}`);try{let v=Ak({ownPid:process.pid,ownPpid:process.ppid});if(v.length>0){let $=await Nk({pids:v});if($.totalKilled>0){let P=$.totalKilled===1?"sibling MCP server":"sibling MCP servers";O.info(k.default.dim(`Stopped ${$.totalKilled} ${P} (SIGTERM: ${$.terminatedBySigterm}, SIGKILL: ${$.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let h=Lk();qd(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4,...h?{env:{...process.env,npm_config_msvs_version:h}}:{}}),qd(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(Xn(Q(p,"package.json"),"utf-8")).files||[],"src","package.json"],_=Q(r)+Yn,b=Q(p)+Yn,S=v=>{try{return!T9(v).isSymbolicLink()}catch{return!1}};for(let v of y){let $=Q(p,v),P=Q(r,v);if((P+Yn).startsWith(_)&&($+Yn).startsWith(b)&&S($)&&Ve($))try{Zd(P,{recursive:!0,force:!0}),FO($,P,{recursive:!0,filter:S})}catch{}}try{let v;try{let{resolveHookRuntime:P}=await Promise.resolve().then(()=>(as(),Nx)),A=P();A.isBun&&(v=A.path)}catch{}(await Promise.resolve().then(()=>(IO(),OO))).normalizeHooksJsonOnly({pluginRoot:r,nodePath:process.execPath,jsRuntimePath:v,platform:process.platform})}catch{}try{if(e.platform==="claude-code"){let{rewriteShellSnapshots:v}=await Promise.resolve().then(()=>(UO(),HO)),$=Q(Ze(),"shell-snapshots"),P=v({snapshotsDir:$,currentVersion:f});P.rewritten.length>0&&O.info(k.default.dim(` Healed ${P.rewritten.length} stale shell snapshot(s) \u2014 Bash tool calls in the active session will pick up v${f} immediately`))}}catch{}s.stop(k.default.green(`Updated in-place to v${f}`));let T=Q(r,".claude-plugin","plugin.json"),D=null;try{let v=JSON.parse(Xn(T,"utf-8"));v&&typeof v.version=="string"&&(D=v.version)}catch{}if(D!==f)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${D??"<missing>"}" but newVersion is "${f}". Refusing to bump registry.`);n.updatePluginRegistry(r,f),O.info(k.default.dim(" Registry synced to "+r));try{let v=Q(Ze(),"plugins","installed_plugins.json");if(Ve(v)){let P=JSON.parse(Xn(v,"utf-8"))?.plugins?.[it];if(Array.isArray(P))for(let A of P){let R=A?.installPath;if(typeof R!="string"||!R)continue;if(!Ve(R))throw new Error(`installPath does not exist on disk: ${R}`);let C=Q(R,".claude-plugin","plugin.json");if(!Ve(C))throw new Error(`missing plugin.json manifest at ${C}`);let z=JSON.parse(Xn(C,"utf-8"));if(z?.version!==A.version)throw new Error(`version mismatch \u2014 registry says "${A.version}" but ${C} says "${z?.version}"`)}}}catch(v){let $=v instanceof Error?v.message:String(v);throw new Error(`Registry consistency check failed: ${$}`)}try{let v=Q(Ze(),"plugins","cache"),$=it,P=mu({pluginRoot:r,pluginCacheRoot:v,pluginKey:$});if(P&&P.error)throw new Error(P.error);let A=mu({pluginRoot:r,pluginCacheRoot:v,pluginKey:$});if(A&&Array.isArray(A.healed)&&A.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${A.healed.join(",")})`)}catch(v){let $=v instanceof Error?v.message:String(v);throw new Error(`plugin.json drift check failed: ${$}`)}try{let v=Q(Ze(),"plugins","cache"),$=it,P=hu({pluginCacheRoot:v,pluginKey:$});P&&P.removed&&P.removed.length>0&&O.info(k.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let A=hu({pluginCacheRoot:v,pluginKey:$});if(A&&Array.isArray(A.removed)&&A.removed.length>0)throw new Error(`.mcp.json sweep drift: ${A.removed.length} file(s) still present after first pass`)}catch(v){let $=v instanceof Error?v.message:String(v);throw new Error(`.mcp.json sweep check failed: ${$}`)}try{let{healClaudeJsonMcpArgs:v}=await Promise.resolve().then(()=>(Vf(),jk)),$=Q(Kd(),".claude.json"),P=Q(Ze(),"plugins","cache","context-mode","context-mode"),A=v({dotClaudeJsonPath:$,pluginCacheParent:P,newPluginRoot:r});A.healed&&A.healed.length>0&&O.info(k.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+f))}catch{}try{let v=Q(i,".claude-plugin","plugin.json");if(Ve(v)){let $=JSON.parse(Xn(v,"utf-8"));$?.version!==f&&(O.warn(k.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${$?.version}" but expected "${f}"`),O.info(k.default.dim(` Run manually: git -C "${i}" fetch --tags origin && git -C "${i}" reset --hard origin/HEAD`)))}}catch{}if(s.start("Installing production dependencies"),qd(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!ro(e.platform)){s.start("Verifying native addon ABI");let v=Q(r,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=Q(r,"hooks","ensure-deps.mjs");if(!Ve(P))throw new Error(`missing ${P}`);await import(`${Gd(P).href}?upgrade=${Date.now()}`),Ve(v)?(s.stop(k.default.green("Native addons OK")+k.default.dim(" \u2014 ABI cache present")),o.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(k.default.yellow("Native addon ABI cache missing")),O.warn(k.default.dim(` Try manually: cd "${r}" && npm rebuild better-sqlite3`)))}catch(P){let A=P instanceof Error?P.message:String(P);s.stop(k.default.yellow("Native addon ABI bootstrap unavailable")),O.warn(k.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${A}`+k.default.dim(`
|
|
1490
|
+
Try manually: cd "${r}" && npm rebuild better-sqlite3`))}let $=Q(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Ve($))try{let P=Q(r,"scripts","heal-better-sqlite3.mjs");if(Ve(P)){let A=await import(`${Gd(P).href}?upgrade=${Date.now()}`);typeof A.healBetterSqlite3Binding=="function"&&A.healBetterSqlite3Binding(r)}}catch{}Ve($)||(process.exitCode=1,O.error(k.default.red("better-sqlite3 native binding: MISSING")+k.default.dim(`
|
|
1491
1491
|
Path: ${$}`)+k.default.dim(`
|
|
1492
1492
|
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+k.default.dim(`
|
|
1493
1493
|
Try (primary): cd "${r}" && npm install better-sqlite3 --no-optional`)+k.default.dim(`
|
|
1494
|
-
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{
|
|
1495
|
-
`),"Changes Applied"):O.info(k.default.dim("No changes were needed."));let d=n.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";O.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${d})`)),O.step("Running doctor to verify..."),console.log();try{let p=Q(r,"cli.bundle.mjs"),m=Q(r,"build","cli.js"),f=
|
|
1494
|
+
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{qd(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(k.default.green("npm global updated")),o.push("Updated npm global package")}catch{s.stop(k.default.yellow("npm global update skipped")),O.info(k.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}Zd(c,{recursive:!0,force:!0});try{let v=Ze(),$=Q(v,"plugins","installed_plugins.json");if(Ve($)){let P=Q(v,"plugins","cache"),A;try{A=Wd(P)}catch{A=P}let R=A+Yn,z=JSON.parse(Xn($,"utf-8"))?.plugins?.[it];if(Array.isArray(z))for(let B of z){let ge=B?.installPath;if(typeof ge!="string"||!ge||ge===r)continue;let Le=Q(ge);if(!(Le+Yn).startsWith(R)||!Ve(Le))continue;let ut;try{ut=Wd(Le)}catch{continue}if(!(ut+Yn).startsWith(R))continue;let In=Q(p,"skills");Ve(In)&&(FO(In,Q(ut,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}catch{}o.push(`Updated v${a} \u2192 v${f}`),O.success(k.default.green("Plugin reinstalled from GitHub!")+k.default.dim(` \u2014 v${f}`))}}catch(p){let m=p instanceof Error?p.message:String(p);s.stop(k.default.red("Update failed")),O.error(k.default.red("GitHub pull failed")+` \u2014 ${m}`),process.exitCode=1,O.warn(k.default.yellow("In-place files were NOT updated")+k.default.dim(" \u2014 old version is still on disk; hooks/settings will still be refreshed.")),O.info(k.default.dim(" Recovery: re-run /ctx-upgrade once network is stable, or run /context-mode:ctx-doctor for a full health check."));try{Zd(c,{recursive:!0,force:!0})}catch{}}O.step(`Backing up ${n.name} settings...`);let u=n.backupSettings();u?.endsWith(".bak")?(O.success(k.default.green("Backup created")+k.default.dim(" -> "+u)),o.push("Backed up settings")):u?O.success(k.default.green("Backup skipped")+k.default.dim(" \u2014 no changes needed")):O.warn(k.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),O.step(`Configuring ${n.name} hooks...`);try{let p=n.configureAllHooks(r);for(let m of p)O.info(k.default.dim(` ${m}`)),o.push(m);O.success(k.default.green("Hooks configured")+k.default.dim(` \u2014 ${n.name}`))}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Hook configuration failed: ${m}`)}O.step("Setting hook script permissions...");let l=n.setHookPermissions(r);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let m=Q(r,p);try{qO(m,WO.F_OK),E9(m,493),l.push(m)}catch{}}l.length>0?(O.success(k.default.green("Permissions set")+k.default.dim(` \u2014 ${l.length} hook script(s)`)),o.push(`Set ${l.length} hook scripts as executable`)):O.error(k.default.red("No hook scripts found")+k.default.dim(" \u2014 expected in "+Q(r,"hooks"))),o.length>0?Cc(o.map(p=>k.default.green(" + ")+p).join(`
|
|
1495
|
+
`),"Changes Applied"):O.info(k.default.dim("No changes were needed."));let d=n.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";O.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${d})`)),O.step("Running doctor to verify..."),console.log();try{let p=Q(r,"cli.bundle.mjs"),m=Q(r,"build","cli.js"),f=Ve(p)?p:m;$i("node",[f,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{O.warn(k.default.yellow("Doctor had warnings")+k.default.dim(` \u2014 restart your ${n.name} session to pick up the new version`))}}function G9(){let t=Ze(),e=[Q(Pi(),"bin","statusline.mjs"),Q(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let r=Q(t,"plugins","installed_plugins.json");if(Ve(r)){let o=Q(t,"plugins","cache"),s;try{s=Wd(o)}catch{s=o}let i=s+Yn,c=JSON.parse(Xn(r,"utf-8"))?.plugins?.[it];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+Yn).startsWith(i))continue;let p;try{p=Wd(d)}catch{continue}(p+Yn).startsWith(i)&&e.push(Q(p,"bin","statusline.mjs"))}}}catch{}let n=e.find(r=>Ve(r));n||process.exit(0),import(Gd(n).href).catch(()=>{process.exit(0)})}export{Kte as npmExec,qd as npmExecFile,j9 as openInBrowser,Wte as toUnixPath};
|