context-mode 1.0.146 → 1.0.148
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 +2 -2
- 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 +26 -23
- package/bin/statusline.mjs +22 -9
- package/build/adapters/base.d.ts +9 -4
- package/build/adapters/base.js +16 -7
- package/build/adapters/codex/index.d.ts +8 -1
- package/build/adapters/codex/index.js +43 -6
- package/build/adapters/openclaw/index.d.ts +11 -2
- package/build/adapters/openclaw/index.js +12 -3
- package/build/adapters/pi/mcp-bridge.d.ts +8 -0
- package/build/adapters/pi/mcp-bridge.js +118 -15
- package/build/adapters/types.d.ts +11 -2
- package/build/cli.d.ts +2 -0
- package/build/cli.js +87 -20
- package/build/search/auto-memory.d.ts +6 -1
- package/build/search/auto-memory.js +11 -2
- package/build/server.js +346 -106
- package/build/session/analytics.d.ts +19 -0
- package/build/session/analytics.js +71 -21
- package/build/session/db.d.ts +81 -0
- package/build/session/db.js +282 -20
- package/build/session/extract.js +16 -0
- package/build/truncate.d.ts +15 -0
- package/build/truncate.js +28 -0
- package/cli.bundle.mjs +435 -350
- package/hooks/core/routing.mjs +4 -4
- package/hooks/routing-block.mjs +18 -23
- package/hooks/session-db.bundle.mjs +21 -19
- package/hooks/session-extract.bundle.mjs +2 -2
- package/hooks/session-helpers.mjs +13 -2
- package/hooks/session-snapshot.bundle.mjs +7 -7
- package/openclaw.plugin.json +1 -1
- package/package.json +4 -2
- package/server.bundle.mjs +383 -300
package/cli.bundle.mjs
CHANGED
|
@@ -1,42 +1,162 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
2
|
+
var xP=Object.create;var Jl=Object.defineProperty;var SP=Object.getOwnPropertyDescriptor;var kP=Object.getOwnPropertyNames;var wP=Object.getPrototypeOf,EP=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Le=(t,e)=>{for(var r in e)Jl(t,r,{get:e[r],enumerable:!0})},$P=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kP(e))!EP.call(t,o)&&o!==r&&Jl(t,o,{get:()=>e[o],enumerable:!(n=SP(e,o))||n.enumerable});return t};var Ys=(t,e,r)=>(r=t!=null?xP(wP(t)):{},$P(e||!t||!t.__esModule?Jl(r,"default",{value:t,enumerable:!0}):r,t));var nd=D((aZ,D_)=>{"use strict";var rd={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let r="";return t<0?r+=`\x1B[${-t}D`:t>0&&(r+=`\x1B[${t}C`),e<0?r+=`\x1B[${-e}A`:e>0&&(r+=`\x1B[${e}B`),r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},MP={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},jP={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?rd.up():"");return t&&(e+=rd.left),e}};D_.exports={cursor:rd,scroll:MP,erase:jP,beep:"\x07"}});var H_=D((ZZ,ud)=>{var Ga=process||{},F_=Ga.argv||[],Wa=Ga.env||{},cR=!(Wa.NO_COLOR||F_.includes("--no-color"))&&(!!Wa.FORCE_COLOR||F_.includes("--color")||Ga.platform==="win32"||(Ga.stdout||{}).isTTY&&Wa.TERM!=="dumb"||!!Wa.CI),uR=(t,e,r=t)=>n=>{let o=""+n,s=o.indexOf(e,t.length);return~s?t+lR(o,e,r,s)+e:t+o+e},lR=(t,e,r,n)=>{let o="",s=0;do o+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return o+t.substring(s)},U_=(t=cR)=>{let e=t?uR:()=>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")}};ud.exports=U_();ud.exports.createColors=U_});import{execFileSync as B_,execSync as ei}from"node:child_process";import{existsSync as Ka}from"node:fs";function dd(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function pR(t){return dR.test(dd(t))}function et(t){try{let e=ti?`where ${t}`:`command -v ${t}`;return ei(e,{stdio:"pipe"}),!0}catch{return!1}}function ld(t){if(ti)try{let r=ei(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!et(t))return!1;try{return ti?ei(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):B_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function q_(){if(et("bun"))return!0;for(let t of V_())if(Ka(t))return!0;return!1}function mR(){for(let e of V_())if(Ka(e))return e;if(et("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return ti?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function V_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(ti){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function fR(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(Ka(e))return e;try{let r=ei("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Ht(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return ei(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return B_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Lo(){let e=q_()?mR():null,r=process.env.SHELL,n=r&&Ka(r)&&pR(r)?r:null,o=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(et("tsx")?"tsx":et("ts-node")?"ts-node":null),python:ld("python3")?"python3":ld("python")?"python":ld("py")?"py":null,shell:n??(o?fR()??(et("sh")?"sh":et("powershell")?"powershell":"cmd.exe"):et("bash")?"bash":"sh"),ruby:et("ruby")?"ruby":null,go:et("go")?"go":null,rust:et("rustc")?"rustc":null,php:et("php")?"php":null,perl:et("perl")?"perl":null,r:et("Rscript")?"Rscript":et("r")?"r":null,elixir:et("elixir")?"elixir":null,csharp:et("dotnet-script")?"dotnet-script":null}}function Hn(){return q_()}function Ja(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Ht(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Ht(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Ht(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Ht(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Ht(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Ht(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Ht(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Ht(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Ht(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Ht(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Ht(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Ht(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
|
|
3
|
+
`)}function Ya(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 W_(t,e,r){switch(e){case"javascript":return Z_.test(dd(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Z_.test(dd(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let s=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${s}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var dR,Z_,ti,Xa=x(()=>{"use strict";dR=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Z_=/^bun(\.exe)?$/i;ti=process.platform==="win32"});function Fe(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function Qa(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}var cn=x(()=>{"use strict"});function hR(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function gR(t){let e=Qa(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function ec(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of hR(s)){let a=gR(i);a&&r.add(a)}return[...r]}var pd=x(()=>{"use strict";cn()});var G_,K_=x(()=>{"use strict";G_={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});var hd={};Le(hd,{BunSQLiteAdapter:()=>tc,NodeSQLiteAdapter:()=>rc,SQLiteBase:()=>ni,applyWALPragmas:()=>Uo,cleanOrphanedWALFiles:()=>Ho,closeDB:()=>Zo,defaultDBPath:()=>fd,deleteDBFiles:()=>nc,hasModernSqlite:()=>X_,isSQLiteCorruptionError:()=>oc,loadDatabase:()=>Xe,nodeSqliteHasFts5:()=>Y_,renameCorruptDB:()=>Q_,withRetry:()=>un});import{createRequire as yR}from"node:module";import{existsSync as _R,unlinkSync as J_,renameSync as vR}from"node:fs";import{tmpdir as bR}from"node:os";import{join as xR}from"node:path";function Y_(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 X_(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function Xe(){if(!Fo){let t=yR(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Fo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new tc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(X_()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&Y_(e)?Fo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new rc(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Fo=t("better-sqlite3")}else Fo=t("better-sqlite3")}return Fo}function Uo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Ho(t){if(!_R(t))for(let e of["-wal","-shm"])try{J_(t+e)}catch{}}function nc(t){for(let e of["","-wal","-shm"])try{J_(t+e)}catch{}}function Zo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function fd(t="context-mode"){return xR(bR(),`${t}-${process.pid}.db`)}function un(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function oc(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 Q_(t){let e=Date.now();for(let r of["","-wal","-shm"])try{vR(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var tc,rc,Fo,ri,md,ni,ln=x(()=>{"use strict";tc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},rc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Fo=null;ri=Symbol.for("__context_mode_live_dbs_v3__"),md=(()=>{let t=globalThis;return t[ri]||(t[ri]=new Set,process.on("exit",()=>{for(let e of t[ri])Zo(e);t[ri].clear()})),t[ri]})(),ni=class{#e;#t;constructor(e){let r=Xe();this.#e=e,Ho(e);let n;try{n=new r(e,{timeout:3e4}),Uo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(oc(s)){Q_(e),Ho(e);try{n=new r(e,{timeout:3e4}),Uo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,md.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){md.delete(this.#t),Zo(this.#t)}withRetry(e){return un(e)}cleanup(){md.delete(this.#t),Zo(this.#t),nc(this.#e)}}});import{createHash as si}from"node:crypto";import{execFileSync as SR}from"node:child_process";import{accessSync as kR,constants as wR,existsSync as ic,mkdirSync as ER,realpathSync as $R,renameSync as yd}from"node:fs";import{homedir as sv}from"node:os";import{dirname as TR,isAbsolute as iv,join as dn,resolve as Bo}from"node:path";function _d(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):dn(PR(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function PR(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?tv(n.trim()):tv(t,sv())}function tv(t,e){return t.startsWith("~")?Bo(sv(),t.replace(/^~[/\\]?/,"")):iv(t)?Bo(t):e?Bo(e,t):Bo(t)}function RR(t,e,r){return new ar(t,e,$r,void 0,[`Invalid ${$r} for context-mode ${t} directory: ${r}`,lv()].join(`
|
|
4
|
+
`))}function cv(t){let e=process.env[$r];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:$r,ignoredReason:"empty"};if(!iv(r))throw RR(t,r,`${$r} must be an absolute path.`);return{kind:"override",root:Bo(r)}}function CR(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function uv(t,e){let r=cv(t);return r.kind!=="override"?null:{kind:t,path:dn(r.root,e),envVar:$r,source:"override"}}function OR(t,e,r){return{kind:t,path:Bo(e()),envVar:null,source:"default",...r}}function pn(t){let e=cv("session");return e.kind==="override"?{kind:"session",path:dn(e.root,av),envVar:$r,source:"override"}:OR("session",t,CR(e))}function qo(t){let e=uv("content",ev);if(e)return e;let r=pn(t);return{kind:"content",path:dn(TR(r.path),ev),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function ii(t){let e=uv("stats",av);if(e)return e;let r=pn(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function ai(t){return t.message}function ac(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function mn(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=gd.get(e);if(r instanceof ar)throw r;if(r===t.path)return r;try{return ER(t.path,{recursive:!0}),kR(t.path,wR.W_OK),gd.set(e,t.path),t.path}catch(n){let o=new ar(t.kind,NR(n)??t.path,$r,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw gd.set(e,o),o}}function IR(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,AR(r),lv()].filter(Boolean).join(`
|
|
5
|
+
`)}function AR(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function lv(){return`Set ${$r} to a writable absolute path.`}function NR(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function ci(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function rv(t){let e=t;try{e=$R.native(t)}catch{}let r=ci(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function dv(t,e){return SR("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function DR(t){let e=dv(t,["rev-parse","--show-toplevel"]);return e.length>0?ci(e):null}function MR(t){let e=dv(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?ci(e):null}function cc(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(oi&&oi.projectDir===t&&oi.envSuffix===e)return oi.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=DR(t),o=MR(t);if(n&&o){let s=rv(n),i=rv(o);s!==i&&(r=`__${si("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return oi={projectDir:t,envSuffix:e,suffix:r},r}function Ur(t){return si("sha256").update(ci(t)).digest("hex").slice(0,16)}function ht(t){let e=ci(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return si("sha256").update(r).digest("hex").slice(0,16)}function pv(t){let{projectDir:e,contentDir:r}=t,n=ht(e),o=dn(r,`${n}.db`);if(ic(o))return o;let s=Ur(e);if(s===n)return o;let i=dn(r,`${s}.db`);if(ic(i))try{yd(i,o);for(let a of["-wal","-shm"])try{yd(i+a,o+a)}catch{}}catch{}return o}function ui(t){return jR({...t,ext:".db"})}function jR(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??cc(e),s=ht(e),i=dn(r,`${s}${o}${n}`);if(ic(i))return i;let a=Ur(e);if(a===s)return i;let c=dn(r,`${a}${o}${n}`);if(ic(c))try{yd(c,i)}catch{}return i}function sc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function mv(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(o=>o.name)),n=!1;for(let[o,s]of zR)r.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function fv(t,e){let r=null;try{r=new e(t),mv(r)}catch{}finally{try{r?.close()}catch{}}}var $r,av,ev,ar,gd,oi,nv,ov,B,zR,cr,Tr=x(()=>{"use strict";ln();$r="CONTEXT_MODE_DIR",av="sessions",ev="content",ar=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=$r,o,s,i={}){super(s??IR(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},gd=new Map;nv=1e3,ov=5;B={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},zR=[["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"]];cr=class extends ni{constructor(e){super(e?.dbPath??fd("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
6
|
+
CREATE TABLE IF NOT EXISTS session_events (
|
|
7
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8
|
+
session_id TEXT NOT NULL,
|
|
9
|
+
type TEXT NOT NULL,
|
|
10
|
+
category TEXT NOT NULL,
|
|
11
|
+
priority INTEGER NOT NULL DEFAULT 2,
|
|
12
|
+
data TEXT NOT NULL,
|
|
13
|
+
project_dir TEXT NOT NULL DEFAULT '',
|
|
14
|
+
attribution_source TEXT NOT NULL DEFAULT 'unknown',
|
|
15
|
+
attribution_confidence REAL NOT NULL DEFAULT 0,
|
|
16
|
+
bytes_avoided INTEGER NOT NULL DEFAULT 0,
|
|
17
|
+
bytes_returned INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
source_hook TEXT NOT NULL,
|
|
19
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
20
|
+
data_hash TEXT NOT NULL DEFAULT ''
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_session ON session_events(session_id);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_type ON session_events(session_id, type);
|
|
25
|
+
CREATE INDEX IF NOT EXISTS idx_session_events_priority ON session_events(session_id, priority);
|
|
26
|
+
|
|
27
|
+
CREATE TABLE IF NOT EXISTS session_meta (
|
|
28
|
+
session_id TEXT PRIMARY KEY,
|
|
29
|
+
project_dir TEXT NOT NULL,
|
|
30
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
31
|
+
last_event_at TEXT,
|
|
32
|
+
event_count INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
compact_count INTEGER NOT NULL DEFAULT 0
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
CREATE TABLE IF NOT EXISTS session_resume (
|
|
37
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
38
|
+
session_id TEXT NOT NULL UNIQUE,
|
|
39
|
+
snapshot TEXT NOT NULL,
|
|
40
|
+
event_count INTEGER NOT NULL,
|
|
41
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
42
|
+
consumed INTEGER NOT NULL DEFAULT 0
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
CREATE TABLE IF NOT EXISTS tool_calls (
|
|
46
|
+
session_id TEXT NOT NULL,
|
|
47
|
+
tool TEXT NOT NULL,
|
|
48
|
+
calls INTEGER NOT NULL DEFAULT 0,
|
|
49
|
+
bytes_returned INTEGER NOT NULL DEFAULT 0,
|
|
50
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
51
|
+
PRIMARY KEY (session_id, tool)
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
55
|
+
`);try{mv(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(B.insertEvent,`INSERT INTO session_events (
|
|
56
|
+
session_id, type, category, priority, data,
|
|
57
|
+
project_dir, attribution_source, attribution_confidence,
|
|
58
|
+
bytes_avoided, bytes_returned,
|
|
59
|
+
source_hook, data_hash
|
|
60
|
+
)
|
|
61
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(B.getEvents,`SELECT id, session_id, type, category, priority, data,
|
|
62
|
+
project_dir, attribution_source, attribution_confidence,
|
|
63
|
+
bytes_avoided, bytes_returned,
|
|
64
|
+
source_hook, created_at, data_hash
|
|
65
|
+
FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByType,`SELECT id, session_id, type, category, priority, data,
|
|
66
|
+
project_dir, attribution_source, attribution_confidence,
|
|
67
|
+
bytes_avoided, bytes_returned,
|
|
68
|
+
source_hook, created_at, data_hash
|
|
69
|
+
FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
|
|
70
|
+
project_dir, attribution_source, attribution_confidence,
|
|
71
|
+
bytes_avoided, bytes_returned,
|
|
72
|
+
source_hook, created_at, data_hash
|
|
73
|
+
FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
|
|
74
|
+
project_dir, attribution_source, attribution_confidence,
|
|
75
|
+
bytes_avoided, bytes_returned,
|
|
76
|
+
source_hook, created_at, data_hash
|
|
77
|
+
FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(B.getLatestAttributedProject,`SELECT project_dir
|
|
78
|
+
FROM session_events
|
|
79
|
+
WHERE session_id = ? AND project_dir != ''
|
|
80
|
+
ORDER BY id DESC
|
|
81
|
+
LIMIT 1`),e(B.checkDuplicate,`SELECT 1 FROM (
|
|
82
|
+
SELECT type, data_hash FROM session_events
|
|
83
|
+
WHERE session_id = ? ORDER BY id DESC LIMIT ?
|
|
84
|
+
) AS recent
|
|
85
|
+
WHERE recent.type = ? AND recent.data_hash = ?
|
|
86
|
+
LIMIT 1`),e(B.evictLowestPriority,`DELETE FROM session_events WHERE id = (
|
|
87
|
+
SELECT id FROM session_events WHERE session_id = ?
|
|
88
|
+
ORDER BY priority ASC, id ASC LIMIT 1
|
|
89
|
+
)`),e(B.updateMetaLastEvent,`UPDATE session_meta
|
|
90
|
+
SET last_event_at = datetime('now'), event_count = event_count + 1
|
|
91
|
+
WHERE session_id = ?`),e(B.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(B.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
|
|
92
|
+
FROM session_meta WHERE session_id = ?`),e(B.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(B.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
|
|
93
|
+
VALUES (?, ?, ?)
|
|
94
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
95
|
+
snapshot = excluded.snapshot,
|
|
96
|
+
event_count = excluded.event_count,
|
|
97
|
+
created_at = datetime('now'),
|
|
98
|
+
consumed = 0`),e(B.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(B.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(B.claimLatestUnconsumedResume,`UPDATE session_resume
|
|
99
|
+
SET consumed = 1
|
|
100
|
+
WHERE id = (
|
|
101
|
+
SELECT id FROM session_resume
|
|
102
|
+
WHERE consumed = 0
|
|
103
|
+
AND session_id != ?
|
|
104
|
+
ORDER BY created_at DESC, id DESC
|
|
105
|
+
LIMIT 1
|
|
106
|
+
)
|
|
107
|
+
RETURNING session_id, snapshot`),e(B.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(B.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(B.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(B.searchEvents,`SELECT id, session_id, category, type, data, created_at
|
|
108
|
+
FROM session_events
|
|
109
|
+
WHERE (project_dir = ? OR project_dir = '')
|
|
110
|
+
AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
|
|
111
|
+
AND (? IS NULL OR category = ?)
|
|
112
|
+
ORDER BY id ASC
|
|
113
|
+
LIMIT ?`),e(B.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(B.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
|
|
114
|
+
VALUES (?, ?, 1, ?)
|
|
115
|
+
ON CONFLICT(session_id, tool) DO UPDATE SET
|
|
116
|
+
calls = calls + 1,
|
|
117
|
+
bytes_returned = bytes_returned + excluded.bytes_returned,
|
|
118
|
+
updated_at = datetime('now')`),e(B.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
|
|
119
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
120
|
+
FROM tool_calls WHERE session_id = ?`),e(B.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
121
|
+
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(B.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
122
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
123
|
+
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=si("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=sc(s?.bytesAvoided),m=sc(s?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(B.checkDuplicate).get(e,ov,r.type,i))return;this.stmt(B.getEventCount).get(e).cnt>=nv&&this.stmt(B.evictLowestPriority).run(e),this.stmt(B.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let d=si("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=o?.[u],m=String(l?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=s?.[u],y=sc(g?.bytesAvoided),v=sc(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:f,attributionConfidence:h,bytesAvoided:y,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(B.getEventCount).get(e).cnt;for(let u of i)this.stmt(B.checkDuplicate).get(e,ov,u.event.type,u.dataHash)||(c>=nv?this.stmt(B.evictLowestPriority).run(e):c++,this.stmt(B.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(B.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(B.getEventsByType).all(e,o,n):s!==void 0?this.stmt(B.getEventsByPriority).all(e,s,n):this.stmt(B.getEvents).all(e,n)}getEventCount(e){return this.stmt(B.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(B.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(B.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(B.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(B.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(B.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(B.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(B.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(B.getResume).get(e)??null}markResumeConsumed(e){this.stmt(B.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(B.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(B.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(B.getToolCallTotals).get(e),n=this.stmt(B.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(B.deleteEvents).run(e),this.stmt(B.deleteResume).run(e),this.stmt(B.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(B.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}}});import{join as Vo,resolve as hv}from"node:path";import{accessSync as LR,copyFileSync as FR,constants as UR,mkdirSync as HR}from"node:fs";import{homedir as vd}from"node:os";function ur(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?hv(vd(),e.replace(/^~[/\\]?/,"")):hv(e)}var Se,gt=x(()=>{"use strict";Tr();Se=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=ur(),r=e?Vo(e,"context-mode","sessions"):Vo(vd(),...this.sessionDirSegments,"context-mode","sessions");return HR(r,{recursive:!0}),r}getConfigDir(e){return Vo(vd(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=ur(),n=r?Vo(r,"context-mode","memory"):Vo(this.getConfigDir(),"memory");return e?Vo(n,ht(e)):n}backupSettings(){let e=this.getSettingsPath();try{LR(e,UR.R_OK);let r=e+".bak";return FR(e,r),r}catch{return null}}}});var Wo,bd=x(()=>{"use strict";gt();Wo=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});async function ZR(){if(Go)return Go;if(li)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Go=n,Go}catch(n){e=n}return li=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return li=t instanceof Error?t.message:String(t),null}}function gv(t){if(Go){let e=Go.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}return li?{status:"FAIL",detail:`integrity helper unavailable: ${li}`}:{status:"FAIL",detail:"integrity helper not yet loaded"}}var Go,li,yv=x(()=>{"use strict";Go=null,li=null;ZR()});function di(t,e){let r=Zn[e],n=Sd(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Sd(t,e){if(e){let r=Zn[t];return Fe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function kd(t){let e=Qa(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function bv(t){let e=Object.values(Zn);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var lr,BR,xd,_v,qR,yB,Zn,vv,_B,xv=x(()=>{"use strict";cn();lr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},BR="mcp__",xd=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",BR],_v=xd.join("|"),qR=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],yB=qR.join("|"),Zn={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},vv=[lr.PRE_TOOL_USE,lr.SESSION_START],_B=[lr.POST_TOOL_USE,lr.PRE_COMPACT,lr.USER_PROMPT_SUBMIT]});var Ed={};Le(Ed,{ClaudeCodeAdapter:()=>wd});import{readFileSync as uc,writeFileSync as Sv,existsSync as kv,readdirSync as VR,chmodSync as WR,accessSync as GR,mkdirSync as KR,constants as JR}from"node:fs";import{resolve as lc,join as fn}from"node:path";import{homedir as wv}from"node:os";var wd,$d=x(()=>{"use strict";bd();gt();hn();yv();cn();xv();wd=class extends Wo{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return qe()}getSessionDir(){let e=ur(),r=e?fn(e,"context-mode","sessions"):fn(this.getConfigDir(),"context-mode","sessions");return KR(r,{recursive:!0}),r}getSettingsPath(){return fn(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Fe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...xd].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=uc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Sv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
124
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,lr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,lr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(Zn).map(([o,s])=>{let i=fn(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>kv(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>gv(e)};return[...r,n]}readPluginHooks(e){let r=[fn(e,"hooks","hooks.json"),fn(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=uc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>di(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>di(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=fn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(uc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),qe(),lc(wv(),".claude"),lc(wv(),".config","claude")]));for(let r of e){let n=lc(r,"plugins","cache","context-mode","context-mode");try{let s=VR(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let d=0;d<3;d++)if((c[d]??0)!==(u[d]??0))return(c[d]??0)-(u[d]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(l=>{let m=l;if(!bv(m))return!0;let f=m.hooks??[];return f.every(h=>!h.command||!kd(h.command))?!0:f.every(h=>{let g=h.command?kd(h.command):null;return g?kv(g):!0})}),d=c.length-u.length;d>0&&(n[a]=u,o.push(`Removed ${d} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&vv.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(Zn),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let h=p,g=h.hooks??[],y=g.length;h.hooks=g.filter(v=>!u(v.command)),m+=y-h.hooks.length}let f=l.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(m>0||f.length!==l.length)&&(n[d]=f,m>0&&o.push(`Removed ${m} duplicate ${d} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[lr.PRE_TOOL_USE,lr.SESSION_START];for(let a of i){let c=Sd(a,e);if(a===lr.PRE_TOOL_USE){let u={matcher:_v,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>di(m,a));l>=0?(d[l]=u,o.push(`Updated existing ${a} hook entry`)):(d.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=d}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},d=n[a];if(d&&Array.isArray(d)){let l=d.findIndex(m=>di(m,a));l>=0?(d[l]=u,o.push(`Updated existing ${a} hook entry`)):(d.push(u),o.push(`Added ${a} hook entry`)),n[a]=d}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Zn)){let o=lc(e,"hooks",n);try{GR(o,JR.R_OK),WR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=fn(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(uc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();Sv(n,JSON.stringify(o,null,2)+`
|
|
125
|
+
`,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Bn(t,e){let r=Td[t];return e&&r?Fe(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var $e,Ev,Td,CB,OB,$v=x(()=>{"use strict";cn();$e={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Ev="mcp__(?!.*context-mode)",Td={[$e.BEFORE_AGENT]:"beforeagent.mjs",[$e.BEFORE_TOOL]:"beforetool.mjs",[$e.AFTER_TOOL]:"aftertool.mjs",[$e.PRE_COMPRESS]:"precompress.mjs",[$e.SESSION_START]:"sessionstart.mjs"},CB=[$e.BEFORE_TOOL,$e.SESSION_START],OB=[$e.AFTER_TOOL,$e.PRE_COMPRESS]});var Pv={};Le(Pv,{GeminiCLIAdapter:()=>Rd});import{readFileSync as Pd,writeFileSync as Tv,mkdirSync as YR,accessSync as XR,chmodSync as QR,constants as eC}from"node:fs";import{resolve as pi,join as tC}from"node:path";import{homedir as dc}from"node:os";var Rd,Rv=x(()=>{"use strict";gt();$v();Rd=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return pi(dc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[$e.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Bn($e.BEFORE_AGENT,e)}]}],[$e.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|${Ev}`,hooks:[{type:"command",command:Bn($e.BEFORE_TOOL,e)}]}],[$e.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Bn($e.AFTER_TOOL,e)}]}],[$e.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Bn($e.PRE_COMPRESS,e)}]}],[$e.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Bn($e.SESSION_START,e)}]}]}}readSettings(){try{let e=Pd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=pi(dc(),".gemini");YR(r,{recursive:!0}),Tv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
126
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[$e.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=pi(dc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Pd(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:$e.BEFORE_AGENT},{name:$e.BEFORE_TOOL},{name:$e.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Bn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=tC(e,"hooks","gemini-cli");for(let o of Object.values(Td)){let s=pi(n,o);try{XR(s,eC.R_OK),QR(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=pi(dc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Pd(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),Tv(n,JSON.stringify(o,null,2)+`
|
|
127
|
+
`,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var qn,LB,FB,Cv=x(()=>{"use strict";qn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},LB=[qn.BEFORE,qn.AFTER],FB=[qn.COMPACTING]});var Iv={};Le(Iv,{OpenCodeAdapter:()=>Cd});import{readFileSync as Ov,writeFileSync as nC,mkdirSync as oC,copyFileSync as sC,accessSync as iC,constants as aC}from"node:fs";import{resolve as Zt,join as Hr}from"node:path";import{homedir as gn}from"node:os";function rC(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Cd,Av=x(()=>{"use strict";gt();Cv();Cd=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Zt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Zt("kilo.json"),Zt("kilo.jsonc"),Zt(".kilo","kilo.json"),Zt(".kilo","kilo.jsonc"),Zt(".kilocode","kilo.json"),Zt(".kilocode","kilo.jsonc"),Hr(gn(),".config","kilo","kilo.json"),Hr(gn(),".config","kilo","kilo.jsonc")]:[Zt("opencode.json"),Zt("opencode.jsonc"),Zt(".opencode","opencode.json"),Zt(".opencode","opencode.jsonc"),Hr(gn(),".config","opencode","opencode.json"),Hr(gn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=ur(),r=e?Hr(e,"context-mode","sessions"):Hr(this.getConfigDir(),"context-mode","sessions");return oC(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Hr(gn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Hr(gn(),".config"),Hr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[qn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[qn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[qn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(gn()))),n=null,o;for(let s of e)try{let i=Ov(s,"utf-8"),a=s.endsWith(".jsonc")?rC(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){nC(this.getSettingsPath(),JSON.stringify(e,null,2)+`
|
|
128
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=Zt(gn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(Ov(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{iC(this.settingsPath,aC.R_OK);let r=this.settingsPath+".bak";return sC(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Vn,WB,GB,Nv=x(()=>{"use strict";Vn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},WB=[Vn.TOOL_CALL_BEFORE,Vn.TOOL_CALL_AFTER],GB=[Vn.COMMAND_NEW]});var Dv={};Le(Dv,{OpenClawAdapter:()=>Nd});import{readFileSync as Od,writeFileSync as cC,copyFileSync as uC,accessSync as lC,constants as dC}from"node:fs";import{resolve as Zr,join as Id}from"node:path";import{homedir as Ad}from"node:os";var Nd,Mv=x(()=>{"use strict";gt();Nv();Nd=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Zr("openclaw.json")}getConfigDir(e){return Zr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Id(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[Vn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Vn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Vn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Zr("openclaw.json"),Zr(".openclaw","openclaw.json"),Id(Ad(),".openclaw","openclaw.json")];for(let r of e)try{let n=Od(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Zr("openclaw.json");cC(r,JSON.stringify(e,null,2)+`
|
|
129
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Zr(Ad(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Od(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Zr("node_modules","context-mode","package.json"),r=JSON.parse(Od(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Zr("openclaw.json"),Zr(".openclaw","openclaw.json"),Id(Ad(),".openclaw","openclaw.json")];for(let r of e)try{lC(r,dC.R_OK);let n=r+".bak";return uC(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as jv}from"node:os";import{resolve as Dd}from"node:path";function zv(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Dd(jv(),t.replace(/^~[/\\]?/,"")):Dd(t):Dd(jv(),".codex")}var Lv=x(()=>{"use strict"});var Bv={};Le(Bv,{CodexAdapter:()=>zd,probeCodexCliVersion:()=>Uv});import{execFileSync as pC}from"node:child_process";import{readFileSync as Ko,writeFileSync as Fv,accessSync as mC,copyFileSync as fC,constants as hC,mkdirSync as Md}from"node:fs";import{resolve as gC,dirname as jd,join as Wn}from"node:path";import{fileURLToPath as yC}from"node:url";function Uv(t=pC){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function Hv(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
|
|
130
|
+
`):null}function Zv(t){let e=Hv(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function bC(t){let e=Hv(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function xC(t){if(Zv(t))return{text:t,changed:!1};let e=t.includes(`\r
|
|
11
131
|
`)?`\r
|
|
12
132
|
`:`
|
|
13
|
-
`,r=t.split(/\r?\n/),n=r.findIndex(
|
|
14
|
-
`)?e:"";return{text:`${t}${
|
|
133
|
+
`,r=t.split(/\r?\n/),n=r.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(n===-1){let s=t.length>0&&!t.endsWith(`
|
|
134
|
+
`)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var _C,Gn,vC,zd,qv=x(()=>{"use strict";gt();Tr();Lv();_C="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__",Gn={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"},vC={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"]};zd=class extends Se{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return zv()}getSettingsPath(){return Wn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=ur(),r=e?Wn(e,"context-mode","sessions"):Wn(this.getConfigDir(),"context-mode","sessions");return Md(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=ur(),n=r?Wn(r,"context-mode","memories"):Wn(this.getConfigDir(),"memories");return e?Wn(n,ht(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:_C,hooks:[{type:"command",command:Gn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Gn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Gn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Gn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Gn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Gn.Stop}]}]}}readSettings(){try{return{_raw_toml:Ko(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=Uv();r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{let c=Ko(this.getSettingsPath(),"utf-8"),u=Zv(c),d=!u&&bC(c);r.push({check:"Codex hooks feature flag",status:u?"pass":"fail",message:u?`[features].hooks enabled in ${this.getSettingsPath()}`:d?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...u?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let o=this.readHooksConfig();if(!o.ok)return o.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):o.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${o.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${o.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!o.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig(""),i=Object.entries(s).map(([c,u])=>{let d=o.config.hooks?.[c],l=u[0],m=Array.isArray(d)&&d.some(p=>this.isExpectedHookEntry(c,p,l)),f=c==="PreCompact"?"warn":"fail";return{check:`${c} hook`,status:m?"pass":f,message:m?`${c} hook configured in ${this.getHooksPath()}`:c==="PreCompact"?`${c} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${c} hook missing or not pointing to context-mode`,fix:m?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),a=[];for(let c of Object.keys(s)){let u=o.config.hooks?.[c];if(!Array.isArray(u))continue;let d=u.filter(l=>this.isManagedContextModeEntry(c,l)).length;d>1&&a.push({check:`${c} duplicates`,status:"warn",message:`${d} context-mode entries found for ${c} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r.concat(i,a)}checkPluginRegistration(){try{let e=Ko(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o;if(r.ok)o=r.config;else if(r.reason==="missing")o={hooks:{}};else if(r.reason==="invalid_json"){let d=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${d}`),o={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let s=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:{},i=this.generateHookConfig(e);for(let[d,l]of Object.entries(i))this.upsertManagedHookEntry(s,d,l[0],n);n.length>0&&(o.hooks=s,this.writeHooksConfig(o),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=Ko(a,"utf-8")}catch{c=""}let u=xC(c);if(u.changed){let d=u.text.includes(`\r
|
|
15
135
|
`)?`\r
|
|
16
136
|
`:`
|
|
17
137
|
`,l=u.text.endsWith(`
|
|
18
|
-
`)?u.text:`${u.text}${d}`;
|
|
138
|
+
`)?u.text:`${u.text}${d}`;Md(jd(a),{recursive:!0}),Fv(a,l,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{mC(r,hC.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=gC(jd(yC(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Ko(e,"utf-8")}catch{return`# context-mode
|
|
19
139
|
|
|
20
|
-
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
|
|
21
|
-
`,"utf-8")}upsertManagedHookEntry(e,r,n,
|
|
22
|
-
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=OR(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Ga(n,s);try{PR(o,CR.R_OK),RR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function gv(t,e){if(!Ed[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Ht,Ed,uB,lB,yv=x(()=>{"use strict";Ht={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Ed={[Ht.PRE_TOOL_USE]:"pretooluse.mjs",[Ht.POST_TOOL_USE]:"posttooluse.mjs",[Ht.PRE_COMPACT]:"precompact.mjs",[Ht.SESSION_START]:"sessionstart.mjs"},uB=[Ht.PRE_TOOL_USE,Ht.SESSION_START],lB=[Ht.POST_TOOL_USE,Ht.PRE_COMPACT]});var vv={};Le(vv,{VSCodeCopilotAdapter:()=>Pd});import{readFileSync as $d,mkdirSync as _v,accessSync as IR,existsSync as AR,constants as NR}from"node:fs";import{resolve as js,join as Yo}from"node:path";import{homedir as Td}from"node:os";var Pd,bv=x(()=>{"use strict";wd();ht();yv();Pd=class extends Ms{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Ht,HOOK_SCRIPTS:Ed,buildHookCommand:gv};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.cwd()}getSessionDir(){let e=ar();if(e){let o=Yo(e,"context-mode","sessions");return _v(o,{recursive:!0}),o}let r=js(".github","context-mode","sessions"),n=Yo(Td(),".vscode","context-mode","sessions"),s=AR(js(".github"))?r:n;return _v(s,{recursive:!0}),s}getConfigDir(e){return js(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=js(".github","hooks");try{IR(n,NR.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=js(n,"context-mode.json");try{let o=$d(s,"utf-8"),a=JSON.parse(o).hooks;a?.[Ht.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Ht.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=js(".vscode","mcp.json"),r=$d(e,"utf-8"),s=JSON.parse(r).servers;return s&&Object.keys(s).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=[Yo(Td(),".vscode","extensions"),Yo(Td(),".vscode-insiders","extensions")];for(let r of e)try{let n=$d(Yo(r,"extensions.json"),"utf-8"),o=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(o&&typeof o.version=="string")return o.version}catch{continue}return"not installed"}}});function xv(t,e){if(!Rd[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Zt,Rd,_B,vB,Sv=x(()=>{"use strict";Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Rd={[Zt.PRE_TOOL_USE]:"pretooluse.mjs",[Zt.POST_TOOL_USE]:"posttooluse.mjs",[Zt.PRE_COMPACT]:"precompact.mjs",[Zt.SESSION_START]:"sessionstart.mjs"},_B=[Zt.PRE_TOOL_USE,Zt.SESSION_START],vB=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT]});var kv={};Le(kv,{JetBrainsCopilotAdapter:()=>Cd});import{readFileSync as DR}from"node:fs";import{resolve as MR}from"node:path";var Cd,wv=x(()=>{"use strict";wd();Sv();Cd=class extends Ms{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Zt,HOOK_SCRIPTS:Rd,buildHookCommand:xv};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 MR(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=DR(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Zt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),o?.[Zt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Xo(t,e){let r=Od[e],n=Bt(e);if("command"in t){let o=t.command??"";return r!=null&&o.includes(r)||o.includes(n)}return t.hooks?.some(o=>{let i=o.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Bt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,Od,jR,zR,Id,Ev,$v,Tv=x(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Od={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},jR="MCP:(?!ctx_)",zR=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",jR],Id=zR.join("|"),Ev=[_e.PRE_TOOL_USE],$v=[_e.POST_TOOL_USE]});var Iv={};Le(Iv,{CursorAdapter:()=>Ad});import{readFileSync as Ka,writeFileSync as LR,mkdirSync as FR,accessSync as Pv,chmodSync as UR,constants as Rv,existsSync as Cv,readdirSync as HR}from"node:fs";import{execSync as ZR}from"node:child_process";import{resolve as Hn,join as Zn}from"node:path";import{homedir as Ja}from"node:os";var Ov,Ad,Av=x(()=>{"use strict";ht();an();Tv();Ov="/Library/Application Support/Cursor/hooks.json",Ad=class extends ke{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Hn(".cursor","hooks.json")}getConfigDir(e){return Hn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Bt(_e.PRE_TOOL_USE),matcher:Id,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Bt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Bt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Bt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Bt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Ka(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();FR(Hn(".cursor"),{recursive:!0}),LR(r,JSON.stringify(e,null,2)+`
|
|
23
|
-
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let
|
|
140
|
+
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 Wn(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return fC(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Ko(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();Md(jd(r),{recursive:!0}),Fv(r,JSON.stringify(e,null,2)+`
|
|
141
|
+
`,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(Gn[e]??""),s=vC[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as Vv,writeFileSync as SC,mkdirSync as kC,accessSync as wC,chmodSync as EC,constants as $C}from"node:fs";import{resolve as pc,join as TC}from"node:path";var Jo,Ld=x(()=>{"use strict";gt();Jo=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return pc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=Vv(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=Vv(pc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();kC(pc(".github","hooks"),{recursive:!0}),SC(r,JSON.stringify(e,null,2)+`
|
|
142
|
+
`,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=TC(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=pc(n,o);try{wC(s,$C.R_OK),EC(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function Wv(t,e){if(!Fd[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Bt,Fd,hq,gq,Gv=x(()=>{"use strict";Bt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Fd={[Bt.PRE_TOOL_USE]:"pretooluse.mjs",[Bt.POST_TOOL_USE]:"posttooluse.mjs",[Bt.PRE_COMPACT]:"precompact.mjs",[Bt.SESSION_START]:"sessionstart.mjs"},hq=[Bt.PRE_TOOL_USE,Bt.SESSION_START],gq=[Bt.POST_TOOL_USE,Bt.PRE_COMPACT]});var Jv={};Le(Jv,{VSCodeCopilotAdapter:()=>Zd});import{readFileSync as Ud,mkdirSync as Kv,accessSync as PC,existsSync as RC,constants as CC}from"node:fs";import{resolve as Yo,join as mi}from"node:path";import{homedir as Hd}from"node:os";var Zd,Yv=x(()=>{"use strict";Ld();gt();Gv();Zd=class extends Jo{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Bt,HOOK_SCRIPTS:Fd,buildHookCommand:Wv};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.cwd()}getSessionDir(){let e=ur();if(e){let s=mi(e,"context-mode","sessions");return Kv(s,{recursive:!0}),s}let r=Yo(".github","context-mode","sessions"),n=mi(Hd(),".vscode","context-mode","sessions"),o=RC(Yo(".github"))?r:n;return Kv(o,{recursive:!0}),o}getConfigDir(e){return Yo(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=Yo(".github","hooks");try{PC(n,CC.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=Yo(n,"context-mode.json");try{let s=Ud(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Bt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Bt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=Yo(".vscode","mcp.json"),r=Ud(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[mi(Hd(),".vscode","extensions"),mi(Hd(),".vscode-insiders","extensions")];for(let r of e)try{let n=Ud(mi(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function Xv(t,e){if(!Bd[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,Bd,wq,Eq,Qv=x(()=>{"use strict";qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Bd={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},wq=[qt.PRE_TOOL_USE,qt.SESSION_START],Eq=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var eb={};Le(eb,{JetBrainsCopilotAdapter:()=>qd});import{readFileSync as OC}from"node:fs";import{resolve as IC}from"node:path";var qd,tb=x(()=>{"use strict";Ld();Qv();qd=class extends Jo{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Bd,buildHookCommand:Xv};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 IC(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=OC(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[qt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[qt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function fi(t,e){let r=Vd[e],n=Vt(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Vt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,Vd,AC,NC,Wd,rb,nb,ob=x(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Vd={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},AC="MCP:(?!ctx_)",NC=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",AC],Wd=NC.join("|"),rb=[_e.PRE_TOOL_USE],nb=[_e.POST_TOOL_USE]});var ub={};Le(ub,{CursorAdapter:()=>Gd});import{readFileSync as mc,writeFileSync as DC,mkdirSync as MC,accessSync as sb,chmodSync as jC,constants as ib,existsSync as ab,readdirSync as zC}from"node:fs";import{execSync as LC}from"node:child_process";import{resolve as Kn,join as Jn}from"node:path";import{homedir as fc}from"node:os";var cb,Gd,lb=x(()=>{"use strict";gt();hn();ob();cb="/Library/Application Support/Cursor/hooks.json",Gd=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Kn(".cursor","hooks.json")}getConfigDir(e){return Kn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Vt(_e.PRE_TOOL_USE),matcher:Wd,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Vt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Vt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Vt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Vt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=mc(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();MC(Kn(".cursor"),{recursive:!0}),DC(r,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of rb){let a=s[i],c=Array.isArray(a)&&a.some(u=>fi(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of nb){let a=s[i],c=Array.isArray(a)&&a.some(u=>fi(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}ab(cb)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>fi(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[Jn(fc(),".cursor","plugins","local"),Jn(fc(),".cursor","plugins","cache")],r=[];for(let n of e){try{sb(n,ib.F_OK)}catch{continue}let o=[];try{o=zC(n)}catch{continue}for(let s of o){let i=Jn(n,s,".cursor-plugin","plugin.json");try{let a=mc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Kn(".cursor","mcp.json"),Jn(fc(),".cursor","mcp.json")];for(let n of e)try{let o=mc(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return LC("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,_e.PRE_TOOL_USE,{type:"command",command:Vt(_e.PRE_TOOL_USE),matcher:Wd,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Vt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Vt(_e.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Vt(_e.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Vt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=Jn(e,"hooks","cursor");for(let o of Object.values(Vd)){let s=Kn(n,o);try{sb(s,ib.R_OK),jC(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Jn(fc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(cb),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=mc(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Kn(".claude","settings.json"),Kn(".claude","settings.local.json"),Jn(qe(),"settings.json")].some(r=>ab(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>fi(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var pb={};Le(pb,{AntigravityAdapter:()=>Jd});import{readFileSync as hc,writeFileSync as FC,mkdirSync as UC}from"node:fs";import{resolve as gc,dirname as db}from"node:path";import{fileURLToPath as HC}from"node:url";import{homedir as Kd}from"node:os";var Jd,mb=x(()=>{"use strict";gt();Jd=class extends Se{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 gc(Kd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return gc(Kd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=hc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();UC(db(r),{recursive:!0}),FC(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=hc(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=gc(Kd(),".gemini","extensions","context-mode","package.json");return JSON.parse(hc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=gc(db(HC(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return hc(e,"utf-8")}catch{return`# context-mode
|
|
24
144
|
|
|
25
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function
|
|
145
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function yc(t,e){let r=fb[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Xo(t,e){let r=fb[t];return e&&r?Fe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ue,fb,ZC,BC,Yd,Vq,Wq,hb=x(()=>{"use strict";cn();Ue={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},fb={[Ue.PRE_TOOL_USE]:"pretooluse.mjs",[Ue.POST_TOOL_USE]:"posttooluse.mjs",[Ue.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ue.AGENT_SPAWN]:"agentspawn.mjs"},ZC="@(?!context-mode/)",BC=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",ZC],Yd=BC.join("|"),Vq=[Ue.PRE_TOOL_USE,Ue.AGENT_SPAWN],Wq=[Ue.POST_TOOL_USE,Ue.USER_PROMPT_SUBMIT]});var vb={};Le(vb,{KiroAdapter:()=>Xd});import{readFileSync as Qo,writeFileSync as gb,mkdirSync as yb}from"node:fs";import{resolve as Yn,dirname as _b}from"node:path";import{fileURLToPath as qC}from"node:url";import{homedir as _c}from"node:os";var Xd,bb=x(()=>{"use strict";gt();hb();Xd=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return Yn(_c(),".kiro","settings","mcp.json")}getConfigDir(e){return Yn(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ue.PRE_TOOL_USE]:[{matcher:Yd,hooks:[{type:"command",command:Xo(Ue.PRE_TOOL_USE,e)}]}],[Ue.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Xo(Ue.POST_TOOL_USE,e)}]}],[Ue.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Xo(Ue.AGENT_SPAWN,e)}]}],[Ue.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Xo(Ue.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Qo(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();yb(_b(r),{recursive:!0}),gb(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Yn(_c(),".kiro","agents","default.json");try{let s=JSON.parse(Qo(n,"utf-8")).hooks??{};for(let i of[Ue.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>yc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Ue.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>yc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=Qo(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=Yn(_c(),".kiro","extensions","context-mode","package.json");return JSON.parse(Qo(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Yn(_c(),".kiro","agents"),o=Yn(n,"default.json");try{yb(n,{recursive:!0});let s={};try{s=JSON.parse(Qo(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ue.PRE_TOOL_USE,Yd],[Ue.POST_TOOL_USE,"*"],[Ue.AGENT_SPAWN,"*"],[Ue.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>yc(l,c))||(d.push({matcher:u,command:Xo(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,gb(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Yn(_b(qC(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Qo(e,"utf-8")}catch{return`# context-mode
|
|
26
146
|
|
|
27
|
-
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
|
|
147
|
+
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 kb={};Le(kb,{ZedAdapter:()=>ep});import{readFileSync as Qd,writeFileSync as VC,mkdirSync as WC}from"node:fs";import{resolve as xb,dirname as Sb}from"node:path";import{fileURLToPath as GC}from"node:url";import{homedir as KC}from"node:os";var ep,wb=x(()=>{"use strict";gt();ep=class extends Se{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 xb(KC(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Qd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();WC(Sb(r),{recursive:!0}),VC(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Qd(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=xb(Sb(GC(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Qd(e,"utf-8")}catch{return`# context-mode
|
|
28
148
|
|
|
29
|
-
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var
|
|
149
|
+
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var tp,Eb=x(()=>{"use strict";tp="mcp__(?!.*context-mode)"});var Pb={};Le(Pb,{QwenCodeAdapter:()=>rp});import{readFileSync as JC,writeFileSync as YC,existsSync as XC}from"node:fs";import{resolve as $b,join as QC}from"node:path";import{homedir as Tb}from"node:os";var rp,Rb=x(()=>{"use strict";bd();Eb();cn();rp=class extends Wo{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 $b(Tb(),".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",tp].join("|"),hooks:[{type:"command",command:Fe(`${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:Fe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=JC(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){YC(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(d=>{let m=d.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?XC(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",tp].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Fe(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,o.push(`Updated ${i} hook`)):(d.push(u),o.push(`Added ${i} hook`)),n[i]=d}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:$b(QC(Tb(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Cb={};Le(Cb,{OMPAdapter:()=>sp});import{readFileSync as np,writeFileSync as eO,mkdirSync as tO}from"node:fs";import{resolve as op,dirname as rO}from"node:path";import{homedir as nO}from"node:os";var sp,Ob=x(()=>{"use strict";gt();sp=class extends Se{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??op(nO(),".omp","agent")}getSettingsPath(){return op(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=np(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();tO(rO(r),{recursive:!0}),eO(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=np(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=op(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(np(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
30
150
|
|
|
31
|
-
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
|
|
151
|
+
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 Ib={};Le(Ib,{PiAdapter:()=>up});import{readFileSync as ip,writeFileSync as oO,mkdirSync as sO}from"node:fs";import{resolve as ap,dirname as iO}from"node:path";import{homedir as cp}from"node:os";var up,Ab=x(()=>{"use strict";gt();up=class extends Se{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 ap(cp(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=ip(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();sO(iO(r),{recursive:!0}),oO(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=ap(cp(),".pi","extensions","context-mode","package.json");try{return JSON.parse(ip(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=ap(cp(),".pi","extensions","context-mode","package.json");return JSON.parse(ip(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
|
|
32
152
|
|
|
33
|
-
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.`}}});var
|
|
34
|
-
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function
|
|
35
|
-
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:
|
|
36
|
-
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function
|
|
37
|
-
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function NC({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!Lr(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=Us(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let s;try{s=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}let o=s&&s.mcpServers;if(!o||typeof o!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=!1;for(let c of Object.values(o))if(!(!c||typeof c!="object"||!Array.isArray(c.args)))for(let u=0;u<c.args.length;u++){let d=c.args[u];if(typeof d!="string")continue;let l=d.replace(/\\/g,"/");if(!l.startsWith(i+"/"))continue;let m=l.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let p=m.slice(f+1),h=kt(r,p);h!==d&&(c.args[u]=h,a=!0)}if(!a)return{healed:[]};try{ni(t,JSON.stringify(s,null,2),"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:["claude-json-mcp-args"]}}function nc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=kt(t);if(!Lr(n))return{removed:r,skipped:"no-cache-root"};let[s,o]=e.split("@");if(!s||!o)return{removed:r,skipped:"bad-plugin-key"};let i=kt(n,s,o),a=n+ri;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!Lr(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=PC(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let d=kt(i,u);if(!d.startsWith(i+ri))continue;try{if(!CC(d).isDirectory())continue}catch{continue}let l=kt(d,".mcp.json");if(Lr(l))try{RC(l),r.push(l)}catch{}}return{removed:r}}var ib,Xd,Qd=x(()=>{"use strict";ib=/[/\\]context-mode-upgrade-\d+[/\\]/,Xd="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ae,ep,j,wr,si=x(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(ae||(ae={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ep||(ep={}));j=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wr=t=>{switch(typeof t){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(t)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(t)?j.array:t===null?j.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?j.promise:typeof Map<"u"&&t instanceof Map?j.map:typeof Set<"u"&&t instanceof Set?j.set:typeof Date<"u"&&t instanceof Date?j.date:j.object;default:return j.unknown}}});var O,jC,wt,sc=x(()=>{si();O=ae.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"]),jC=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),wt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ae.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};wt.create=t=>new wt(t)});var zC,Fr,tp=x(()=>{sc();si();zC=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===j.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ae.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ae.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case O.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case O.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=e.defaultError,ae.assertNever(t)}return{message:r}},Fr=zC});function LC(t){ub=t}function Hs(){return ub}var ub,oc=x(()=>{tp();ub=Fr});function D(t,e){let r=Hs(),n=oi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Fr?void 0:Fr].filter(s=>!!s)});t.common.issues.push(n)}var oi,FC,Xe,G,Vn,ut,ic,ac,ln,Zs,rp=x(()=>{oc();tp();oi=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},FC=[];Xe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return G;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return G;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},G=Object.freeze({status:"aborted"}),Vn=t=>({status:"dirty",value:t}),ut=t=>({status:"valid",value:t}),ic=t=>t.status==="aborted",ac=t=>t.status==="dirty",ln=t=>t.status==="valid",Zs=t=>typeof Promise<"u"&&t instanceof Promise});var lb=x(()=>{});var U,db=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function hb(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function nO(t){return new RegExp(`^${hb(t)}$`)}function gb(t){let e=`${fb}T${hb(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sO(t,e){return!!((e==="v4"||!e)&&JC.test(t)||(e==="v6"||!e)&&XC.test(t))}function oO(t,e){if(!VC.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function iO(t,e){return!!((e==="v4"||!e)&&YC.test(t)||(e==="v6"||!e)&&QC.test(t))}function aO(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Bs(t){if(t instanceof $t){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Et.create(Bs(n))}return new $t({...t._def,shape:()=>e})}else return t instanceof Zr?new Zr({...t._def,type:Bs(t.element)}):t instanceof Et?Et.create(Bs(t.unwrap())):t instanceof $r?$r.create(Bs(t.unwrap())):t instanceof Er?Er.create(t.items.map(e=>Bs(e))):t}function sp(t,e){let r=wr(t),n=wr(e);if(t===e)return{valid:!0,data:t};if(r===j.object&&n===j.object){let s=ae.objectKeys(e),o=ae.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=sp(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===j.array&&n===j.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=sp(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===j.date&&n===j.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function yb(t,e){return new ns({values:t,typeName:I.ZodEnum,...Q(e)})}function mb(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function _b(t,e={},r){return t?pn.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=mb(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=mb(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):pn.create()}var qt,pb,te,UC,HC,ZC,BC,qC,VC,WC,GC,KC,np,JC,YC,XC,QC,eO,tO,fb,rO,dn,Wn,Gn,Kn,Jn,qs,Yn,Xn,pn,Hr,ur,Vs,Zr,$t,Qn,Ur,cc,es,Er,uc,Ws,Gs,lc,ts,rs,ns,ss,mn,Vt,Et,$r,os,is,Ks,cO,ii,ai,as,uO,I,lO,vb,bb,dO,pO,xb,mO,fO,hO,gO,yO,_O,vO,bO,xO,op,SO,kO,wO,EO,$O,TO,PO,RO,CO,OO,IO,AO,NO,DO,MO,jO,zO,LO,FO,UO,HO,ZO,BO,qO,Sb=x(()=>{sc();oc();db();rp();si();qt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},pb=(t,e)=>{if(ln(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new wt(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return wr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Xe,ctx:{common:e.parent.common,data:e.data,parsedType:wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Zs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return pb(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ln(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ln(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Zs(s)?s:Promise.resolve(s));return pb(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:O.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Vt({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Et.create(this,this._def)}nullable(){return $r.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zr.create(this)}promise(){return mn.create(this,this._def)}or(e){return Qn.create([this,e],this._def)}and(e){return es.create(this,e,this._def)}transform(e){return new Vt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new os({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new ii({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new is({...Q(this._def),innerType:this,catchValue:r,typeName:I.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ai.create(this,e)}readonly(){return as.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},UC=/^c[^\s-]{8,}$/i,HC=/^[0-9a-z]+$/,ZC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,BC=/^[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,qC=/^[a-z0-9_-]{21}$/i,VC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,WC=/^[-+]?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)?)??$/,GC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,KC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",JC=/^(?:(?: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])$/,YC=/^(?:(?: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])$/,XC=/^(([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]))$/,QC=/^(([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])$/,eO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tO=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fb="((\\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])))",rO=new RegExp(`^${fb}$`);dn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let o=this._getOrReturnCtx(e);return D(o,{code:O.invalid_type,expected:j.string,received:o.parsedType}),G}let n=new Xe,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?D(s,{code:O.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&D(s,{code:O.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")GC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"email",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")np||(np=new RegExp(KC,"u")),np.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"emoji",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")BC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"uuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")qC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"nanoid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")UC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")HC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cuid2",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ZC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ulid",code:O.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),D(s,{validation:"url",code:O.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"regex",code:O.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?gb(o).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?rO.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?nO(o).test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{code:O.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?WC.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"duration",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?sO(e.data,o.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"ip",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?oO(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"jwt",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?iO(e.data,o.version)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"cidr",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?eO.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?tO.test(e.data)||(s=this._getOrReturnCtx(e,s),D(s,{validation:"base64url",code:O.invalid_string,message:o.message}),n.dirty()):ae.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:O.invalid_string,...U.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.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,...U.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,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...U.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...U.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...U.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...U.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...U.errToObj(r)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};dn.create=t=>new dn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});Wn=class t extends te{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)!==j.number){let o=this._getOrReturnCtx(e);return D(o,{code:O.invalid_type,expected:j.number,received:o.parsedType}),G}let n,s=new Xe;for(let o of this._def.checks)o.kind==="int"?ae.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:O.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?aO(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),D(n,{code:O.not_finite,message:o.message}),s.dirty()):ae.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ae.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Wn.create=t=>new Wn({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Gn=class t extends te{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)!==j.bigint)return this._getInvalidInput(e);let n,s=new Xe;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),D(n,{code:O.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):ae.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return D(r,{code:O.invalid_type,expected:j.bigint,received:r.parsedType}),G}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.toString(s)}]})}_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:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Gn.create=t=>new Gn({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Kn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.boolean,received:n.parsedType}),G}return ut(e.data)}};Kn.create=t=>new Kn({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});Jn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let o=this._getOrReturnCtx(e);return D(o,{code:O.invalid_type,expected:j.date,received:o.parsedType}),G}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return D(o,{code:O.invalid_date}),G}let n=new Xe,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:O.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),D(s,{code:O.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ae.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Jn.create=t=>new Jn({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});qs=class extends te{_parse(e){if(this._getType(e)!==j.symbol){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.symbol,received:n.parsedType}),G}return ut(e.data)}};qs.create=t=>new qs({typeName:I.ZodSymbol,...Q(t)});Yn=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.undefined,received:n.parsedType}),G}return ut(e.data)}};Yn.create=t=>new Yn({typeName:I.ZodUndefined,...Q(t)});Xn=class extends te{_parse(e){if(this._getType(e)!==j.null){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.null,received:n.parsedType}),G}return ut(e.data)}};Xn.create=t=>new Xn({typeName:I.ZodNull,...Q(t)});pn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return ut(e.data)}};pn.create=t=>new pn({typeName:I.ZodAny,...Q(t)});Hr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ut(e.data)}};Hr.create=t=>new Hr({typeName:I.ZodUnknown,...Q(t)});ur=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return D(r,{code:O.invalid_type,expected:j.never,received:r.parsedType}),G}};ur.create=t=>new ur({typeName:I.ZodNever,...Q(t)});Vs=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.void,received:n.parsedType}),G}return ut(e.data)}};Vs.create=t=>new Vs({typeName:I.ZodVoid,...Q(t)});Zr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==j.array)return D(r,{code:O.invalid_type,expected:j.array,received:r.parsedType}),G;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(D(r,{code:i?O.too_big:O.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(D(r,{code:O.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(D(r,{code:O.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new qt(r,i,r.path,a)))).then(i=>Xe.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new qt(r,i,r.path,a)));return Xe.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:U.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:U.toString(r)}})}nonempty(e){return this.min(1,e)}};Zr.create=(t,e)=>new Zr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});$t=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ae.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==j.object){let u=this._getOrReturnCtx(e);return D(u,{code:O.invalid_type,expected:j.object,received:u.parsedType}),G}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ur&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=o[u],l=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new qt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ur){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")a.length>0&&(D(s,{code:O.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new qt(s,l,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Xe.mergeObjectSync(n,u)):Xe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:U.errToObj(e).message??s}:{message:s}}}:{}})}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:I.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ae.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ae.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Bs(this)}partial(e){let r={};for(let n of ae.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ae.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Et;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return yb(ae.objectKeys(this.shape))}};$t.create=(t,e)=>new $t({shape:()=>t,unknownKeys:"strip",catchall:ur.create(),typeName:I.ZodObject,...Q(e)});$t.strictCreate=(t,e)=>new $t({shape:()=>t,unknownKeys:"strict",catchall:ur.create(),typeName:I.ZodObject,...Q(e)});$t.lazycreate=(t,e)=>new $t({shape:t,unknownKeys:"strip",catchall:ur.create(),typeName:I.ZodObject,...Q(e)});Qn=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new wt(a.ctx.common.issues));return D(r,{code:O.invalid_union,unionErrors:i}),G}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new wt(c));return D(r,{code:O.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};Qn.create=(t,e)=>new Qn({options:t,typeName:I.ZodUnion,...Q(e)});Ur=t=>t instanceof ts?Ur(t.schema):t instanceof Vt?Ur(t.innerType()):t instanceof rs?[t.value]:t instanceof ns?t.options:t instanceof ss?ae.objectValues(t.enum):t instanceof os?Ur(t._def.innerType):t instanceof Yn?[void 0]:t instanceof Xn?[null]:t instanceof Et?[void 0,...Ur(t.unwrap())]:t instanceof $r?[null,...Ur(t.unwrap())]:t instanceof ii||t instanceof as?Ur(t.unwrap()):t instanceof is?Ur(t._def.innerType):[],cc=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.object)return D(r,{code:O.invalid_type,expected:j.object,received:r.parsedType}),G;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(D(r,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Ur(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:I.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...Q(n)})}};es=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(ic(o)||ic(i))return G;let a=sp(o.value,i.value);return a.valid?((ac(o)||ac(i))&&r.dirty(),{status:r.value,value:a.data}):(D(n,{code:O.invalid_intersection_types}),G)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};es.create=(t,e,r)=>new es({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});Er=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return D(n,{code:O.invalid_type,expected:j.array,received:n.parsedType}),G;if(n.data.length<this._def.items.length)return D(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&n.data.length>this._def.items.length&&(D(n,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new qt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Xe.mergeArray(r,i)):Xe.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Er.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Er({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};uc=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.object)return D(n,{code:O.invalid_type,expected:j.object,received:n.parsedType}),G;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new qt(n,a,n.path,a)),value:i._parse(new qt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Xe.mergeObjectAsync(r,s):Xe.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof te?new t({keyType:e,valueType:r,typeName:I.ZodRecord,...Q(n)}):new t({keyType:dn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},Ws=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.map)return D(n,{code:O.invalid_type,expected:j.map,received:n.parsedType}),G;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new qt(n,a,n.path,[u,"key"])),value:o._parse(new qt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return G;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return G;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Ws.create=(t,e,r)=>new Ws({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});Gs=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return D(n,{code:O.invalid_type,expected:j.set,received:n.parsedType}),G;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(D(n,{code:O.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(D(n,{code:O.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return G;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new qt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:U.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gs.create=(t,e)=>new Gs({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});lc=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.function)return D(r,{code:O.invalid_type,expected:j.function,received:r.parsedType}),G;function n(a,c){return oi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hs(),Fr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function s(a,c){return oi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hs(),Fr].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof mn){let a=this;return ut(async function(...c){let u=new wt([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return ut(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new wt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new wt([s(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Er.create(e).rest(Hr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Er.create([]).rest(Hr.create()),returns:r||Hr.create(),typeName:I.ZodFunction,...Q(n)})}},ts=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ts.create=(t,e)=>new ts({getter:t,typeName:I.ZodLazy,...Q(e)});rs=class extends te{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return D(r,{received:r.data,code:O.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};rs.create=(t,e)=>new rs({value:t,typeName:I.ZodLiteral,...Q(e)});ns=class t extends te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return D(r,{expected:ae.joinValues(n),received:r.parsedType,code:O.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return D(r,{received:r.data,code:O.invalid_enum_value,options:n}),G}return ut(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};ns.create=yb;ss=class extends te{_parse(e){let r=ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let s=ae.objectValues(r);return D(n,{expected:ae.joinValues(s),received:n.parsedType,code:O.invalid_type}),G}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ae.objectValues(r);return D(n,{received:n.data,code:O.invalid_enum_value,options:s}),G}return ut(e.data)}get enum(){return this._def.values}};ss.create=(t,e)=>new ss({values:t,typeName:I.ZodNativeEnum,...Q(e)});mn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.promise&&r.common.async===!1)return D(r,{code:O.invalid_type,expected:j.promise,received:r.parsedType}),G;let n=r.parsedType===j.promise?r.data:Promise.resolve(r.data);return ut(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};mn.create=(t,e)=>new mn({type:t,typeName:I.ZodPromise,...Q(e)});Vt=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{D(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?G:c.status==="dirty"?Vn(c.value):r.value==="dirty"?Vn(c.value):c});{if(r.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?G:a.status==="dirty"?Vn(a.value):r.value==="dirty"?Vn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?G:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?G:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ln(i))return G;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ln(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):G);ae.assertNever(s)}};Vt.create=(t,e,r)=>new Vt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});Vt.createWithPreprocess=(t,e,r)=>new Vt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});Et=class extends te{_parse(e){return this._getType(e)===j.undefined?ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:I.ZodOptional,...Q(e)});$r=class extends te{_parse(e){return this._getType(e)===j.null?ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$r.create=(t,e)=>new $r({innerType:t,typeName:I.ZodNullable,...Q(e)});os=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};os.create=(t,e)=>new os({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});is=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Zs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new wt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new wt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};is.create=(t,e)=>new is({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Ks=class extends te{_parse(e){if(this._getType(e)!==j.nan){let n=this._getOrReturnCtx(e);return D(n,{code:O.invalid_type,expected:j.nan,received:n.parsedType}),G}return{status:"valid",value:e.data}}};Ks.create=t=>new Ks({typeName:I.ZodNaN,...Q(t)});cO=Symbol("zod_brand"),ii=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ai=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?G:o.status==="dirty"?(r.dirty(),Vn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?G:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:I.ZodPipeline})}},as=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=s=>(ln(s)&&(s.value=Object.freeze(s.value)),s);return Zs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};as.create=(t,e)=>new as({innerType:t,typeName:I.ZodReadonly,...Q(e)});uO={object:$t.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"})(I||(I={}));lO=(t,e={message:`Input not instance of ${t.name}`})=>_b(r=>r instanceof t,e),vb=dn.create,bb=Wn.create,dO=Ks.create,pO=Gn.create,xb=Kn.create,mO=Jn.create,fO=qs.create,hO=Yn.create,gO=Xn.create,yO=pn.create,_O=Hr.create,vO=ur.create,bO=Vs.create,xO=Zr.create,op=$t.create,SO=$t.strictCreate,kO=Qn.create,wO=cc.create,EO=es.create,$O=Er.create,TO=uc.create,PO=Ws.create,RO=Gs.create,CO=lc.create,OO=ts.create,IO=rs.create,AO=ns.create,NO=ss.create,DO=mn.create,MO=Vt.create,jO=Et.create,zO=$r.create,LO=Vt.createWithPreprocess,FO=ai.create,UO=()=>vb().optional(),HO=()=>bb().optional(),ZO=()=>xb().optional(),BO={string:(t=>dn.create({...t,coerce:!0})),number:(t=>Wn.create({...t,coerce:!0})),boolean:(t=>Kn.create({...t,coerce:!0})),bigint:(t=>Gn.create({...t,coerce:!0})),date:(t=>Jn.create({...t,coerce:!0}))},qO=G});var F={};Le(F,{BRAND:()=>cO,DIRTY:()=>Vn,EMPTY_PATH:()=>FC,INVALID:()=>G,NEVER:()=>qO,OK:()=>ut,ParseStatus:()=>Xe,Schema:()=>te,ZodAny:()=>pn,ZodArray:()=>Zr,ZodBigInt:()=>Gn,ZodBoolean:()=>Kn,ZodBranded:()=>ii,ZodCatch:()=>is,ZodDate:()=>Jn,ZodDefault:()=>os,ZodDiscriminatedUnion:()=>cc,ZodEffects:()=>Vt,ZodEnum:()=>ns,ZodError:()=>wt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>lc,ZodIntersection:()=>es,ZodIssueCode:()=>O,ZodLazy:()=>ts,ZodLiteral:()=>rs,ZodMap:()=>Ws,ZodNaN:()=>Ks,ZodNativeEnum:()=>ss,ZodNever:()=>ur,ZodNull:()=>Xn,ZodNullable:()=>$r,ZodNumber:()=>Wn,ZodObject:()=>$t,ZodOptional:()=>Et,ZodParsedType:()=>j,ZodPipeline:()=>ai,ZodPromise:()=>mn,ZodReadonly:()=>as,ZodRecord:()=>uc,ZodSchema:()=>te,ZodSet:()=>Gs,ZodString:()=>dn,ZodSymbol:()=>qs,ZodTransformer:()=>Vt,ZodTuple:()=>Er,ZodType:()=>te,ZodUndefined:()=>Yn,ZodUnion:()=>Qn,ZodUnknown:()=>Hr,ZodVoid:()=>Vs,addIssueToContext:()=>D,any:()=>yO,array:()=>xO,bigint:()=>pO,boolean:()=>xb,coerce:()=>BO,custom:()=>_b,date:()=>mO,datetimeRegex:()=>gb,defaultErrorMap:()=>Fr,discriminatedUnion:()=>wO,effect:()=>MO,enum:()=>AO,function:()=>CO,getErrorMap:()=>Hs,getParsedType:()=>wr,instanceof:()=>lO,intersection:()=>EO,isAborted:()=>ic,isAsync:()=>Zs,isDirty:()=>ac,isValid:()=>ln,late:()=>uO,lazy:()=>OO,literal:()=>IO,makeIssue:()=>oi,map:()=>PO,nan:()=>dO,nativeEnum:()=>NO,never:()=>vO,null:()=>gO,nullable:()=>zO,number:()=>bb,object:()=>op,objectUtil:()=>ep,oboolean:()=>ZO,onumber:()=>HO,optional:()=>jO,ostring:()=>UO,pipeline:()=>FO,preprocess:()=>LO,promise:()=>DO,quotelessJson:()=>jC,record:()=>TO,set:()=>RO,setErrorMap:()=>LC,strictObject:()=>SO,string:()=>vb,symbol:()=>fO,transformer:()=>MO,tuple:()=>$O,undefined:()=>hO,union:()=>kO,unknown:()=>_O,util:()=>ae,void:()=>bO});var dc=x(()=>{oc();rp();lb();si();Sb();sc()});var ci=x(()=>{dc()});function E(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Nt(t){return t&&Object.assign(pc,t),pc}var WO,Br,pc,Js=x(()=>{WO=Object.freeze({status:"aborted"});Br=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},pc={}});var ce={};Le(ce,{BIGINT_FORMAT_RANGES:()=>wb,Class:()=>ap,NUMBER_FORMAT_RANGES:()=>fp,aborted:()=>us,allowsEval:()=>dp,assert:()=>XO,assertEqual:()=>GO,assertIs:()=>JO,assertNever:()=>YO,assertNotEqual:()=>KO,assignProp:()=>lp,cached:()=>di,captureStackTrace:()=>fc,cleanEnum:()=>dI,cleanRegex:()=>mi,clone:()=>Dt,createTransparentProxy:()=>sI,defineLazy:()=>we,esc:()=>cs,escapeRegex:()=>fn,extend:()=>aI,finalizeIssue:()=>lr,floatSafeRemainder:()=>up,getElementAtPath:()=>QO,getEnumValues:()=>li,getLengthableOrigin:()=>fi,getParsedType:()=>nI,getSizableOrigin:()=>Eb,isObject:()=>Ys,isPlainObject:()=>Xs,issue:()=>hp,joinValues:()=>mc,jsonStringifyReplacer:()=>cp,merge:()=>cI,normalizeParams:()=>K,nullish:()=>pi,numKeys:()=>rI,omit:()=>iI,optionalKeys:()=>mp,partial:()=>uI,pick:()=>oI,prefixIssues:()=>Tr,primitiveTypes:()=>kb,promiseAllObject:()=>eI,propertyKeyTypes:()=>pp,randomString:()=>tI,required:()=>lI,stringifyPrimitive:()=>hc,unwrapMessage:()=>ui});function GO(t){return t}function KO(t){return t}function JO(t){}function YO(t){throw new Error}function XO(t){}function li(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function mc(t,e="|"){return t.map(r=>hc(r)).join(e)}function cp(t,e){return typeof e=="bigint"?e.toString():e}function di(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function pi(t){return t==null}function mi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function up(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function we(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function lp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function QO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function eI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function tI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function cs(t){return JSON.stringify(t)}function Ys(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xs(t){if(Ys(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ys(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function rI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function fn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function K(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 sI(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function hc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function mp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function oI(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return Dt(t,{...t._zod.def,shape:r,checks:[]})}function iI(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return Dt(t,{...t._zod.def,shape:r,checks:[]})}function aI(t,e){if(!Xs(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return lp(this,"shape",n),n},checks:[]};return Dt(t,r)}function cI(t,e){return Dt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return lp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function uI(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return Dt(e,{...e._zod.def,shape:s,checks:[]})}function lI(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return Dt(e,{...e._zod.def,shape:s,checks:[]})}function us(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Tr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ui(t){return typeof t=="string"?t:t?.message}function lr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=ui(t.inst?._zod.def?.error?.(t))??ui(e?.error?.(t))??ui(r.customError?.(t))??ui(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Eb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function fi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function hp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function dI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var fc,dp,nI,pp,kb,fp,wb,ap,Pr=x(()=>{fc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};dp=di(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});nI=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}`)}},pp=new Set(["string","number","symbol"]),kb=new Set(["string","number","bigint","boolean","symbol","undefined"]);fp={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]},wb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ap=class{constructor(...e){}}});function gp(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function yp(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(t),n}var $b,gc,hi,_p=x(()=>{Js();Pr();$b=(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,cp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gc=E("$ZodError",$b),hi=E("$ZodError",$b,{Parent:Error})});var vp,bp,xp,Sp,kp,ls,wp,ds,Ep=x(()=>{Js();_p();Pr();vp=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Br;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>lr(c,o,Nt())));throw fc(a,s?.callee),a}return i.value},bp=vp(hi),xp=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>lr(c,o,Nt())));throw fc(a,s?.callee),a}return i.value},Sp=xp(hi),kp=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Br;return o.issues.length?{success:!1,error:new(t??gc)(o.issues.map(i=>lr(i,s,Nt())))}:{success:!0,data:o.value}},ls=kp(hi),wp=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>lr(i,s,Nt())))}:{success:!0,data:o.value}},ds=wp(hi)});function Mb(){return new RegExp(mI,"u")}function Vb(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 Wb(t){return new RegExp(`^${Vb(t)}$`)}function Gb(t){let e=Vb({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Bb}T(?:${n})$`)}var Tb,Pb,Rb,Cb,Ob,Ib,Ab,Nb,$p,Db,mI,jb,zb,Lb,Fb,Ub,Tp,Hb,Zb,Bb,qb,Kb,Jb,Yb,Xb,Qb,ex,tx,_c=x(()=>{Tb=/^[cC][^\s-]{8,}$/,Pb=/^[0-9a-z]+$/,Rb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Cb=/^[0-9a-vA-V]{20}$/,Ob=/^[A-Za-z0-9]{27}$/,Ib=/^[a-zA-Z0-9_-]{21}$/,Ab=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Nb=/^([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})$/,$p=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)$/,Db=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";jb=/^(?:(?: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])$/,zb=/^(([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})$/,Lb=/^((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])$/,Fb=/^(([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])$/,Ub=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tp=/^[A-Za-z0-9_-]*$/,Hb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Zb=/^\+(?:[0-9]){6,14}[0-9]$/,Bb="(?:(?:\\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])))",qb=new RegExp(`^${Bb}$`);Kb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Jb=/^\d+$/,Yb=/^-?\d+(?:\.\d+)?/i,Xb=/true|false/i,Qb=/null/i,ex=/^[^A-Z]*$/,tx=/^[^a-z]*$/});var Qe,rx,Pp,Rp,nx,sx,ox,ix,ax,gi,cx,ux,lx,dx,px,mx,fx,vc=x(()=>{Js();_c();Pr();Qe=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),rx={number:"number",bigint:"bigint",object:"date"},Pp=E("$ZodCheckLessThan",(t,e)=>{Qe.init(t,e);let r=rx[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Rp=E("$ZodCheckGreaterThan",(t,e)=>{Qe.init(t,e);let r=rx[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),nx=E("$ZodCheckMultipleOf",(t,e)=>{Qe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):up(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),sx=E("$ZodCheckNumberFormat",(t,e)=>{Qe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=fp[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=Jb)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),ox=E("$ZodCheckMaxLength",(t,e)=>{var r;Qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!pi(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=fi(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),ix=E("$ZodCheckMinLength",(t,e)=>{var r;Qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!pi(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=fi(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),ax=E("$ZodCheckLengthEquals",(t,e)=>{var r;Qe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!pi(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=fi(s),a=o>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),gi=E("$ZodCheckStringFormat",(t,e)=>{var r,n;Qe.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),cx=E("$ZodCheckRegex",(t,e)=>{gi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),ux=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ex),gi.init(t,e)}),lx=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=tx),gi.init(t,e)}),dx=E("$ZodCheckIncludes",(t,e)=>{Qe.init(t,e);let r=fn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),px=E("$ZodCheckStartsWith",(t,e)=>{Qe.init(t,e);let r=new RegExp(`^${fn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),mx=E("$ZodCheckEndsWith",(t,e)=>{Qe.init(t,e);let r=new RegExp(`.*${fn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),fx=E("$ZodCheckOverwrite",(t,e)=>{Qe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var bc,Cp=x(()=>{bc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
38
|
-
`).filter(i=>i),
|
|
39
|
-
`))}}});var
|
|
153
|
+
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.`}}});var vc={};Le(vc,{PLATFORM_ENV_VARS:()=>es,__resetClaudeCodePluginCacheForTests:()=>uO,__seedClaudeCodePluginCacheMissForTests:()=>lO,detectPlatform:()=>wt,foreignIdentificationEnv:()=>fO,foreignWorkspaceEnv:()=>mO,getAdapter:()=>gi,getEnvVarNames:()=>pO,getSessionDirSegments:()=>hi,workspaceEnvVarsFor:()=>lp});import{existsSync as Dt,readFileSync as aO}from"node:fs";import{resolve as kt}from"node:path";import{homedir as Nb}from"node:os";function cO(){if(Xn!==null)return Xn!=="miss"&&Xn.hasCM;try{let t=kt(Nb(),".claude","plugins","installed_plugins.json"),e=aO(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return Xn={hasCM:o},o}catch{return Xn="miss",!1}}function uO(){Xn=null}function lO(){Xn="miss"}function pO(t){return(es.get(t)??[]).map(e=>e.name)}function lp(t){return(es.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function mO(t){let e=new Set;for(let[r,n]of es)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function fO(t){let e=new Set;for(let[r,n]of es)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function hi(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function wt(t){if(t?.name){let n=G_[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of es)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&cO()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Nb();return Dt(kt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Dt(kt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Dt(kt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Dt(kt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Dt(kt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Dt(kt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Dt(kt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Dt(kt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Dt(kt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Dt(kt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Dt(kt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Dt(kt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Dt(kt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function gi(t){let e=t??wt().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>($d(),Ed));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(Rv(),Pv));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(Av(),Iv));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(Mv(),Dv));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(qv(),Bv));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(Yv(),Jv));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(tb(),eb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(lb(),ub));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(mb(),pb));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(bb(),vb));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(wb(),kb));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Rb(),Pb));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Ob(),Cb));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Ab(),Ib));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>($d(),Ed));return new r}}}var Xn,dO,es,yn=x(()=>{"use strict";K_();Xn=null;dO=[["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"}]]],es=new Map(dO)});import{resolve as yi}from"node:path";import{homedir as dp}from"node:os";function qe(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?yi(dp(),e.replace(/^~[/\\]?/,"")):yi(e):yi(dp(),".claude")}function hO(t=process.env){return yi(qe(t),"settings.json")}function pp(t=process.env){let e=[],r=wt();if(r.platform!=="claude-code"){let o=hi(r.platform);o&&o.length>0&&e.push(yi(dp(),...o,"settings.json"))}let n=hO(t);return e.includes(n)||e.push(n),e}var hn=x(()=>{"use strict";yn()});var zb={};Le(zb,{healClaudeJsonMcpArgs:()=>CO,healInstalledPlugins:()=>TO,healMcpJsonArgs:()=>RO,healPluginJsonMcpServers:()=>bc,healSettingsEnabledPlugins:()=>PO,sweepStaleMcpJson:()=>xc});import{existsSync as Br,readFileSync as ts,writeFileSync as vi,readdirSync as wO,unlinkSync as EO,statSync as $O}from"node:fs";import{resolve as Et,sep as _i}from"node:path";function TO({registryPath:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!Br(t))return{healed:[],skipped:"no-registry"};let n;try{n=ts(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!o||typeof o!="object")return{healed:[],error:"bad-shape"};let s=o.plugins&&o.plugins[r]||[];if(!Array.isArray(s)||s.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of s){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let d=Et(u),l=Et(e)+_i;if(!d.startsWith(l))continue;let m=Et(u,".claude-plugin","plugin.json");if(!Br(m))continue;let f=null;try{let p=JSON.parse(ts(m,"utf-8"));p&&typeof p.version=="string"&&p.version&&(f=p.version)}catch{continue}f&&(a=f,c.version!==f&&(c.version=f,i.includes("entry-version")||i.push("entry-version")))}if(a){(!o.enabledPlugins||typeof o.enabledPlugins!="object"||Array.isArray(o.enabledPlugins))&&(o.enabledPlugins={});let c=o.enabledPlugins[r];(c==null||c===!1||c==="")&&(o.enabledPlugins[r]=!0,i.push("enabled-plugins"))}if(i.length>0)try{vi(t,JSON.stringify(o,null,2)+`
|
|
154
|
+
`,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function PO({settingsPath:t,pluginKey:e}){if(!t||!Br(t))return{healed:[],skipped:"no-settings"};let r;try{r=ts(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let n;try{n=JSON.parse(r)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let o=[];(!n.enabledPlugins||typeof n.enabledPlugins!="object"||Array.isArray(n.enabledPlugins))&&(n.enabledPlugins={});let s=n.enabledPlugins[e];if(s===!1)return{healed:[],skipped:"explicit-opt-out"};if(s!==!0&&(n.enabledPlugins[e]=!0,o.push("enabled-plugins")),o.length>0)try{vi(t,JSON.stringify(n,null,2)+`
|
|
155
|
+
`,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:o}}function bc({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Et(t),o=Et(e)+_i;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=Et(t,".claude-plugin","plugin.json");if(!Br(s))return{healed:[],skipped:"no-plugin-json"};let i;try{i=ts(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=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,f=m.map(h=>typeof h!="string"?h:jb.test(h)&&/[/\\]start\.mjs$/.test(h)?mp:h);if(f.some((h,g)=>h!==m[g])){d.args=f,l.push("plugin-json-args");try{vi(s,JSON.stringify(a,null,2)+`
|
|
156
|
+
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function RO({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Et(t),o=Et(e)+_i;if(!n.startsWith(o))return{healed:[],skipped:"outside-cache-root"};let s=Et(t,".mcp.json");if(!Br(s))return{healed:[],skipped:"no-mcp-json"};let i;try{i=ts(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=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,f=m.map(h=>typeof h!="string"?h:h==="./start.mjs"||h==="start.mjs"||jb.test(h)&&/[/\\]start\.mjs$/.test(h)?mp:h);if(f.some((h,g)=>h!==m[g])){d.args=f,l.push("mcp-json-args");try{vi(s,JSON.stringify(a,null,2)+`
|
|
157
|
+
`,"utf-8")}catch(h){return{healed:[],error:`write-failed: ${h&&h.message||h}`}}}return{healed:l}}function CO({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!Br(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=ts(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let o;try{o=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}let s=o&&o.mcpServers;if(!s||typeof s!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=!1;for(let c of Object.values(s))if(!(!c||typeof c!="object"||!Array.isArray(c.args)))for(let u=0;u<c.args.length;u++){let d=c.args[u];if(typeof d!="string")continue;let l=d.replace(/\\/g,"/");if(!l.startsWith(i+"/"))continue;let m=l.slice(i.length+1),f=m.indexOf("/");if(f<0)continue;let p=m.slice(f+1),h=Et(r,p);h!==d&&(c.args[u]=h,a=!0)}if(!a)return{healed:[]};try{vi(t,JSON.stringify(o,null,2),"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:["claude-json-mcp-args"]}}function xc({pluginCacheRoot:t,pluginKey:e}){let r=[];if(!t||!e)return{removed:r,skipped:"missing-args"};let n=Et(t);if(!Br(n))return{removed:r,skipped:"no-cache-root"};let[o,s]=e.split("@");if(!o||!s)return{removed:r,skipped:"bad-plugin-key"};let i=Et(n,o,s),a=n+_i;if(!i.startsWith(a))return{removed:r,skipped:"outside-cache-root"};if(!Br(i))return{removed:r,skipped:"no-plugin-dir"};let c=[];try{c=wO(i)}catch{return{removed:r,skipped:"readdir-failed"}}for(let u of c){let d=Et(i,u);if(!d.startsWith(i+_i))continue;try{if(!$O(d).isDirectory())continue}catch{continue}let l=Et(d,".mcp.json");if(Br(l))try{EO(l),r.push(l)}catch{}}return{removed:r}}var jb,mp,fp=x(()=>{"use strict";jb=/[/\\]context-mode-upgrade-\d+[/\\]/,mp="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ce,hp,M,Pr,bi=x(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ce||(ce={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(hp||(hp={}));M=ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var O,AO,$t,Sc=x(()=>{bi();O=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"]),AO=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),$t=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};$t.create=t=>new $t(t)});var NO,qr,gp=x(()=>{Sc();bi();NO=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ce.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ce.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ce.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ce.joinValues(t.options)}, received '${t.received}'`;break;case O.invalid_arguments:r="Invalid function arguments";break;case O.invalid_return_type:r="Invalid function return type";break;case O.invalid_date:r="Invalid date";break;case O.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ce.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case O.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case O.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case O.custom:r="Invalid input";break;case O.invalid_intersection_types:r="Intersection results could not be merged";break;case O.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case O.not_finite:r="Number must be finite";break;default:r=e.defaultError,ce.assertNever(t)}return{message:r}},qr=NO});function DO(t){Fb=t}function rs(){return Fb}var Fb,kc=x(()=>{gp();Fb=qr});function N(t,e){let r=rs(),n=xi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===qr?void 0:qr].filter(o=>!!o)});t.common.issues.push(n)}var xi,MO,tt,K,Qn,ct,wc,Ec,_n,ns,yp=x(()=>{kc();gp();xi=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},MO=[];tt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return K;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return K;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},K=Object.freeze({status:"aborted"}),Qn=t=>({status:"dirty",value:t}),ct=t=>({status:"valid",value:t}),wc=t=>t.status==="aborted",Ec=t=>t.status==="dirty",_n=t=>t.status==="valid",ns=t=>typeof Promise<"u"&&t instanceof Promise});var Ub=x(()=>{});var U,Hb=x(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(U||(U={}))});function Q(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Vb(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function QO(t){return new RegExp(`^${Vb(t)}$`)}function Wb(t){let e=`${qb}T${Vb(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function eI(t,e){return!!((e==="v4"||!e)&&VO.test(t)||(e==="v6"||!e)&&GO.test(t))}function tI(t,e){if(!HO.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function rI(t,e){return!!((e==="v4"||!e)&&WO.test(t)||(e==="v6"||!e)&&KO.test(t))}function nI(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function os(t){if(t instanceof Pt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Tt.create(os(n))}return new Pt({...t._def,shape:()=>e})}else return t instanceof Gr?new Gr({...t._def,type:os(t.element)}):t instanceof Tt?Tt.create(os(t.unwrap())):t instanceof Cr?Cr.create(os(t.unwrap())):t instanceof Rr?Rr.create(t.items.map(e=>os(e))):t}function vp(t,e){let r=Pr(t),n=Pr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.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=vp(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.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=vp(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Gb(t,e){return new lo({values:t,typeName:I.ZodEnum,...Q(e)})}function Bb(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Kb(t,e={},r){return t?bn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Bb(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Bb(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):bn.create()}var Wt,Zb,te,jO,zO,LO,FO,UO,HO,ZO,BO,qO,_p,VO,WO,GO,KO,JO,YO,qb,XO,vn,eo,to,ro,no,ss,oo,so,bn,Wr,dr,is,Gr,Pt,io,Vr,$c,ao,Rr,Tc,as,cs,Pc,co,uo,lo,po,xn,Gt,Tt,Cr,mo,fo,us,oI,Si,ki,ho,sI,I,iI,Jb,Yb,aI,cI,Xb,uI,lI,dI,pI,mI,fI,hI,gI,yI,bp,_I,vI,bI,xI,SI,kI,wI,EI,$I,TI,PI,RI,CI,OI,II,AI,NI,DI,MI,jI,zI,LI,FI,UI,Qb=x(()=>{Sc();kc();Hb();yp();bi();Wt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Zb=(t,e)=>{if(_n(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new $t(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return Pr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tt,ctx:{common:e.parent.common,data:e.data,parsedType:Pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ns(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Zb(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return _n(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>_n(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ns(o)?o:Promise.resolve(o));return Zb(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:O.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Gt({schema:this,typeName:I.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Tt.create(this,this._def)}nullable(){return Cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gr.create(this)}promise(){return xn.create(this,this._def)}or(e){return io.create([this,e],this._def)}and(e){return ao.create(this,e,this._def)}transform(e){return new Gt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new mo({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new Si({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new fo({...Q(this._def),innerType:this,catchValue:r,typeName:I.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ki.create(this,e)}readonly(){return ho.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},jO=/^c[^\s-]{8,}$/i,zO=/^[0-9a-z]+$/,LO=/^[0-9A-HJKMNP-TV-Z]{26}$/i,FO=/^[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,UO=/^[a-z0-9_-]{21}$/i,HO=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ZO=/^[-+]?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)?)??$/,BO=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",VO=/^(?:(?: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])$/,WO=/^(?:(?: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])$/,GO=/^(([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]))$/,KO=/^(([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])$/,JO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,YO=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,qb="((\\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])))",XO=new RegExp(`^${qb}$`);vn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:M.string,received:s.parsedType}),K}let n=new tt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?N(o,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&N(o,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")BO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"email",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")_p||(_p=new RegExp(qO,"u")),_p.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"emoji",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")FO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"uuid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")UO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"nanoid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")jO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")zO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid2",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")LO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ulid",code:O.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),N(o,{validation:"url",code:O.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"regex",code:O.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Wb(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?XO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?QO(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:O.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ZO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"duration",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?eI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ip",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?tI(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"jwt",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?rI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cidr",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?JO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64",code:O.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?YO.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64url",code:O.invalid_string,message:s.message}),n.dirty()):ce.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:O.invalid_string,...U.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.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,...U.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,...U.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...U.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...U.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...U.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...U.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...U.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...U.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...U.errToObj(r)})}nonempty(e){return this.min(1,U.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};vn.create=t=>new vn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});eo=class t extends te{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)!==M.number){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:M.number,received:s.parsedType}),K}let n,o=new tt;for(let s of this._def.checks)s.kind==="int"?ce.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?nI(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_finite,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:U.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ce.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};eo.create=t=>new eo({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});to=class t extends te{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)!==M.bigint)return this._getInvalidInput(e);let n,o=new tt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),N(n,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ce.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.bigint,received:r.parsedType}),K}gte(e,r){return this.setLimit("min",e,!0,U.toString(r))}gt(e,r){return this.setLimit("min",e,!1,U.toString(r))}lte(e,r){return this.setLimit("max",e,!0,U.toString(r))}lt(e,r){return this.setLimit("max",e,!1,U.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:U.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:U.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:U.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};to.create=t=>new to({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});ro=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.boolean,received:n.parsedType}),K}return ct(e.data)}};ro.create=t=>new ro({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});no=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_type,expected:M.date,received:s.parsedType}),K}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return N(s,{code:O.invalid_date}),K}let n=new tt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),N(o,{code:O.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ce.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:U.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:U.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};no.create=t=>new no({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});ss=class extends te{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.symbol,received:n.parsedType}),K}return ct(e.data)}};ss.create=t=>new ss({typeName:I.ZodSymbol,...Q(t)});oo=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.undefined,received:n.parsedType}),K}return ct(e.data)}};oo.create=t=>new oo({typeName:I.ZodUndefined,...Q(t)});so=class extends te{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.null,received:n.parsedType}),K}return ct(e.data)}};so.create=t=>new so({typeName:I.ZodNull,...Q(t)});bn=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return ct(e.data)}};bn.create=t=>new bn({typeName:I.ZodAny,...Q(t)});Wr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ct(e.data)}};Wr.create=t=>new Wr({typeName:I.ZodUnknown,...Q(t)});dr=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:M.never,received:r.parsedType}),K}};dr.create=t=>new dr({typeName:I.ZodNever,...Q(t)});is=class extends te{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.void,received:n.parsedType}),K}return ct(e.data)}};is.create=t=>new is({typeName:I.ZodVoid,...Q(t)});Gr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==M.array)return N(r,{code:O.invalid_type,expected:M.array,received:r.parsedType}),K;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(N(r,{code:i?O.too_big:O.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(N(r,{code:O.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(N(r,{code:O.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Wt(r,i,r.path,a)))).then(i=>tt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Wt(r,i,r.path,a)));return tt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:U.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:U.toString(r)}})}nonempty(e){return this.min(1,e)}};Gr.create=(t,e)=>new Gr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});Pt=class t extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ce.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:M.object,received:u.parsedType}),K}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof dr&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=s[u],l=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Wt(o,l,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof dr){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")a.length>0&&(N(o,{code:O.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Wt(o,l,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>tt.mergeObjectSync(n,u)):tt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return U.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:U.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:I.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ce.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ce.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return os(this)}partial(e){let r={};for(let n of ce.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ce.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Tt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Gb(ce.objectKeys(this.shape))}};Pt.create=(t,e)=>new Pt({shape:()=>t,unknownKeys:"strip",catchall:dr.create(),typeName:I.ZodObject,...Q(e)});Pt.strictCreate=(t,e)=>new Pt({shape:()=>t,unknownKeys:"strict",catchall:dr.create(),typeName:I.ZodObject,...Q(e)});Pt.lazycreate=(t,e)=>new Pt({shape:t,unknownKeys:"strip",catchall:dr.create(),typeName:I.ZodObject,...Q(e)});io=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new $t(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),K}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new $t(c));return N(r,{code:O.invalid_union,unionErrors:a}),K}}get options(){return this._def.options}};io.create=(t,e)=>new io({options:t,typeName:I.ZodUnion,...Q(e)});Vr=t=>t instanceof co?Vr(t.schema):t instanceof Gt?Vr(t.innerType()):t instanceof uo?[t.value]:t instanceof lo?t.options:t instanceof po?ce.objectValues(t.enum):t instanceof mo?Vr(t._def.innerType):t instanceof oo?[void 0]:t instanceof so?[null]:t instanceof Tt?[void 0,...Vr(t.unwrap())]:t instanceof Cr?[null,...Vr(t.unwrap())]:t instanceof Si||t instanceof ho?Vr(t.unwrap()):t instanceof fo?Vr(t._def.innerType):[],$c=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return N(r,{code:O.invalid_type,expected:M.object,received:r.parsedType}),K;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(N(r,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Vr(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:I.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...Q(n)})}};ao=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(wc(s)||wc(i))return K;let a=vp(s.value,i.value);return a.valid?((Ec(s)||Ec(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),K)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ao.create=(t,e,r)=>new ao({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});Rr=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return N(n,{code:O.invalid_type,expected:M.array,received:n.parsedType}),K;if(n.data.length<this._def.items.length)return N(n,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&n.data.length>this._def.items.length&&(N(n,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Wt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>tt.mergeArray(r,i)):tt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Rr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Rr({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};Tc=class t extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return N(n,{code:O.invalid_type,expected:M.object,received:n.parsedType}),K;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Wt(n,a,n.path,a)),value:i._parse(new Wt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?tt.mergeObjectAsync(r,o):tt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof te?new t({keyType:e,valueType:r,typeName:I.ZodRecord,...Q(n)}):new t({keyType:vn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},as=class extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return N(n,{code:O.invalid_type,expected:M.map,received:n.parsedType}),K;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Wt(n,a,n.path,[u,"key"])),value:s._parse(new Wt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return K;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return K;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};as.create=(t,e,r)=>new as({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});cs=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return N(n,{code:O.invalid_type,expected:M.set,received:n.parsedType}),K;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(N(n,{code:O.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(N(n,{code:O.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return K;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Wt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:U.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:U.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};cs.create=(t,e)=>new cs({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});Pc=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return N(r,{code:O.invalid_type,expected:M.function,received:r.parsedType}),K;function n(a,c){return xi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,rs(),qr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function o(a,c){return xi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,rs(),qr].filter(u=>!!u),issueData:{code:O.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof xn){let a=this;return ct(async function(...c){let u=new $t([]),d=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,s).catch(f=>{throw u.addIssue(o(l,f)),u})})}else{let a=this;return ct(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new $t([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,s);if(!l.success)throw new $t([o(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Rr.create(e).rest(Wr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Rr.create([]).rest(Wr.create()),returns:r||Wr.create(),typeName:I.ZodFunction,...Q(n)})}},co=class extends te{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};co.create=(t,e)=>new co({getter:t,typeName:I.ZodLazy,...Q(e)});uo=class extends te{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(r,{received:r.data,code:O.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:e.data}}get value(){return this._def.value}};uo.create=(t,e)=>new uo({value:t,typeName:I.ZodLiteral,...Q(e)});lo=class t extends te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ce.joinValues(n),received:r.parsedType,code:O.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{received:r.data,code:O.invalid_enum_value,options:n}),K}return ct(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};lo.create=Gb;po=class extends te{_parse(e){let r=ce.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let o=ce.objectValues(r);return N(n,{expected:ce.joinValues(o),received:n.parsedType,code:O.invalid_type}),K}if(this._cache||(this._cache=new Set(ce.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ce.objectValues(r);return N(n,{received:n.data,code:O.invalid_enum_value,options:o}),K}return ct(e.data)}get enum(){return this._def.values}};po.create=(t,e)=>new po({values:t,typeName:I.ZodNativeEnum,...Q(e)});xn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:M.promise,received:r.parsedType}),K;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return ct(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};xn.create=(t,e)=>new xn({type:t,typeName:I.ZodPromise,...Q(e)});Gt=class extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{N(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return K;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?K:c.status==="dirty"?Qn(c.value):r.value==="dirty"?Qn(c.value):c});{if(r.value==="aborted")return K;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?K:a.status==="dirty"?Qn(a.value):r.value==="dirty"?Qn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?K:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?K:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_n(i))return K;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>_n(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):K);ce.assertNever(o)}};Gt.create=(t,e,r)=>new Gt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});Gt.createWithPreprocess=(t,e,r)=>new Gt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});Tt=class extends te{_parse(e){return this._getType(e)===M.undefined?ct(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Tt.create=(t,e)=>new Tt({innerType:t,typeName:I.ZodOptional,...Q(e)});Cr=class extends te{_parse(e){return this._getType(e)===M.null?ct(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cr.create=(t,e)=>new Cr({innerType:t,typeName:I.ZodNullable,...Q(e)});mo=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};mo.create=(t,e)=>new mo({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});fo=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ns(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new $t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};fo.create=(t,e)=>new fo({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});us=class extends te{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:M.nan,received:n.parsedType}),K}return{status:"valid",value:e.data}}};us.create=t=>new us({typeName:I.ZodNaN,...Q(t)});oI=Symbol("zod_brand"),Si=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ki=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?K:s.status==="dirty"?(r.dirty(),Qn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?K:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:I.ZodPipeline})}},ho=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=o=>(_n(o)&&(o.value=Object.freeze(o.value)),o);return ns(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};ho.create=(t,e)=>new ho({innerType:t,typeName:I.ZodReadonly,...Q(e)});sI={object:Pt.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"})(I||(I={}));iI=(t,e={message:`Input not instance of ${t.name}`})=>Kb(r=>r instanceof t,e),Jb=vn.create,Yb=eo.create,aI=us.create,cI=to.create,Xb=ro.create,uI=no.create,lI=ss.create,dI=oo.create,pI=so.create,mI=bn.create,fI=Wr.create,hI=dr.create,gI=is.create,yI=Gr.create,bp=Pt.create,_I=Pt.strictCreate,vI=io.create,bI=$c.create,xI=ao.create,SI=Rr.create,kI=Tc.create,wI=as.create,EI=cs.create,$I=Pc.create,TI=co.create,PI=uo.create,RI=lo.create,CI=po.create,OI=xn.create,II=Gt.create,AI=Tt.create,NI=Cr.create,DI=Gt.createWithPreprocess,MI=ki.create,jI=()=>Jb().optional(),zI=()=>Yb().optional(),LI=()=>Xb().optional(),FI={string:(t=>vn.create({...t,coerce:!0})),number:(t=>eo.create({...t,coerce:!0})),boolean:(t=>ro.create({...t,coerce:!0})),bigint:(t=>to.create({...t,coerce:!0})),date:(t=>no.create({...t,coerce:!0}))},UI=K});var L={};Le(L,{BRAND:()=>oI,DIRTY:()=>Qn,EMPTY_PATH:()=>MO,INVALID:()=>K,NEVER:()=>UI,OK:()=>ct,ParseStatus:()=>tt,Schema:()=>te,ZodAny:()=>bn,ZodArray:()=>Gr,ZodBigInt:()=>to,ZodBoolean:()=>ro,ZodBranded:()=>Si,ZodCatch:()=>fo,ZodDate:()=>no,ZodDefault:()=>mo,ZodDiscriminatedUnion:()=>$c,ZodEffects:()=>Gt,ZodEnum:()=>lo,ZodError:()=>$t,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>Pc,ZodIntersection:()=>ao,ZodIssueCode:()=>O,ZodLazy:()=>co,ZodLiteral:()=>uo,ZodMap:()=>as,ZodNaN:()=>us,ZodNativeEnum:()=>po,ZodNever:()=>dr,ZodNull:()=>so,ZodNullable:()=>Cr,ZodNumber:()=>eo,ZodObject:()=>Pt,ZodOptional:()=>Tt,ZodParsedType:()=>M,ZodPipeline:()=>ki,ZodPromise:()=>xn,ZodReadonly:()=>ho,ZodRecord:()=>Tc,ZodSchema:()=>te,ZodSet:()=>cs,ZodString:()=>vn,ZodSymbol:()=>ss,ZodTransformer:()=>Gt,ZodTuple:()=>Rr,ZodType:()=>te,ZodUndefined:()=>oo,ZodUnion:()=>io,ZodUnknown:()=>Wr,ZodVoid:()=>is,addIssueToContext:()=>N,any:()=>mI,array:()=>yI,bigint:()=>cI,boolean:()=>Xb,coerce:()=>FI,custom:()=>Kb,date:()=>uI,datetimeRegex:()=>Wb,defaultErrorMap:()=>qr,discriminatedUnion:()=>bI,effect:()=>II,enum:()=>RI,function:()=>$I,getErrorMap:()=>rs,getParsedType:()=>Pr,instanceof:()=>iI,intersection:()=>xI,isAborted:()=>wc,isAsync:()=>ns,isDirty:()=>Ec,isValid:()=>_n,late:()=>sI,lazy:()=>TI,literal:()=>PI,makeIssue:()=>xi,map:()=>wI,nan:()=>aI,nativeEnum:()=>CI,never:()=>hI,null:()=>pI,nullable:()=>NI,number:()=>Yb,object:()=>bp,objectUtil:()=>hp,oboolean:()=>LI,onumber:()=>zI,optional:()=>AI,ostring:()=>jI,pipeline:()=>MI,preprocess:()=>DI,promise:()=>OI,quotelessJson:()=>AO,record:()=>kI,set:()=>EI,setErrorMap:()=>DO,strictObject:()=>_I,string:()=>Jb,symbol:()=>lI,transformer:()=>II,tuple:()=>SI,undefined:()=>dI,union:()=>vI,unknown:()=>fI,util:()=>ce,void:()=>gI});var Rc=x(()=>{kc();yp();Ub();bi();Qb();Sc()});var wi=x(()=>{Rc()});function T(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Mt(t){return t&&Object.assign(Cc,t),Cc}var ZI,Kr,Cc,ls=x(()=>{ZI=Object.freeze({status:"aborted"});Kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Cc={}});var ue={};Le(ue,{BIGINT_FORMAT_RANGES:()=>tx,Class:()=>Sp,NUMBER_FORMAT_RANGES:()=>Rp,aborted:()=>yo,allowsEval:()=>$p,assert:()=>GI,assertEqual:()=>BI,assertIs:()=>VI,assertNever:()=>WI,assertNotEqual:()=>qI,assignProp:()=>Ep,cached:()=>Ti,captureStackTrace:()=>Ic,cleanEnum:()=>aA,cleanRegex:()=>Ri,clone:()=>jt,createTransparentProxy:()=>eA,defineLazy:()=>ke,esc:()=>go,escapeRegex:()=>Sn,extend:()=>nA,finalizeIssue:()=>pr,floatSafeRemainder:()=>wp,getElementAtPath:()=>KI,getEnumValues:()=>$i,getLengthableOrigin:()=>Ci,getParsedType:()=>QI,getSizableOrigin:()=>rx,isObject:()=>ds,isPlainObject:()=>ps,issue:()=>Cp,joinValues:()=>Oc,jsonStringifyReplacer:()=>kp,merge:()=>oA,normalizeParams:()=>J,nullish:()=>Pi,numKeys:()=>XI,omit:()=>rA,optionalKeys:()=>Pp,partial:()=>sA,pick:()=>tA,prefixIssues:()=>Or,primitiveTypes:()=>ex,promiseAllObject:()=>JI,propertyKeyTypes:()=>Tp,randomString:()=>YI,required:()=>iA,stringifyPrimitive:()=>Ac,unwrapMessage:()=>Ei});function BI(t){return t}function qI(t){return t}function VI(t){}function WI(t){throw new Error}function GI(t){}function $i(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Oc(t,e="|"){return t.map(r=>Ac(r)).join(e)}function kp(t,e){return typeof e=="bigint"?e.toString():e}function Ti(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Pi(t){return t==null}function Ri(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function wp(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Ep(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function KI(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function JI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function YI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function go(t){return JSON.stringify(t)}function ds(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ps(t){if(ds(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ds(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function XI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Sn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}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 eA(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ac(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Pp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function tA(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return jt(t,{...t._zod.def,shape:r,checks:[]})}function rA(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return jt(t,{...t._zod.def,shape:r,checks:[]})}function nA(t,e){if(!ps(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Ep(this,"shape",n),n},checks:[]};return jt(t,r)}function oA(t,e){return jt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ep(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function sA(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return jt(e,{...e._zod.def,shape:o,checks:[]})}function iA(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return jt(e,{...e._zod.def,shape:o,checks:[]})}function yo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Or(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ei(t){return typeof t=="string"?t:t?.message}function pr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ei(t.inst?._zod.def?.error?.(t))??Ei(e?.error?.(t))??Ei(r.customError?.(t))??Ei(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function rx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ci(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Cp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function aA(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ic,$p,QI,Tp,ex,Rp,tx,Sp,Ir=x(()=>{Ic=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};$p=Ti(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});QI=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}`)}},Tp=new Set(["string","number","symbol"]),ex=new Set(["string","number","bigint","boolean","symbol","undefined"]);Rp={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]},tx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Sp=class{constructor(...e){}}});function Op(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Ip(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var nx,Nc,Oi,Ap=x(()=>{ls();Ir();nx=(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,kp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Nc=T("$ZodError",nx),Oi=T("$ZodError",nx,{Parent:Error})});var Np,Dp,Mp,jp,zp,_o,Lp,vo,Fp=x(()=>{ls();Ap();Ir();Np=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>pr(c,s,Mt())));throw Ic(a,o?.callee),a}return i.value},Dp=Np(Oi),Mp=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>pr(c,s,Mt())));throw Ic(a,o?.callee),a}return i.value},jp=Mp(Oi),zp=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Kr;return s.issues.length?{success:!1,error:new(t??Nc)(s.issues.map(i=>pr(i,o,Mt())))}:{success:!0,data:s.value}},_o=zp(Oi),Lp=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>pr(i,o,Mt())))}:{success:!0,data:s.value}},vo=Lp(Oi)});function mx(){return new RegExp(uA,"u")}function kx(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 wx(t){return new RegExp(`^${kx(t)}$`)}function Ex(t){let e=kx({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${xx}T(?:${n})$`)}var ox,sx,ix,ax,cx,ux,lx,dx,Up,px,uA,fx,hx,gx,yx,_x,Hp,vx,bx,xx,Sx,$x,Tx,Px,Rx,Cx,Ox,Ix,Mc=x(()=>{ox=/^[cC][^\s-]{8,}$/,sx=/^[0-9a-z]+$/,ix=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ax=/^[0-9a-vA-V]{20}$/,cx=/^[A-Za-z0-9]{27}$/,ux=/^[a-zA-Z0-9_-]{21}$/,lx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dx=/^([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})$/,Up=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)$/,px=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";fx=/^(?:(?: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])$/,hx=/^(([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})$/,gx=/^((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])$/,yx=/^(([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])$/,_x=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hp=/^[A-Za-z0-9_-]*$/,vx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,bx=/^\+(?:[0-9]){6,14}[0-9]$/,xx="(?:(?:\\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])))",Sx=new RegExp(`^${xx}$`);$x=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Tx=/^\d+$/,Px=/^-?\d+(?:\.\d+)?/i,Rx=/true|false/i,Cx=/null/i,Ox=/^[^A-Z]*$/,Ix=/^[^a-z]*$/});var rt,Ax,Zp,Bp,Nx,Dx,Mx,jx,zx,Ii,Lx,Fx,Ux,Hx,Zx,Bx,qx,jc=x(()=>{ls();Mc();Ir();rt=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ax={number:"number",bigint:"bigint",object:"date"},Zp=T("$ZodCheckLessThan",(t,e)=>{rt.init(t,e);let r=Ax[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Bp=T("$ZodCheckGreaterThan",(t,e)=>{rt.init(t,e);let r=Ax[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Nx=T("$ZodCheckMultipleOf",(t,e)=>{rt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):wp(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Dx=T("$ZodCheckNumberFormat",(t,e)=>{rt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Rp[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Tx)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Mx=T("$ZodCheckMaxLength",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Pi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ci(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),jx=T("$ZodCheckMinLength",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Pi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ci(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),zx=T("$ZodCheckLengthEquals",(t,e)=>{var r;rt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Pi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ci(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ii=T("$ZodCheckStringFormat",(t,e)=>{var r,n;rt.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Lx=T("$ZodCheckRegex",(t,e)=>{Ii.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Fx=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ox),Ii.init(t,e)}),Ux=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ix),Ii.init(t,e)}),Hx=T("$ZodCheckIncludes",(t,e)=>{rt.init(t,e);let r=Sn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Zx=T("$ZodCheckStartsWith",(t,e)=>{rt.init(t,e);let r=new RegExp(`^${Sn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Bx=T("$ZodCheckEndsWith",(t,e)=>{rt.init(t,e);let r=new RegExp(`.*${Sn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),qx=T("$ZodCheckOverwrite",(t,e)=>{rt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var zc,qp=x(()=>{zc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
158
|
+
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
|
|
159
|
+
`))}}});var Wx,Vp=x(()=>{Wx={major:4,minor:0,patch:0}});function aS(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function lA(t){if(!Hp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return aS(r)}function dA(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function Gx(t,e,r){t.issues.length&&e.issues.push(...Or(r,t.issues)),e.value[r]=t.value}function Lc(t,e,r){t.issues.length&&e.issues.push(...Or(r,t.issues)),e.value[r]=t.value}function Kx(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Or(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Jx(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>pr(s,n,Mt())))}),e}function Wp(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(ps(t)&&ps(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Wp(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Wp(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Yx(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),yo(t))return t;let n=Wp(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Xx(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Qx(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 eS(t,e,r){return yo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function tS(t){return t.value=Object.freeze(t.value),t}function rS(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Cp(o))}}var ve,Ai,we,Gp,Kp,Jp,Yp,Xp,Qp,em,tm,rm,nm,om,nS,oS,sS,iS,sm,im,am,cm,um,lm,dm,pm,Fc,mm,fm,hm,gm,ym,_m,Uc,Hc,vm,bm,xm,Sm,km,wm,Em,$m,Tm,Pm,Rm,Cm,Om,Im,Am,cS=x(()=>{jc();ls();qp();Fp();Mc();Ir();Vp();Ir();ve=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Wx;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=yo(s),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let l=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new Kr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==l&&(c||(c=yo(s,l)))});else{if(s.issues.length===l)continue;c||(c=yo(s,l))}}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 Kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=_o(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return vo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ai=T("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??$x(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=T("$ZodStringFormat",(t,e)=>{Ii.init(t,e),Ai.init(t,e)}),Gp=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=dx),we.init(t,e)}),Kp=T("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Up(n))}else e.pattern??(e.pattern=Up());we.init(t,e)}),Jp=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=px),we.init(t,e)}),Yp=T("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:vx.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Xp=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=mx()),we.init(t,e)}),Qp=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ux),we.init(t,e)}),em=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ox),we.init(t,e)}),tm=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sx),we.init(t,e)}),rm=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ix),we.init(t,e)}),nm=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ax),we.init(t,e)}),om=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=cx),we.init(t,e)}),nS=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ex(e)),we.init(t,e)}),oS=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sx),we.init(t,e)}),sS=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=wx(e)),we.init(t,e)}),iS=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=lx),we.init(t,e)}),sm=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=fx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),im=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=hx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),am=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=gx),we.init(t,e)}),cm=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=yx),we.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});um=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=_x),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{aS(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});lm=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Hp),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{lA(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),dm=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=bx),we.init(t,e)});pm=T("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{dA(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Fc=T("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??Px,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),mm=T("$ZodNumber",(t,e)=>{Dx.init(t,e),Fc.init(t,e)}),fm=T("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=Rx,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),hm=T("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=Cx,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),gm=T("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=r=>r}),ym=T("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});_m=T("$ZodArray",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Gx(u,r,i))):Gx(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Uc=T("$ZodObject",(t,e)=>{ve.init(t,e);let r=Ti(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof ve))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=Pp(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});ke(t._zod,"propValues",()=>{let l=e.shape,m={};for(let f in l){let p=l[f]._zod;if(p.values){m[f]??(m[f]=new Set);for(let h of p.values)m[f].add(h)}}return m});let n=l=>{let m=new zc(["shape","payload","ctx"]),f=r.value,p=v=>{let _=go(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of f.keys)h[v]=`key_${g++}`;m.write("const newResult = {}");for(let v of f.keys)if(f.optionalKeys.has(v)){let _=h[v];m.write(`const ${_} = ${p(v)};`);let b=go(v);m.write(`
|
|
40
160
|
if (${_}.issues.length) {
|
|
41
161
|
if (input[${b}] === undefined) {
|
|
42
162
|
if (${b} in input) {
|
|
@@ -58,24 +178,24 @@ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ct
|
|
|
58
178
|
`)}else{let _=h[v];m.write(`const ${_} = ${p(v)};`),m.write(`
|
|
59
179
|
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
|
60
180
|
...iss,
|
|
61
|
-
path: iss.path ? [${
|
|
62
|
-
})));`),m.write(`newResult[${cs(v)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(v,_)=>y(l,v,_)},s,o=Ys,i=!pc.jitless,c=i&&dp.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let _=d.shape;for(let b of d.keys){let S=_[b],T=S._zod.run({value:f[b],issues:[]},m),$=S._zod.optin==="optional"&&S._zod.optout==="optional";T instanceof Promise?p.push(T.then(R=>$?_x(R,l,b,f):xc(R,l,b))):$?_x(T,l,b,f):xc(T,l,b)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,y=u._zod,v=y.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(v==="never"){h.push(_);continue}let b=y.run({value:f[_],issues:[]},m);b instanceof Promise?p.push(b.then(S=>xc(S,l,_))):xc(b,l,_)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});wc=E("$ZodUnion",(t,e)=>{ve.init(t,e),we(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),we(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),we(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),we(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>mi(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>vx(i,r,t,n)):vx(o,r,t,n)}}),sm=E("$ZodDiscriminatedUnion",(t,e)=>{wc.init(t,e);let r=t._zod.parse;we(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=di(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!Ys(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),om=E("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>bx(r,c,u)):bx(r,o,i)}});im=E("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Xs(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...Tr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Tr(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>lr(u,n,Nt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...Tr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Tr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),am=E("$ZodEnum",(t,e)=>{ve.init(t,e);let r=li(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>pp.has(typeof n)).map(n=>typeof n=="string"?fn(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),cm=E("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?fn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),um=E("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Br;return r.value=s,r}}),lm=E("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",we(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${mi(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),dm=E("$ZodNullable",(t,e)=>{ve.init(t,e),we(t._zod,"optin",()=>e.innerType._zod.optin),we(t._zod,"optout",()=>e.innerType._zod.optout),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${mi(r.source)}|null)$`):void 0}),we(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),pm=E("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",we(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>xx(o,e)):xx(s,e)}});mm=E("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",we(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),fm=E("$ZodNonOptional",(t,e)=>{ve.init(t,e),we(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Sx(o,t)):Sx(s,t)}});hm=E("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",we(t._zod,"optout",()=>e.innerType._zod.optout),we(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>lr(i,n,Nt()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>lr(o,n,Nt()))},input:r.value}),r.issues=[]),r)}}),gm=E("$ZodPipe",(t,e)=>{ve.init(t,e),we(t._zod,"values",()=>e.in._zod.values),we(t._zod,"optin",()=>e.in._zod.optin),we(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>kx(o,e,n)):kx(s,e,n)}});ym=E("$ZodReadonly",(t,e)=>{ve.init(t,e),we(t._zod,"propValues",()=>e.innerType._zod.propValues),we(t._zod,"values",()=>e.innerType._zod.values),we(t._zod,"optin",()=>e.innerType._zod.optin),we(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(wx):wx(s)}});_m=E("$ZodCustom",(t,e)=>{Qe.init(t,e),ve.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Ex(o,r,n,t));Ex(s,r,n,t)}})});function Ix(){return{localeError:yI()}}var gI,yI,Ax=x(()=>{Pr();gI=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},yI=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${gI(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${hc(n.values[0])}`:`Invalid option: expected one of ${mc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${mc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Ec=x(()=>{});function Nx(){return new _i}var _i,hn,bm=x(()=>{_i=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};hn=Nx()});function xm(t,e){return new t({type:"string",...K(e)})}function Sm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...K(e)})}function $c(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...K(e)})}function km(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...K(e)})}function wm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K(e)})}function Em(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K(e)})}function $m(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K(e)})}function Tm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...K(e)})}function Pm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...K(e)})}function Rm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...K(e)})}function Cm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...K(e)})}function Om(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...K(e)})}function Im(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...K(e)})}function Am(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...K(e)})}function Nm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...K(e)})}function Dm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...K(e)})}function Mm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...K(e)})}function jm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K(e)})}function zm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K(e)})}function Lm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...K(e)})}function Fm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...K(e)})}function Um(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...K(e)})}function Hm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...K(e)})}function Dx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K(e)})}function Mx(t,e){return new t({type:"string",format:"date",check:"string_format",...K(e)})}function jx(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...K(e)})}function zx(t,e){return new t({type:"string",format:"duration",check:"string_format",...K(e)})}function Zm(t,e){return new t({type:"number",checks:[],...K(e)})}function Bm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...K(e)})}function qm(t,e){return new t({type:"boolean",...K(e)})}function Vm(t,e){return new t({type:"null",...K(e)})}function Wm(t){return new t({type:"unknown"})}function Gm(t,e){return new t({type:"never",...K(e)})}function Tc(t,e){return new Pp({check:"less_than",...K(e),value:t,inclusive:!1})}function vi(t,e){return new Pp({check:"less_than",...K(e),value:t,inclusive:!0})}function Pc(t,e){return new Rp({check:"greater_than",...K(e),value:t,inclusive:!1})}function bi(t,e){return new Rp({check:"greater_than",...K(e),value:t,inclusive:!0})}function Rc(t,e){return new nx({check:"multiple_of",...K(e),value:t})}function Cc(t,e){return new ox({check:"max_length",...K(e),maximum:t})}function Qs(t,e){return new ix({check:"min_length",...K(e),minimum:t})}function Oc(t,e){return new ax({check:"length_equals",...K(e),length:t})}function Km(t,e){return new cx({check:"string_format",format:"regex",...K(e),pattern:t})}function Jm(t){return new ux({check:"string_format",format:"lowercase",...K(t)})}function Ym(t){return new lx({check:"string_format",format:"uppercase",...K(t)})}function Xm(t,e){return new dx({check:"string_format",format:"includes",...K(e),includes:t})}function Qm(t,e){return new px({check:"string_format",format:"starts_with",...K(e),prefix:t})}function ef(t,e){return new mx({check:"string_format",format:"ends_with",...K(e),suffix:t})}function ps(t){return new fx({check:"overwrite",tx:t})}function tf(t){return ps(e=>e.normalize(t))}function rf(){return ps(t=>t.trim())}function nf(){return ps(t=>t.toLowerCase())}function sf(){return ps(t=>t.toUpperCase())}function Lx(t,e,r){return new t({type:"array",element:e,...K(r)})}function of(t,e,r){let n=K(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function af(t,e,r){return new t({type:"custom",check:"custom",fn:e,...K(r)})}var Fx=x(()=>{vc();Pr()});var Ux=x(()=>{});function cf(t,e){if(t instanceof _i){let n=new Ic(e),s={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,u]=a;o[c]=n.emit(u,{...e,external:i})}if(Object.keys(s).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let r=new Ic(e);return r.process(t),r.emit(t,e)}function Ge(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let s=t._zod.def;switch(s.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 Ge(s.element,r);case"object":{for(let o in s.shape)if(Ge(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Ge(o,r))return!0;return!1}case"intersection":return Ge(s.left,r)||Ge(s.right,r);case"tuple":{for(let o of s.items)if(Ge(o,r))return!0;return!!(s.rest&&Ge(s.rest,r))}case"record":return Ge(s.keyType,r)||Ge(s.valueType,r);case"map":return Ge(s.keyType,r)||Ge(s.valueType,r);case"set":return Ge(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ge(s.innerType,r);case"lazy":return Ge(s.getter(),r);case"default":return Ge(s.innerType,r);case"prefault":return Ge(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ge(s.in,r)||Ge(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var Ic,Hx=x(()=>{bm();Pr();Ic=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??hn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){let b=[...v];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=s.shape;for(let v in h)p.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(v=>{let _=s.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=f;p.type="array";let h=s.items.map((v,_)=>this.process(v,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,s.rest){let v=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}s.rest&&(p.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=f,h=li(s.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,h=[];for(let g of s.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];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ge(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
181
|
+
path: iss.path ? [${go(v)}, ...iss.path] : [${go(v)}]
|
|
182
|
+
})));`),m.write(`newResult[${go(v)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(v,_)=>y(l,v,_)},o,s=ds,i=!Cc.jitless,c=i&&$p.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!s(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),l=o(l,m);else{l.value={};let _=d.shape;for(let b of d.keys){let S=_[b],P=S._zod.run({value:f[b],issues:[]},m),$=S._zod.optin==="optional"&&S._zod.optout==="optional";P instanceof Promise?p.push(P.then(R=>$?Kx(R,l,b,f):Lc(R,l,b))):$?Kx(P,l,b,f):Lc(P,l,b)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,y=u._zod,v=y.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(v==="never"){h.push(_);continue}let b=y.run({value:f[_],issues:[]},m);b instanceof Promise?p.push(b.then(S=>Lc(S,l,_))):Lc(b,l,_)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Hc=T("$ZodUnion",(t,e)=>{ve.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ri(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Jx(i,r,t,n)):Jx(s,r,t,n)}}),vm=T("$ZodDiscriminatedUnion",(t,e)=>{Hc.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Ti(()=>{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(!ds(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),bm=T("$ZodIntersection",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Yx(r,c,u)):Yx(r,s,i)}});xm=T("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ps(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...Or(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Or(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>pr(u,n,Mt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Or(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Or(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Sm=T("$ZodEnum",(t,e)=>{ve.init(t,e);let r=$i(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Tp.has(typeof n)).map(n=>typeof n=="string"?Sn(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),km=T("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Sn(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),wm=T("$ZodTransform",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Kr;return r.value=o,r}}),Em=T("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ri(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),$m=T("$ZodNullable",(t,e)=>{ve.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ri(r.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Tm=T("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Xx(s,e)):Xx(o,e)}});Pm=T("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Rm=T("$ZodNonOptional",(t,e)=>{ve.init(t,e),ke(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Qx(s,t)):Qx(o,t)}});Cm=T("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>pr(i,n,Mt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>pr(s,n,Mt()))},input:r.value}),r.issues=[]),r)}}),Om=T("$ZodPipe",(t,e)=>{ve.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>eS(s,e,n)):eS(o,e,n)}});Im=T("$ZodReadonly",(t,e)=>{ve.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(tS):tS(o)}});Am=T("$ZodCustom",(t,e)=>{rt.init(t,e),ve.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>rS(s,r,n,t));rS(o,r,n,t)}})});function uS(){return{localeError:mA()}}var pA,mA,lS=x(()=>{Ir();pA=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},mA=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${pA(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ac(n.values[0])}`:`Invalid option: expected one of ${Oc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Oc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Zc=x(()=>{});function dS(){return new Ni}var Ni,kn,Dm=x(()=>{Ni=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};kn=dS()});function Mm(t,e){return new t({type:"string",...J(e)})}function jm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...J(e)})}function Bc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...J(e)})}function zm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...J(e)})}function Lm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...J(e)})}function Fm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...J(e)})}function Um(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...J(e)})}function Hm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...J(e)})}function Zm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...J(e)})}function Bm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...J(e)})}function qm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...J(e)})}function Vm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...J(e)})}function Wm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...J(e)})}function Gm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...J(e)})}function Km(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...J(e)})}function Jm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...J(e)})}function Ym(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...J(e)})}function Xm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...J(e)})}function Qm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...J(e)})}function ef(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...J(e)})}function tf(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...J(e)})}function rf(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...J(e)})}function nf(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...J(e)})}function pS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...J(e)})}function mS(t,e){return new t({type:"string",format:"date",check:"string_format",...J(e)})}function fS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...J(e)})}function hS(t,e){return new t({type:"string",format:"duration",check:"string_format",...J(e)})}function of(t,e){return new t({type:"number",checks:[],...J(e)})}function sf(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...J(e)})}function af(t,e){return new t({type:"boolean",...J(e)})}function cf(t,e){return new t({type:"null",...J(e)})}function uf(t){return new t({type:"unknown"})}function lf(t,e){return new t({type:"never",...J(e)})}function qc(t,e){return new Zp({check:"less_than",...J(e),value:t,inclusive:!1})}function Di(t,e){return new Zp({check:"less_than",...J(e),value:t,inclusive:!0})}function Vc(t,e){return new Bp({check:"greater_than",...J(e),value:t,inclusive:!1})}function Mi(t,e){return new Bp({check:"greater_than",...J(e),value:t,inclusive:!0})}function Wc(t,e){return new Nx({check:"multiple_of",...J(e),value:t})}function Gc(t,e){return new Mx({check:"max_length",...J(e),maximum:t})}function ms(t,e){return new jx({check:"min_length",...J(e),minimum:t})}function Kc(t,e){return new zx({check:"length_equals",...J(e),length:t})}function df(t,e){return new Lx({check:"string_format",format:"regex",...J(e),pattern:t})}function pf(t){return new Fx({check:"string_format",format:"lowercase",...J(t)})}function mf(t){return new Ux({check:"string_format",format:"uppercase",...J(t)})}function ff(t,e){return new Hx({check:"string_format",format:"includes",...J(e),includes:t})}function hf(t,e){return new Zx({check:"string_format",format:"starts_with",...J(e),prefix:t})}function gf(t,e){return new Bx({check:"string_format",format:"ends_with",...J(e),suffix:t})}function bo(t){return new qx({check:"overwrite",tx:t})}function yf(t){return bo(e=>e.normalize(t))}function _f(){return bo(t=>t.trim())}function vf(){return bo(t=>t.toLowerCase())}function bf(){return bo(t=>t.toUpperCase())}function gS(t,e,r){return new t({type:"array",element:e,...J(r)})}function xf(t,e,r){let n=J(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Sf(t,e,r){return new t({type:"custom",check:"custom",fn:e,...J(r)})}var yS=x(()=>{jc();Ir()});var _S=x(()=>{});function kf(t,e){if(t instanceof Ni){let n=new Jc(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Jc(e);return r.process(t),r.emit(t,e)}function Ke(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ke(o.element,r);case"object":{for(let s in o.shape)if(Ke(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ke(s,r))return!0;return!1}case"intersection":return Ke(o.left,r)||Ke(o.right,r);case"tuple":{for(let s of o.items)if(Ke(s,r))return!0;return!!(o.rest&&Ke(o.rest,r))}case"record":return Ke(o.keyType,r)||Ke(o.valueType,r);case"map":return Ke(o.keyType,r)||Ke(o.valueType,r);case"set":return Ke(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ke(o.innerType,r);case"lazy":return Ke(o.getter(),r);case"default":return Ke(o.innerType,r);case"prefault":return Ke(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ke(o.in,r)||Ke(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Jc,vS=x(()=>{Dm();Ir();Jc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){let b=[...v];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.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":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=o.shape;for(let v in h)p.properties[v]=this.process(h[v],{...l,path:[...l.path,"properties",v]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(v=>{let _=o.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=f;p.anyOf=o.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(o.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(o.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=f;p.type="array";let h=o.items.map((v,_)=>this.process(v,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let v=this.process(o.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=f;p.type="object",p.propertyNames=this.process(o.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=f,h=$i(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,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];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(o.innerType,l),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,l),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,l),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(o.innerType,l),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,l),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ke(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===o)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=s(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
63
183
|
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,s.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Zx=x(()=>{});var gt=x(()=>{Js();Ep();_p();Ox();vc();Op();Pr();_c();Ec();bm();Cp();Ux();Fx();Hx();Zx()});var uf=x(()=>{gt()});function lf(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new QI(r)}var XI,QI,Bx=x(()=>{gt();gt();uf();XI=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>bp(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ls(t,r,n),t.parseAsync=async(r,n)=>Sp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ds(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),QI=E("ZodMiniObject",(t,e)=>{kc.init(t,e),XI.init(t,e),ce.defineLazy(t,"shape",()=>e.shape)})});var qx=x(()=>{});var Vx=x(()=>{});var Wx=x(()=>{});var Gx=x(()=>{gt();uf();Bx();qx();gt();Ec();Vx();Wx()});var Kx=x(()=>{Gx()});var df=x(()=>{Kx()});function Wt(t){return!!t._zod}function fs(t){let e=Object.values(t);if(e.length===0)return lf({});let r=e.every(Wt),n=e.every(s=>!Wt(s));if(r)return lf(t);if(n)return op(t);throw new Error("Mixed Zod versions detected in object shape.")}function gn(t,e){return Wt(t)?ls(t,e):t.safeParse(e)}async function Ac(t,e){return Wt(t)?await ds(t,e):await t.safeParseAsync(e)}function yn(t){if(!t)return;let e;if(Wt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function eo(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return fs(t)}}if(Wt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Nc(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Yx(t){return t.description}function Xx(t){if(Wt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Dc(t){if(Wt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var xi=x(()=>{ci();df()});var pf=x(()=>{gt()});var Si={};Le(Si,{ZodISODate:()=>eS,ZodISODateTime:()=>Qx,ZodISODuration:()=>rS,ZodISOTime:()=>tS,date:()=>ff,datetime:()=>mf,duration:()=>gf,time:()=>hf});function mf(t){return Dx(Qx,t)}function ff(t){return Mx(eS,t)}function hf(t){return jx(tS,t)}function gf(t){return zx(rS,t)}var Qx,eS,tS,rS,yf=x(()=>{gt();_f();Qx=E("ZodISODateTime",(t,e)=>{$x.init(t,e),Ne.init(t,e)});eS=E("ZodISODate",(t,e)=>{Tx.init(t,e),Ne.init(t,e)});tS=E("ZodISOTime",(t,e)=>{Px.init(t,e),Ne.init(t,e)});rS=E("ZodISODuration",(t,e)=>{Rx.init(t,e),Ne.init(t,e)})});var nS,f9,ki,vf=x(()=>{gt();gt();nS=(t,e)=>{gc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>yp(t,r)},flatten:{value:r=>gp(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},f9=E("ZodError",nS),ki=E("ZodError",nS,{Parent:Error})});var sS,oS,iS,aS,bf=x(()=>{gt();vf();sS=vp(ki),oS=xp(ki),iS=kp(ki),aS=wp(ki)});function k(t){return xm(uA,t)}function ge(t){return Zm(pS,t)}function uS(t){return Bm(TA,t)}function Je(t){return qm(PA,t)}function mS(t){return Vm(RA,t)}function De(){return Wm(CA)}function IA(t){return Gm(OA,t)}function ue(t,e){return Lx(AA,t,e)}function z(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new fS(r)}function yt(t,e){return new fS({type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ce.normalizeParams(e)})}function Pe(t,e){return new hS({type:"union",options:t,...ce.normalizeParams(e)})}function kf(t,e,r){return new NA({type:"union",options:e,discriminator:t,...ce.normalizeParams(r)})}function jc(t,e){return new DA({type:"intersection",left:t,right:e})}function $e(t,e,r){return new MA({type:"record",keyType:t,valueType:e,...ce.normalizeParams(r)})}function Tt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new xf({type:"enum",entries:r,...ce.normalizeParams(e)})}function Z(t,e){return new jA({type:"literal",values:Array.isArray(t)?t:[t],...ce.normalizeParams(e)})}function gS(t){return new zA({type:"transform",transform:t})}function Me(t){return new yS({type:"optional",innerType:t})}function lS(t){return new LA({type:"nullable",innerType:t})}function UA(t,e){return new FA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ZA(t,e){return new HA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function BA(t,e){return new _S({type:"nonoptional",innerType:t,...ce.normalizeParams(e)})}function VA(t,e){return new qA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Sf(t,e){return new WA({type:"pipe",in:t,out:e})}function KA(t){return new GA({type:"readonly",innerType:t})}function JA(t){let e=new Qe({check:"custom"});return e._zod.check=t,e}function bS(t,e){return of(vS,t??(()=>!0),e)}function YA(t,e={}){return af(vS,t,e)}function XA(t){let e=JA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ce.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ce.issue(s))}},t(r.value,r)));return e}function wf(t,e){return Sf(gS(t),e)}var He,dS,uA,Ne,lA,cS,Mc,dA,pA,mA,fA,hA,gA,yA,_A,vA,bA,xA,SA,kA,wA,EA,$A,pS,TA,PA,RA,CA,OA,AA,fS,hS,NA,DA,MA,xf,jA,zA,yS,LA,FA,HA,_S,qA,WA,GA,vS,_f=x(()=>{gt();gt();pf();yf();bf();He=E("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Dt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>sS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>iS(t,r,n),t.parseAsync=async(r,n)=>oS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>aS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(YA(r,n)),t.superRefine=r=>t.check(XA(r)),t.overwrite=r=>t.check(ps(r)),t.optional=()=>Me(t),t.nullable=()=>lS(t),t.nullish=()=>Me(lS(t)),t.nonoptional=r=>BA(t,r),t.array=()=>ue(t),t.or=r=>Pe([t,r]),t.and=r=>jc(t,r),t.transform=r=>Sf(t,gS(r)),t.default=r=>UA(t,r),t.prefault=r=>ZA(t,r),t.catch=r=>VA(t,r),t.pipe=r=>Sf(t,r),t.readonly=()=>KA(t),t.describe=r=>{let n=t.clone();return hn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return hn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return hn.get(t);let n=t.clone();return hn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),dS=E("_ZodString",(t,e)=>{yi.init(t,e),He.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Km(...n)),t.includes=(...n)=>t.check(Xm(...n)),t.startsWith=(...n)=>t.check(Qm(...n)),t.endsWith=(...n)=>t.check(ef(...n)),t.min=(...n)=>t.check(Qs(...n)),t.max=(...n)=>t.check(Cc(...n)),t.length=(...n)=>t.check(Oc(...n)),t.nonempty=(...n)=>t.check(Qs(1,...n)),t.lowercase=n=>t.check(Jm(n)),t.uppercase=n=>t.check(Ym(n)),t.trim=()=>t.check(rf()),t.normalize=(...n)=>t.check(tf(...n)),t.toLowerCase=()=>t.check(nf()),t.toUpperCase=()=>t.check(sf())}),uA=E("ZodString",(t,e)=>{yi.init(t,e),dS.init(t,e),t.email=r=>t.check(Sm(lA,r)),t.url=r=>t.check(Tm(dA,r)),t.jwt=r=>t.check(Hm($A,r)),t.emoji=r=>t.check(Pm(pA,r)),t.guid=r=>t.check($c(cS,r)),t.uuid=r=>t.check(km(Mc,r)),t.uuidv4=r=>t.check(wm(Mc,r)),t.uuidv6=r=>t.check(Em(Mc,r)),t.uuidv7=r=>t.check($m(Mc,r)),t.nanoid=r=>t.check(Rm(mA,r)),t.guid=r=>t.check($c(cS,r)),t.cuid=r=>t.check(Cm(fA,r)),t.cuid2=r=>t.check(Om(hA,r)),t.ulid=r=>t.check(Im(gA,r)),t.base64=r=>t.check(Lm(kA,r)),t.base64url=r=>t.check(Fm(wA,r)),t.xid=r=>t.check(Am(yA,r)),t.ksuid=r=>t.check(Nm(_A,r)),t.ipv4=r=>t.check(Dm(vA,r)),t.ipv6=r=>t.check(Mm(bA,r)),t.cidrv4=r=>t.check(jm(xA,r)),t.cidrv6=r=>t.check(zm(SA,r)),t.e164=r=>t.check(Um(EA,r)),t.datetime=r=>t.check(mf(r)),t.date=r=>t.check(ff(r)),t.time=r=>t.check(hf(r)),t.duration=r=>t.check(gf(r))});Ne=E("ZodStringFormat",(t,e)=>{Ee.init(t,e),dS.init(t,e)}),lA=E("ZodEmail",(t,e)=>{Dp.init(t,e),Ne.init(t,e)}),cS=E("ZodGUID",(t,e)=>{Ap.init(t,e),Ne.init(t,e)}),Mc=E("ZodUUID",(t,e)=>{Np.init(t,e),Ne.init(t,e)}),dA=E("ZodURL",(t,e)=>{Mp.init(t,e),Ne.init(t,e)}),pA=E("ZodEmoji",(t,e)=>{jp.init(t,e),Ne.init(t,e)}),mA=E("ZodNanoID",(t,e)=>{zp.init(t,e),Ne.init(t,e)}),fA=E("ZodCUID",(t,e)=>{Lp.init(t,e),Ne.init(t,e)}),hA=E("ZodCUID2",(t,e)=>{Fp.init(t,e),Ne.init(t,e)}),gA=E("ZodULID",(t,e)=>{Up.init(t,e),Ne.init(t,e)}),yA=E("ZodXID",(t,e)=>{Hp.init(t,e),Ne.init(t,e)}),_A=E("ZodKSUID",(t,e)=>{Zp.init(t,e),Ne.init(t,e)}),vA=E("ZodIPv4",(t,e)=>{Bp.init(t,e),Ne.init(t,e)}),bA=E("ZodIPv6",(t,e)=>{qp.init(t,e),Ne.init(t,e)}),xA=E("ZodCIDRv4",(t,e)=>{Vp.init(t,e),Ne.init(t,e)}),SA=E("ZodCIDRv6",(t,e)=>{Wp.init(t,e),Ne.init(t,e)}),kA=E("ZodBase64",(t,e)=>{Gp.init(t,e),Ne.init(t,e)}),wA=E("ZodBase64URL",(t,e)=>{Kp.init(t,e),Ne.init(t,e)}),EA=E("ZodE164",(t,e)=>{Jp.init(t,e),Ne.init(t,e)}),$A=E("ZodJWT",(t,e)=>{Yp.init(t,e),Ne.init(t,e)}),pS=E("ZodNumber",(t,e)=>{Sc.init(t,e),He.init(t,e),t.gt=(n,s)=>t.check(Pc(n,s)),t.gte=(n,s)=>t.check(bi(n,s)),t.min=(n,s)=>t.check(bi(n,s)),t.lt=(n,s)=>t.check(Tc(n,s)),t.lte=(n,s)=>t.check(vi(n,s)),t.max=(n,s)=>t.check(vi(n,s)),t.int=n=>t.check(uS(n)),t.safe=n=>t.check(uS(n)),t.positive=n=>t.check(Pc(0,n)),t.nonnegative=n=>t.check(bi(0,n)),t.negative=n=>t.check(Tc(0,n)),t.nonpositive=n=>t.check(vi(0,n)),t.multipleOf=(n,s)=>t.check(Rc(n,s)),t.step=(n,s)=>t.check(Rc(n,s)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});TA=E("ZodNumberFormat",(t,e)=>{Xp.init(t,e),pS.init(t,e)});PA=E("ZodBoolean",(t,e)=>{Qp.init(t,e),He.init(t,e)});RA=E("ZodNull",(t,e)=>{em.init(t,e),He.init(t,e)});CA=E("ZodUnknown",(t,e)=>{tm.init(t,e),He.init(t,e)});OA=E("ZodNever",(t,e)=>{rm.init(t,e),He.init(t,e)});AA=E("ZodArray",(t,e)=>{nm.init(t,e),He.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Qs(r,n)),t.nonempty=r=>t.check(Qs(1,r)),t.max=(r,n)=>t.check(Cc(r,n)),t.length=(r,n)=>t.check(Oc(r,n)),t.unwrap=()=>t.element});fS=E("ZodObject",(t,e)=>{kc.init(t,e),He.init(t,e),ce.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Tt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),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:IA()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ce.extend(t,r),t.merge=r=>ce.merge(t,r),t.pick=r=>ce.pick(t,r),t.omit=r=>ce.omit(t,r),t.partial=(...r)=>ce.partial(yS,t,r[0]),t.required=(...r)=>ce.required(_S,t,r[0])});hS=E("ZodUnion",(t,e)=>{wc.init(t,e),He.init(t,e),t.options=e.options});NA=E("ZodDiscriminatedUnion",(t,e)=>{hS.init(t,e),sm.init(t,e)});DA=E("ZodIntersection",(t,e)=>{om.init(t,e),He.init(t,e)});MA=E("ZodRecord",(t,e)=>{im.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});xf=E("ZodEnum",(t,e)=>{am.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new xf({...e,checks:[],...ce.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new xf({...e,checks:[],...ce.normalizeParams(s),entries:o})}});jA=E("ZodLiteral",(t,e)=>{cm.init(t,e),He.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]}})});zA=E("ZodTransform",(t,e)=>{um.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ce.issue(o,r.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ce.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});yS=E("ZodOptional",(t,e)=>{lm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});LA=E("ZodNullable",(t,e)=>{dm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});FA=E("ZodDefault",(t,e)=>{pm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});HA=E("ZodPrefault",(t,e)=>{mm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});_S=E("ZodNonOptional",(t,e)=>{fm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});qA=E("ZodCatch",(t,e)=>{hm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});WA=E("ZodPipe",(t,e)=>{gm.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});GA=E("ZodReadonly",(t,e)=>{ym.init(t,e),He.init(t,e)});vS=E("ZodCustom",(t,e)=>{_m.init(t,e),He.init(t,e)})});var xS=x(()=>{});var SS=x(()=>{});var kS=x(()=>{gt();_f();pf();vf();bf();xS();gt();Ax();Ec();yf();SS();Nt(Ix())});var wS=x(()=>{kS()});var ES=x(()=>{wS()});function HS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function ZS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var $f,$S,_n,Lc,Ke,TS,PS,C9,tN,rN,Tf,Mt,wi,RS,et,Gt,Kt,tt,Fc,CS,Pf,OS,IS,Rf,Ei,V,Cf,AS,NS,O9,Uc,nN,Hc,sN,$i,to,DS,oN,iN,aN,cN,uN,lN,Of,dN,pN,If,Zc,mN,fN,Bc,hN,Ti,Pi,gN,Ri,ro,yN,Ci,qc,Vc,Wc,I9,Gc,Kc,Jc,MS,jS,zS,Af,LS,Oi,no,FS,_N,so,vN,oo,bN,Nf,xN,Yc,SN,kN,wN,EN,$N,TN,PN,RN,CN,ON,io,IN,AN,Xc,Df,Mf,jf,NN,DN,MN,zf,jN,zN,LN,FN,UN,US,ao,HN,Qc,A9,ZN,co,BN,N9,Ii,qN,Lf,VN,WN,GN,KN,JN,YN,XN,zc,QN,e1,t1,Ai,Ff,r1,n1,s1,o1,i1,a1,c1,u1,l1,d1,p1,m1,f1,h1,g1,y1,_1,v1,uo,b1,x1,S1,eu,k1,w1,E1,Uf,$1,D9,M9,j9,z9,L9,F9,H,Ef,hs=x(()=>{ES();$f="2025-11-25",$S=[$f,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],_n="io.modelcontextprotocol/related-task",Lc="2.0",Ke=bS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),TS=Pe([k(),ge().int()]),PS=k(),C9=yt({ttl:ge().optional(),pollInterval:ge().optional()}),tN=z({ttl:ge().optional()}),rN=z({taskId:k()}),Tf=yt({progressToken:TS.optional(),[_n]:rN.optional()}),Mt=z({_meta:Tf.optional()}),wi=Mt.extend({task:tN.optional()}),RS=t=>wi.safeParse(t).success,et=z({method:k(),params:Mt.loose().optional()}),Gt=z({_meta:Tf.optional()}),Kt=z({method:k(),params:Gt.loose().optional()}),tt=yt({_meta:Tf.optional()}),Fc=Pe([k(),ge().int()]),CS=z({jsonrpc:Z(Lc),id:Fc,...et.shape}).strict(),Pf=t=>CS.safeParse(t).success,OS=z({jsonrpc:Z(Lc),...Kt.shape}).strict(),IS=t=>OS.safeParse(t).success,Rf=z({jsonrpc:Z(Lc),id:Fc,result:tt}).strict(),Ei=t=>Rf.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"})(V||(V={}));Cf=z({jsonrpc:Z(Lc),id:Fc.optional(),error:z({code:ge().int(),message:k(),data:De().optional()})}).strict(),AS=t=>Cf.safeParse(t).success,NS=Pe([CS,OS,Rf,Cf]),O9=Pe([Rf,Cf]),Uc=tt.strict(),nN=Gt.extend({requestId:Fc.optional(),reason:k().optional()}),Hc=Kt.extend({method:Z("notifications/cancelled"),params:nN}),sN=z({src:k(),mimeType:k().optional(),sizes:ue(k()).optional(),theme:Tt(["light","dark"]).optional()}),$i=z({icons:ue(sN).optional()}),to=z({name:k(),title:k().optional()}),DS=to.extend({...to.shape,...$i.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),oN=jc(z({applyDefaults:Je().optional()}),$e(k(),De())),iN=wf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,jc(z({form:oN.optional(),url:Ke.optional()}),$e(k(),De()).optional())),aN=yt({list:Ke.optional(),cancel:Ke.optional(),requests:yt({sampling:yt({createMessage:Ke.optional()}).optional(),elicitation:yt({create:Ke.optional()}).optional()}).optional()}),cN=yt({list:Ke.optional(),cancel:Ke.optional(),requests:yt({tools:yt({call:Ke.optional()}).optional()}).optional()}),uN=z({experimental:$e(k(),Ke).optional(),sampling:z({context:Ke.optional(),tools:Ke.optional()}).optional(),elicitation:iN.optional(),roots:z({listChanged:Je().optional()}).optional(),tasks:aN.optional(),extensions:$e(k(),Ke).optional()}),lN=Mt.extend({protocolVersion:k(),capabilities:uN,clientInfo:DS}),Of=et.extend({method:Z("initialize"),params:lN}),dN=z({experimental:$e(k(),Ke).optional(),logging:Ke.optional(),completions:Ke.optional(),prompts:z({listChanged:Je().optional()}).optional(),resources:z({subscribe:Je().optional(),listChanged:Je().optional()}).optional(),tools:z({listChanged:Je().optional()}).optional(),tasks:cN.optional(),extensions:$e(k(),Ke).optional()}),pN=tt.extend({protocolVersion:k(),capabilities:dN,serverInfo:DS,instructions:k().optional()}),If=Kt.extend({method:Z("notifications/initialized"),params:Gt.optional()}),Zc=et.extend({method:Z("ping"),params:Mt.optional()}),mN=z({progress:ge(),total:Me(ge()),message:Me(k())}),fN=z({...Gt.shape,...mN.shape,progressToken:TS}),Bc=Kt.extend({method:Z("notifications/progress"),params:fN}),hN=Mt.extend({cursor:PS.optional()}),Ti=et.extend({params:hN.optional()}),Pi=tt.extend({nextCursor:PS.optional()}),gN=Tt(["working","input_required","completed","failed","cancelled"]),Ri=z({taskId:k(),status:gN,ttl:Pe([ge(),mS()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:Me(ge()),statusMessage:Me(k())}),ro=tt.extend({task:Ri}),yN=Gt.merge(Ri),Ci=Kt.extend({method:Z("notifications/tasks/status"),params:yN}),qc=et.extend({method:Z("tasks/get"),params:Mt.extend({taskId:k()})}),Vc=tt.merge(Ri),Wc=et.extend({method:Z("tasks/result"),params:Mt.extend({taskId:k()})}),I9=tt.loose(),Gc=Ti.extend({method:Z("tasks/list")}),Kc=Pi.extend({tasks:ue(Ri)}),Jc=et.extend({method:Z("tasks/cancel"),params:Mt.extend({taskId:k()})}),MS=tt.merge(Ri),jS=z({uri:k(),mimeType:Me(k()),_meta:$e(k(),De()).optional()}),zS=jS.extend({text:k()}),Af=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),LS=jS.extend({blob:Af}),Oi=Tt(["user","assistant"]),no=z({audience:ue(Oi).optional(),priority:ge().min(0).max(1).optional(),lastModified:Si.datetime({offset:!0}).optional()}),FS=z({...to.shape,...$i.shape,uri:k(),description:Me(k()),mimeType:Me(k()),size:Me(ge()),annotations:no.optional(),_meta:Me(yt({}))}),_N=z({...to.shape,...$i.shape,uriTemplate:k(),description:Me(k()),mimeType:Me(k()),annotations:no.optional(),_meta:Me(yt({}))}),so=Ti.extend({method:Z("resources/list")}),vN=Pi.extend({resources:ue(FS)}),oo=Ti.extend({method:Z("resources/templates/list")}),bN=Pi.extend({resourceTemplates:ue(_N)}),Nf=Mt.extend({uri:k()}),xN=Nf,Yc=et.extend({method:Z("resources/read"),params:xN}),SN=tt.extend({contents:ue(Pe([zS,LS]))}),kN=Kt.extend({method:Z("notifications/resources/list_changed"),params:Gt.optional()}),wN=Nf,EN=et.extend({method:Z("resources/subscribe"),params:wN}),$N=Nf,TN=et.extend({method:Z("resources/unsubscribe"),params:$N}),PN=Gt.extend({uri:k()}),RN=Kt.extend({method:Z("notifications/resources/updated"),params:PN}),CN=z({name:k(),description:Me(k()),required:Me(Je())}),ON=z({...to.shape,...$i.shape,description:Me(k()),arguments:Me(ue(CN)),_meta:Me(yt({}))}),io=Ti.extend({method:Z("prompts/list")}),IN=Pi.extend({prompts:ue(ON)}),AN=Mt.extend({name:k(),arguments:$e(k(),k()).optional()}),Xc=et.extend({method:Z("prompts/get"),params:AN}),Df=z({type:Z("text"),text:k(),annotations:no.optional(),_meta:$e(k(),De()).optional()}),Mf=z({type:Z("image"),data:Af,mimeType:k(),annotations:no.optional(),_meta:$e(k(),De()).optional()}),jf=z({type:Z("audio"),data:Af,mimeType:k(),annotations:no.optional(),_meta:$e(k(),De()).optional()}),NN=z({type:Z("tool_use"),name:k(),id:k(),input:$e(k(),De()),_meta:$e(k(),De()).optional()}),DN=z({type:Z("resource"),resource:Pe([zS,LS]),annotations:no.optional(),_meta:$e(k(),De()).optional()}),MN=FS.extend({type:Z("resource_link")}),zf=Pe([Df,Mf,jf,MN,DN]),jN=z({role:Oi,content:zf}),zN=tt.extend({description:k().optional(),messages:ue(jN)}),LN=Kt.extend({method:Z("notifications/prompts/list_changed"),params:Gt.optional()}),FN=z({title:k().optional(),readOnlyHint:Je().optional(),destructiveHint:Je().optional(),idempotentHint:Je().optional(),openWorldHint:Je().optional()}),UN=z({taskSupport:Tt(["required","optional","forbidden"]).optional()}),US=z({...to.shape,...$i.shape,description:k().optional(),inputSchema:z({type:Z("object"),properties:$e(k(),Ke).optional(),required:ue(k()).optional()}).catchall(De()),outputSchema:z({type:Z("object"),properties:$e(k(),Ke).optional(),required:ue(k()).optional()}).catchall(De()).optional(),annotations:FN.optional(),execution:UN.optional(),_meta:$e(k(),De()).optional()}),ao=Ti.extend({method:Z("tools/list")}),HN=Pi.extend({tools:ue(US)}),Qc=tt.extend({content:ue(zf).default([]),structuredContent:$e(k(),De()).optional(),isError:Je().optional()}),A9=Qc.or(tt.extend({toolResult:De()})),ZN=wi.extend({name:k(),arguments:$e(k(),De()).optional()}),co=et.extend({method:Z("tools/call"),params:ZN}),BN=Kt.extend({method:Z("notifications/tools/list_changed"),params:Gt.optional()}),N9=z({autoRefresh:Je().default(!0),debounceMs:ge().int().nonnegative().default(300)}),Ii=Tt(["debug","info","notice","warning","error","critical","alert","emergency"]),qN=Mt.extend({level:Ii}),Lf=et.extend({method:Z("logging/setLevel"),params:qN}),VN=Gt.extend({level:Ii,logger:k().optional(),data:De()}),WN=Kt.extend({method:Z("notifications/message"),params:VN}),GN=z({name:k().optional()}),KN=z({hints:ue(GN).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),JN=z({mode:Tt(["auto","required","none"]).optional()}),YN=z({type:Z("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:ue(zf).default([]),structuredContent:z({}).loose().optional(),isError:Je().optional(),_meta:$e(k(),De()).optional()}),XN=kf("type",[Df,Mf,jf]),zc=kf("type",[Df,Mf,jf,NN,YN]),QN=z({role:Oi,content:Pe([zc,ue(zc)]),_meta:$e(k(),De()).optional()}),e1=wi.extend({messages:ue(QN),modelPreferences:KN.optional(),systemPrompt:k().optional(),includeContext:Tt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:ue(k()).optional(),metadata:Ke.optional(),tools:ue(US).optional(),toolChoice:JN.optional()}),t1=et.extend({method:Z("sampling/createMessage"),params:e1}),Ai=tt.extend({model:k(),stopReason:Me(Tt(["endTurn","stopSequence","maxTokens"]).or(k())),role:Oi,content:XN}),Ff=tt.extend({model:k(),stopReason:Me(Tt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:Oi,content:Pe([zc,ue(zc)])}),r1=z({type:Z("boolean"),title:k().optional(),description:k().optional(),default:Je().optional()}),n1=z({type:Z("string"),title:k().optional(),description:k().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:Tt(["email","uri","date","date-time"]).optional(),default:k().optional()}),s1=z({type:Tt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),o1=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),default:k().optional()}),i1=z({type:Z("string"),title:k().optional(),description:k().optional(),oneOf:ue(z({const:k(),title:k()})),default:k().optional()}),a1=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),enumNames:ue(k()).optional(),default:k().optional()}),c1=Pe([o1,i1]),u1=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:Z("string"),enum:ue(k())}),default:ue(k()).optional()}),l1=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:ue(z({const:k(),title:k()}))}),default:ue(k()).optional()}),d1=Pe([u1,l1]),p1=Pe([a1,c1,d1]),m1=Pe([p1,r1,n1,s1]),f1=wi.extend({mode:Z("form").optional(),message:k(),requestedSchema:z({type:Z("object"),properties:$e(k(),m1),required:ue(k()).optional()})}),h1=wi.extend({mode:Z("url"),message:k(),elicitationId:k(),url:k().url()}),g1=Pe([f1,h1]),y1=et.extend({method:Z("elicitation/create"),params:g1}),_1=Gt.extend({elicitationId:k()}),v1=Kt.extend({method:Z("notifications/elicitation/complete"),params:_1}),uo=tt.extend({action:Tt(["accept","decline","cancel"]),content:wf(t=>t===null?void 0:t,$e(k(),Pe([k(),ge(),Je(),ue(k())])).optional())}),b1=z({type:Z("ref/resource"),uri:k()}),x1=z({type:Z("ref/prompt"),name:k()}),S1=Mt.extend({ref:Pe([x1,b1]),argument:z({name:k(),value:k()}),context:z({arguments:$e(k(),k()).optional()}).optional()}),eu=et.extend({method:Z("completion/complete"),params:S1});k1=tt.extend({completion:yt({values:ue(k()).max(100),total:Me(ge().int()),hasMore:Me(Je())})}),w1=z({uri:k().startsWith("file://"),name:k().optional(),_meta:$e(k(),De()).optional()}),E1=et.extend({method:Z("roots/list"),params:Mt.optional()}),Uf=tt.extend({roots:ue(w1)}),$1=Kt.extend({method:Z("notifications/roots/list_changed"),params:Gt.optional()}),D9=Pe([Zc,Of,eu,Lf,Xc,io,so,oo,Yc,EN,TN,co,ao,qc,Wc,Gc,Jc]),M9=Pe([Hc,Bc,If,$1,Ci]),j9=Pe([Uc,Ai,Ff,uo,Uf,Vc,Kc,ro]),z9=Pe([Zc,t1,y1,E1,qc,Wc,Gc,Jc]),L9=Pe([Hc,Bc,WN,RN,kN,BN,LN,Ci,v1]),F9=Pe([Uc,pN,k1,zN,IN,vN,bN,SN,Qc,HN,Vc,Kc,ro]),H=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===V.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Ef(s.elicitations,r)}return new t(e,r,n)}},Ef=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(V.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function vn(t){return t==="completed"||t==="failed"||t==="cancelled"}var BS=x(()=>{});var VS,qS,WS,tu=x(()=>{VS=Symbol("Let zodToJsonSchema decide on which parser to use"),qS={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"},WS=t=>typeof t=="string"?{...qS,name:t}:{...qS,...t}});var GS,Hf=x(()=>{tu();GS=t=>{let e=WS(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Zf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function le(t,e,r,n,s){t[e]=r,Zf(t,e,n,s)}var bn=x(()=>{});var ru,nu=x(()=>{ru=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ru(e,t.currentPath):e.join("/")}}var Jt=x(()=>{nu()});function KS(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==I.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&le(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(r,"minItems",t.exactLength.value,t.exactLength.message,e),le(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Bf=x(()=>{ci();bn();Ve()});function JS(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var qf=x(()=>{bn()});function YS(){return{type:"boolean"}}var Vf=x(()=>{});function su(t,e){return J(t.type._def,e)}var ou=x(()=>{Ve()});var XS,Wf=x(()=>{Ve();XS=(t,e)=>J(t.innerType._def,e)});function Gf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Gf(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return T1(t,e)}}var T1,Kf=x(()=>{bn();T1=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":le(r,"minimum",n.value,n.message,e);break;case"max":le(r,"maximum",n.value,n.message,e);break}return r}});function QS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var Jf=x(()=>{Ve()});function ek(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):je(e)}var Yf=x(()=>{Ve();Jt()});function tk(t){return{type:"string",enum:Array.from(t.values)}}var Xf=x(()=>{});function rk(t,e){let r=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(P1(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var P1,Qf=x(()=>{Ve();P1=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function nk(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var eh=x(()=>{});function iu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":pr(r,"email",n.message,e);break;case"format:idn-email":pr(r,"idn-email",n.message,e);break;case"pattern:zod":_t(r,dr.email,n.message,e);break}break;case"url":pr(r,"uri",n.message,e);break;case"uuid":pr(r,"uuid",n.message,e);break;case"regex":_t(r,n.regex,n.message,e);break;case"cuid":_t(r,dr.cuid,n.message,e);break;case"cuid2":_t(r,dr.cuid2,n.message,e);break;case"startsWith":_t(r,RegExp(`^${rh(n.value,e)}`),n.message,e);break;case"endsWith":_t(r,RegExp(`${rh(n.value,e)}$`),n.message,e);break;case"datetime":pr(r,"date-time",n.message,e);break;case"date":pr(r,"date",n.message,e);break;case"time":pr(r,"time",n.message,e);break;case"duration":pr(r,"duration",n.message,e);break;case"length":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{_t(r,RegExp(rh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&pr(r,"ipv4",n.message,e),n.version!=="v4"&&pr(r,"ipv6",n.message,e);break}case"base64url":_t(r,dr.base64url,n.message,e);break;case"jwt":_t(r,dr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&_t(r,dr.ipv4Cidr,n.message,e),n.version!=="v4"&&_t(r,dr.ipv6Cidr,n.message,e);break}case"emoji":_t(r,dr.emoji(),n.message,e);break;case"ulid":{_t(r,dr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pr(r,"binary",n.message,e);break}case"contentEncoding:base64":{le(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{_t(r,dr.base64,n.message,e);break}}break}case"nanoid":_t(r,dr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function rh(t,e){return e.patternStrategy==="escape"?C1(t):t}function C1(t){let e="";for(let r=0;r<t.length;r++)R1.has(t[r])||(e+="\\"),e+=t[r];return e}function pr(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):le(t,"format",e,r,n)}function _t(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:sk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):le(t,"pattern",sk(e,n),r,n)}function sk(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
65
|
-
]))`;continue}else if(n[c]==="$"){
|
|
66
|
-
]))`;continue}}if(r.s&&n[c]==="."){
|
|
184
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var bS=x(()=>{});var yt=x(()=>{ls();Fp();Ap();cS();jc();Vp();Ir();Mc();Zc();Dm();qp();_S();yS();vS();bS()});var wf=x(()=>{yt()});function Ef(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new KA(r)}var GA,KA,xS=x(()=>{yt();yt();wf();GA=T("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>Dp(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>_o(t,r,n),t.parseAsync=async(r,n)=>jp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>vo(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>jt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),KA=T("ZodMiniObject",(t,e)=>{Uc.init(t,e),GA.init(t,e),ue.defineLazy(t,"shape",()=>e.shape)})});var SS=x(()=>{});var kS=x(()=>{});var wS=x(()=>{});var ES=x(()=>{yt();wf();xS();SS();yt();Zc();kS();wS()});var $S=x(()=>{ES()});var $f=x(()=>{$S()});function Kt(t){return!!t._zod}function So(t){let e=Object.values(t);if(e.length===0)return Ef({});let r=e.every(Kt),n=e.every(o=>!Kt(o));if(r)return Ef(t);if(n)return bp(t);throw new Error("Mixed Zod versions detected in object shape.")}function wn(t,e){return Kt(t)?_o(t,e):t.safeParse(e)}async function Yc(t,e){return Kt(t)?await vo(t,e):await t.safeParseAsync(e)}function En(t){if(!t)return;let e;if(Kt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function fs(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return So(t)}}if(Kt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Xc(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function PS(t){return t.description}function RS(t){if(Kt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Qc(t){if(Kt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ji=x(()=>{wi();$f()});var Tf=x(()=>{yt()});var zi={};Le(zi,{ZodISODate:()=>OS,ZodISODateTime:()=>CS,ZodISODuration:()=>AS,ZodISOTime:()=>IS,date:()=>Rf,datetime:()=>Pf,duration:()=>Of,time:()=>Cf});function Pf(t){return pS(CS,t)}function Rf(t){return mS(OS,t)}function Cf(t){return fS(IS,t)}function Of(t){return hS(AS,t)}var CS,OS,IS,AS,If=x(()=>{yt();Af();CS=T("ZodISODateTime",(t,e)=>{nS.init(t,e),Ae.init(t,e)});OS=T("ZodISODate",(t,e)=>{oS.init(t,e),Ae.init(t,e)});IS=T("ZodISOTime",(t,e)=>{sS.init(t,e),Ae.init(t,e)});AS=T("ZodISODuration",(t,e)=>{iS.init(t,e),Ae.init(t,e)})});var NS,bV,Li,Nf=x(()=>{yt();yt();NS=(t,e)=>{Nc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ip(t,r)},flatten:{value:r=>Op(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},bV=T("ZodError",NS),Li=T("ZodError",NS,{Parent:Error})});var DS,MS,jS,zS,Df=x(()=>{yt();Nf();DS=Np(Li),MS=Mp(Li),jS=zp(Li),zS=Lp(Li)});function E(t){return Mm(sN,t)}function ge(t){return of(ZS,t)}function FS(t){return sf(kN,t)}function Qe(t){return af(wN,t)}function BS(t){return cf(EN,t)}function Ne(){return uf($N)}function PN(t){return lf(TN,t)}function le(t,e){return gS(RN,t,e)}function j(t,e){let r={type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},...ue.normalizeParams(e)};return new qS(r)}function _t(t,e){return new qS({type:"object",get shape(){return ue.assignProp(this,"shape",{...t}),this.shape},catchall:Ne(),...ue.normalizeParams(e)})}function Te(t,e){return new VS({type:"union",options:t,...ue.normalizeParams(e)})}function zf(t,e,r){return new CN({type:"union",options:e,discriminator:t,...ue.normalizeParams(r)})}function tu(t,e){return new ON({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new IN({type:"record",keyType:t,valueType:e,...ue.normalizeParams(r)})}function Rt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Mf({type:"enum",entries:r,...ue.normalizeParams(e)})}function q(t,e){return new AN({type:"literal",values:Array.isArray(t)?t:[t],...ue.normalizeParams(e)})}function WS(t){return new NN({type:"transform",transform:t})}function De(t){return new GS({type:"optional",innerType:t})}function US(t){return new DN({type:"nullable",innerType:t})}function jN(t,e){return new MN({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function LN(t,e){return new zN({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function FN(t,e){return new KS({type:"nonoptional",innerType:t,...ue.normalizeParams(e)})}function HN(t,e){return new UN({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function jf(t,e){return new ZN({type:"pipe",in:t,out:e})}function qN(t){return new BN({type:"readonly",innerType:t})}function VN(t){let e=new rt({check:"custom"});return e._zod.check=t,e}function YS(t,e){return xf(JS,t??(()=>!0),e)}function WN(t,e={}){return Sf(JS,t,e)}function GN(t){let e=VN(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ue.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ue.issue(o))}},t(r.value,r)));return e}function Lf(t,e){return jf(WS(t),e)}var He,HS,sN,Ae,iN,LS,eu,aN,cN,uN,lN,dN,pN,mN,fN,hN,gN,yN,_N,vN,bN,xN,SN,ZS,kN,wN,EN,$N,TN,RN,qS,VS,CN,ON,IN,Mf,AN,NN,GS,DN,MN,zN,KS,UN,ZN,BN,JS,Af=x(()=>{yt();yt();Tf();If();Df();He=T("ZodType",(t,e)=>(ve.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>jt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>DS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jS(t,r,n),t.parseAsync=async(r,n)=>MS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>zS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(WN(r,n)),t.superRefine=r=>t.check(GN(r)),t.overwrite=r=>t.check(bo(r)),t.optional=()=>De(t),t.nullable=()=>US(t),t.nullish=()=>De(US(t)),t.nonoptional=r=>FN(t,r),t.array=()=>le(t),t.or=r=>Te([t,r]),t.and=r=>tu(t,r),t.transform=r=>jf(t,WS(r)),t.default=r=>jN(t,r),t.prefault=r=>LN(t,r),t.catch=r=>HN(t,r),t.pipe=r=>jf(t,r),t.readonly=()=>qN(t),t.describe=r=>{let n=t.clone();return kn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kn.get(t);let n=t.clone();return kn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),HS=T("_ZodString",(t,e)=>{Ai.init(t,e),He.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(df(...n)),t.includes=(...n)=>t.check(ff(...n)),t.startsWith=(...n)=>t.check(hf(...n)),t.endsWith=(...n)=>t.check(gf(...n)),t.min=(...n)=>t.check(ms(...n)),t.max=(...n)=>t.check(Gc(...n)),t.length=(...n)=>t.check(Kc(...n)),t.nonempty=(...n)=>t.check(ms(1,...n)),t.lowercase=n=>t.check(pf(n)),t.uppercase=n=>t.check(mf(n)),t.trim=()=>t.check(_f()),t.normalize=(...n)=>t.check(yf(...n)),t.toLowerCase=()=>t.check(vf()),t.toUpperCase=()=>t.check(bf())}),sN=T("ZodString",(t,e)=>{Ai.init(t,e),HS.init(t,e),t.email=r=>t.check(jm(iN,r)),t.url=r=>t.check(Hm(aN,r)),t.jwt=r=>t.check(nf(SN,r)),t.emoji=r=>t.check(Zm(cN,r)),t.guid=r=>t.check(Bc(LS,r)),t.uuid=r=>t.check(zm(eu,r)),t.uuidv4=r=>t.check(Lm(eu,r)),t.uuidv6=r=>t.check(Fm(eu,r)),t.uuidv7=r=>t.check(Um(eu,r)),t.nanoid=r=>t.check(Bm(uN,r)),t.guid=r=>t.check(Bc(LS,r)),t.cuid=r=>t.check(qm(lN,r)),t.cuid2=r=>t.check(Vm(dN,r)),t.ulid=r=>t.check(Wm(pN,r)),t.base64=r=>t.check(ef(vN,r)),t.base64url=r=>t.check(tf(bN,r)),t.xid=r=>t.check(Gm(mN,r)),t.ksuid=r=>t.check(Km(fN,r)),t.ipv4=r=>t.check(Jm(hN,r)),t.ipv6=r=>t.check(Ym(gN,r)),t.cidrv4=r=>t.check(Xm(yN,r)),t.cidrv6=r=>t.check(Qm(_N,r)),t.e164=r=>t.check(rf(xN,r)),t.datetime=r=>t.check(Pf(r)),t.date=r=>t.check(Rf(r)),t.time=r=>t.check(Cf(r)),t.duration=r=>t.check(Of(r))});Ae=T("ZodStringFormat",(t,e)=>{we.init(t,e),HS.init(t,e)}),iN=T("ZodEmail",(t,e)=>{Jp.init(t,e),Ae.init(t,e)}),LS=T("ZodGUID",(t,e)=>{Gp.init(t,e),Ae.init(t,e)}),eu=T("ZodUUID",(t,e)=>{Kp.init(t,e),Ae.init(t,e)}),aN=T("ZodURL",(t,e)=>{Yp.init(t,e),Ae.init(t,e)}),cN=T("ZodEmoji",(t,e)=>{Xp.init(t,e),Ae.init(t,e)}),uN=T("ZodNanoID",(t,e)=>{Qp.init(t,e),Ae.init(t,e)}),lN=T("ZodCUID",(t,e)=>{em.init(t,e),Ae.init(t,e)}),dN=T("ZodCUID2",(t,e)=>{tm.init(t,e),Ae.init(t,e)}),pN=T("ZodULID",(t,e)=>{rm.init(t,e),Ae.init(t,e)}),mN=T("ZodXID",(t,e)=>{nm.init(t,e),Ae.init(t,e)}),fN=T("ZodKSUID",(t,e)=>{om.init(t,e),Ae.init(t,e)}),hN=T("ZodIPv4",(t,e)=>{sm.init(t,e),Ae.init(t,e)}),gN=T("ZodIPv6",(t,e)=>{im.init(t,e),Ae.init(t,e)}),yN=T("ZodCIDRv4",(t,e)=>{am.init(t,e),Ae.init(t,e)}),_N=T("ZodCIDRv6",(t,e)=>{cm.init(t,e),Ae.init(t,e)}),vN=T("ZodBase64",(t,e)=>{um.init(t,e),Ae.init(t,e)}),bN=T("ZodBase64URL",(t,e)=>{lm.init(t,e),Ae.init(t,e)}),xN=T("ZodE164",(t,e)=>{dm.init(t,e),Ae.init(t,e)}),SN=T("ZodJWT",(t,e)=>{pm.init(t,e),Ae.init(t,e)}),ZS=T("ZodNumber",(t,e)=>{Fc.init(t,e),He.init(t,e),t.gt=(n,o)=>t.check(Vc(n,o)),t.gte=(n,o)=>t.check(Mi(n,o)),t.min=(n,o)=>t.check(Mi(n,o)),t.lt=(n,o)=>t.check(qc(n,o)),t.lte=(n,o)=>t.check(Di(n,o)),t.max=(n,o)=>t.check(Di(n,o)),t.int=n=>t.check(FS(n)),t.safe=n=>t.check(FS(n)),t.positive=n=>t.check(Vc(0,n)),t.nonnegative=n=>t.check(Mi(0,n)),t.negative=n=>t.check(qc(0,n)),t.nonpositive=n=>t.check(Di(0,n)),t.multipleOf=(n,o)=>t.check(Wc(n,o)),t.step=(n,o)=>t.check(Wc(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});kN=T("ZodNumberFormat",(t,e)=>{mm.init(t,e),ZS.init(t,e)});wN=T("ZodBoolean",(t,e)=>{fm.init(t,e),He.init(t,e)});EN=T("ZodNull",(t,e)=>{hm.init(t,e),He.init(t,e)});$N=T("ZodUnknown",(t,e)=>{gm.init(t,e),He.init(t,e)});TN=T("ZodNever",(t,e)=>{ym.init(t,e),He.init(t,e)});RN=T("ZodArray",(t,e)=>{_m.init(t,e),He.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ms(r,n)),t.nonempty=r=>t.check(ms(1,r)),t.max=(r,n)=>t.check(Gc(r,n)),t.length=(r,n)=>t.check(Kc(r,n)),t.unwrap=()=>t.element});qS=T("ZodObject",(t,e)=>{Uc.init(t,e),He.init(t,e),ue.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Rt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ne()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ne()}),t.strict=()=>t.clone({...t._zod.def,catchall:PN()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ue.extend(t,r),t.merge=r=>ue.merge(t,r),t.pick=r=>ue.pick(t,r),t.omit=r=>ue.omit(t,r),t.partial=(...r)=>ue.partial(GS,t,r[0]),t.required=(...r)=>ue.required(KS,t,r[0])});VS=T("ZodUnion",(t,e)=>{Hc.init(t,e),He.init(t,e),t.options=e.options});CN=T("ZodDiscriminatedUnion",(t,e)=>{VS.init(t,e),vm.init(t,e)});ON=T("ZodIntersection",(t,e)=>{bm.init(t,e),He.init(t,e)});IN=T("ZodRecord",(t,e)=>{xm.init(t,e),He.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Mf=T("ZodEnum",(t,e)=>{Sm.init(t,e),He.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Mf({...e,checks:[],...ue.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Mf({...e,checks:[],...ue.normalizeParams(o),entries:s})}});AN=T("ZodLiteral",(t,e)=>{km.init(t,e),He.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]}})});NN=T("ZodTransform",(t,e)=>{wm.init(t,e),He.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ue.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ue.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});GS=T("ZodOptional",(t,e)=>{Em.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});DN=T("ZodNullable",(t,e)=>{$m.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});MN=T("ZodDefault",(t,e)=>{Tm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});zN=T("ZodPrefault",(t,e)=>{Pm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});KS=T("ZodNonOptional",(t,e)=>{Rm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType});UN=T("ZodCatch",(t,e)=>{Cm.init(t,e),He.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});ZN=T("ZodPipe",(t,e)=>{Om.init(t,e),He.init(t,e),t.in=e.in,t.out=e.out});BN=T("ZodReadonly",(t,e)=>{Im.init(t,e),He.init(t,e)});JS=T("ZodCustom",(t,e)=>{Am.init(t,e),He.init(t,e)})});var XS=x(()=>{});var QS=x(()=>{});var ek=x(()=>{yt();Af();Tf();Nf();Df();XS();yt();lS();Zc();If();QS();Mt(uS())});var tk=x(()=>{ek()});var rk=x(()=>{tk()});function vk(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function bk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Uf,nk,$n,nu,Je,ok,sk,MV,YN,XN,Hf,zt,Fi,ik,nt,Jt,Yt,ot,ou,ak,Zf,ck,uk,Bf,Ui,W,qf,lk,dk,jV,su,QN,iu,e1,Hi,hs,pk,t1,r1,n1,o1,s1,i1,Vf,a1,c1,Wf,au,u1,l1,cu,d1,Zi,Bi,p1,qi,gs,m1,Vi,uu,lu,du,zV,pu,mu,fu,mk,fk,hk,Gf,gk,Wi,ys,yk,f1,_s,h1,vs,g1,Kf,y1,hu,_1,v1,b1,x1,S1,k1,w1,E1,$1,T1,bs,P1,R1,gu,Jf,Yf,Xf,C1,O1,I1,Qf,A1,N1,D1,M1,j1,_k,xs,z1,yu,LV,L1,Ss,F1,FV,Gi,U1,eh,H1,Z1,B1,q1,V1,W1,G1,ru,K1,J1,Y1,Ki,th,X1,Q1,eD,tD,rD,nD,oD,sD,iD,aD,cD,uD,lD,dD,pD,mD,fD,hD,ks,gD,yD,_D,_u,vD,bD,xD,rh,SD,UV,HV,ZV,BV,qV,VV,Z,Ff,ko=x(()=>{rk();Uf="2025-11-25",nk=[Uf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],$n="io.modelcontextprotocol/related-task",nu="2.0",Je=YS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ok=Te([E(),ge().int()]),sk=E(),MV=_t({ttl:ge().optional(),pollInterval:ge().optional()}),YN=j({ttl:ge().optional()}),XN=j({taskId:E()}),Hf=_t({progressToken:ok.optional(),[$n]:XN.optional()}),zt=j({_meta:Hf.optional()}),Fi=zt.extend({task:YN.optional()}),ik=t=>Fi.safeParse(t).success,nt=j({method:E(),params:zt.loose().optional()}),Jt=j({_meta:Hf.optional()}),Yt=j({method:E(),params:Jt.loose().optional()}),ot=_t({_meta:Hf.optional()}),ou=Te([E(),ge().int()]),ak=j({jsonrpc:q(nu),id:ou,...nt.shape}).strict(),Zf=t=>ak.safeParse(t).success,ck=j({jsonrpc:q(nu),...Yt.shape}).strict(),uk=t=>ck.safeParse(t).success,Bf=j({jsonrpc:q(nu),id:ou,result:ot}).strict(),Ui=t=>Bf.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"})(W||(W={}));qf=j({jsonrpc:q(nu),id:ou.optional(),error:j({code:ge().int(),message:E(),data:Ne().optional()})}).strict(),lk=t=>qf.safeParse(t).success,dk=Te([ak,ck,Bf,qf]),jV=Te([Bf,qf]),su=ot.strict(),QN=Jt.extend({requestId:ou.optional(),reason:E().optional()}),iu=Yt.extend({method:q("notifications/cancelled"),params:QN}),e1=j({src:E(),mimeType:E().optional(),sizes:le(E()).optional(),theme:Rt(["light","dark"]).optional()}),Hi=j({icons:le(e1).optional()}),hs=j({name:E(),title:E().optional()}),pk=hs.extend({...hs.shape,...Hi.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),t1=tu(j({applyDefaults:Qe().optional()}),Ee(E(),Ne())),r1=Lf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,tu(j({form:t1.optional(),url:Je.optional()}),Ee(E(),Ne()).optional())),n1=_t({list:Je.optional(),cancel:Je.optional(),requests:_t({sampling:_t({createMessage:Je.optional()}).optional(),elicitation:_t({create:Je.optional()}).optional()}).optional()}),o1=_t({list:Je.optional(),cancel:Je.optional(),requests:_t({tools:_t({call:Je.optional()}).optional()}).optional()}),s1=j({experimental:Ee(E(),Je).optional(),sampling:j({context:Je.optional(),tools:Je.optional()}).optional(),elicitation:r1.optional(),roots:j({listChanged:Qe().optional()}).optional(),tasks:n1.optional(),extensions:Ee(E(),Je).optional()}),i1=zt.extend({protocolVersion:E(),capabilities:s1,clientInfo:pk}),Vf=nt.extend({method:q("initialize"),params:i1}),a1=j({experimental:Ee(E(),Je).optional(),logging:Je.optional(),completions:Je.optional(),prompts:j({listChanged:Qe().optional()}).optional(),resources:j({subscribe:Qe().optional(),listChanged:Qe().optional()}).optional(),tools:j({listChanged:Qe().optional()}).optional(),tasks:o1.optional(),extensions:Ee(E(),Je).optional()}),c1=ot.extend({protocolVersion:E(),capabilities:a1,serverInfo:pk,instructions:E().optional()}),Wf=Yt.extend({method:q("notifications/initialized"),params:Jt.optional()}),au=nt.extend({method:q("ping"),params:zt.optional()}),u1=j({progress:ge(),total:De(ge()),message:De(E())}),l1=j({...Jt.shape,...u1.shape,progressToken:ok}),cu=Yt.extend({method:q("notifications/progress"),params:l1}),d1=zt.extend({cursor:sk.optional()}),Zi=nt.extend({params:d1.optional()}),Bi=ot.extend({nextCursor:sk.optional()}),p1=Rt(["working","input_required","completed","failed","cancelled"]),qi=j({taskId:E(),status:p1,ttl:Te([ge(),BS()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:De(ge()),statusMessage:De(E())}),gs=ot.extend({task:qi}),m1=Jt.merge(qi),Vi=Yt.extend({method:q("notifications/tasks/status"),params:m1}),uu=nt.extend({method:q("tasks/get"),params:zt.extend({taskId:E()})}),lu=ot.merge(qi),du=nt.extend({method:q("tasks/result"),params:zt.extend({taskId:E()})}),zV=ot.loose(),pu=Zi.extend({method:q("tasks/list")}),mu=Bi.extend({tasks:le(qi)}),fu=nt.extend({method:q("tasks/cancel"),params:zt.extend({taskId:E()})}),mk=ot.merge(qi),fk=j({uri:E(),mimeType:De(E()),_meta:Ee(E(),Ne()).optional()}),hk=fk.extend({text:E()}),Gf=E().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),gk=fk.extend({blob:Gf}),Wi=Rt(["user","assistant"]),ys=j({audience:le(Wi).optional(),priority:ge().min(0).max(1).optional(),lastModified:zi.datetime({offset:!0}).optional()}),yk=j({...hs.shape,...Hi.shape,uri:E(),description:De(E()),mimeType:De(E()),size:De(ge()),annotations:ys.optional(),_meta:De(_t({}))}),f1=j({...hs.shape,...Hi.shape,uriTemplate:E(),description:De(E()),mimeType:De(E()),annotations:ys.optional(),_meta:De(_t({}))}),_s=Zi.extend({method:q("resources/list")}),h1=Bi.extend({resources:le(yk)}),vs=Zi.extend({method:q("resources/templates/list")}),g1=Bi.extend({resourceTemplates:le(f1)}),Kf=zt.extend({uri:E()}),y1=Kf,hu=nt.extend({method:q("resources/read"),params:y1}),_1=ot.extend({contents:le(Te([hk,gk]))}),v1=Yt.extend({method:q("notifications/resources/list_changed"),params:Jt.optional()}),b1=Kf,x1=nt.extend({method:q("resources/subscribe"),params:b1}),S1=Kf,k1=nt.extend({method:q("resources/unsubscribe"),params:S1}),w1=Jt.extend({uri:E()}),E1=Yt.extend({method:q("notifications/resources/updated"),params:w1}),$1=j({name:E(),description:De(E()),required:De(Qe())}),T1=j({...hs.shape,...Hi.shape,description:De(E()),arguments:De(le($1)),_meta:De(_t({}))}),bs=Zi.extend({method:q("prompts/list")}),P1=Bi.extend({prompts:le(T1)}),R1=zt.extend({name:E(),arguments:Ee(E(),E()).optional()}),gu=nt.extend({method:q("prompts/get"),params:R1}),Jf=j({type:q("text"),text:E(),annotations:ys.optional(),_meta:Ee(E(),Ne()).optional()}),Yf=j({type:q("image"),data:Gf,mimeType:E(),annotations:ys.optional(),_meta:Ee(E(),Ne()).optional()}),Xf=j({type:q("audio"),data:Gf,mimeType:E(),annotations:ys.optional(),_meta:Ee(E(),Ne()).optional()}),C1=j({type:q("tool_use"),name:E(),id:E(),input:Ee(E(),Ne()),_meta:Ee(E(),Ne()).optional()}),O1=j({type:q("resource"),resource:Te([hk,gk]),annotations:ys.optional(),_meta:Ee(E(),Ne()).optional()}),I1=yk.extend({type:q("resource_link")}),Qf=Te([Jf,Yf,Xf,I1,O1]),A1=j({role:Wi,content:Qf}),N1=ot.extend({description:E().optional(),messages:le(A1)}),D1=Yt.extend({method:q("notifications/prompts/list_changed"),params:Jt.optional()}),M1=j({title:E().optional(),readOnlyHint:Qe().optional(),destructiveHint:Qe().optional(),idempotentHint:Qe().optional(),openWorldHint:Qe().optional()}),j1=j({taskSupport:Rt(["required","optional","forbidden"]).optional()}),_k=j({...hs.shape,...Hi.shape,description:E().optional(),inputSchema:j({type:q("object"),properties:Ee(E(),Je).optional(),required:le(E()).optional()}).catchall(Ne()),outputSchema:j({type:q("object"),properties:Ee(E(),Je).optional(),required:le(E()).optional()}).catchall(Ne()).optional(),annotations:M1.optional(),execution:j1.optional(),_meta:Ee(E(),Ne()).optional()}),xs=Zi.extend({method:q("tools/list")}),z1=Bi.extend({tools:le(_k)}),yu=ot.extend({content:le(Qf).default([]),structuredContent:Ee(E(),Ne()).optional(),isError:Qe().optional()}),LV=yu.or(ot.extend({toolResult:Ne()})),L1=Fi.extend({name:E(),arguments:Ee(E(),Ne()).optional()}),Ss=nt.extend({method:q("tools/call"),params:L1}),F1=Yt.extend({method:q("notifications/tools/list_changed"),params:Jt.optional()}),FV=j({autoRefresh:Qe().default(!0),debounceMs:ge().int().nonnegative().default(300)}),Gi=Rt(["debug","info","notice","warning","error","critical","alert","emergency"]),U1=zt.extend({level:Gi}),eh=nt.extend({method:q("logging/setLevel"),params:U1}),H1=Jt.extend({level:Gi,logger:E().optional(),data:Ne()}),Z1=Yt.extend({method:q("notifications/message"),params:H1}),B1=j({name:E().optional()}),q1=j({hints:le(B1).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),V1=j({mode:Rt(["auto","required","none"]).optional()}),W1=j({type:q("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:le(Qf).default([]),structuredContent:j({}).loose().optional(),isError:Qe().optional(),_meta:Ee(E(),Ne()).optional()}),G1=zf("type",[Jf,Yf,Xf]),ru=zf("type",[Jf,Yf,Xf,C1,W1]),K1=j({role:Wi,content:Te([ru,le(ru)]),_meta:Ee(E(),Ne()).optional()}),J1=Fi.extend({messages:le(K1),modelPreferences:q1.optional(),systemPrompt:E().optional(),includeContext:Rt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:le(E()).optional(),metadata:Je.optional(),tools:le(_k).optional(),toolChoice:V1.optional()}),Y1=nt.extend({method:q("sampling/createMessage"),params:J1}),Ki=ot.extend({model:E(),stopReason:De(Rt(["endTurn","stopSequence","maxTokens"]).or(E())),role:Wi,content:G1}),th=ot.extend({model:E(),stopReason:De(Rt(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:Wi,content:Te([ru,le(ru)])}),X1=j({type:q("boolean"),title:E().optional(),description:E().optional(),default:Qe().optional()}),Q1=j({type:q("string"),title:E().optional(),description:E().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:Rt(["email","uri","date","date-time"]).optional(),default:E().optional()}),eD=j({type:Rt(["number","integer"]),title:E().optional(),description:E().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),tD=j({type:q("string"),title:E().optional(),description:E().optional(),enum:le(E()),default:E().optional()}),rD=j({type:q("string"),title:E().optional(),description:E().optional(),oneOf:le(j({const:E(),title:E()})),default:E().optional()}),nD=j({type:q("string"),title:E().optional(),description:E().optional(),enum:le(E()),enumNames:le(E()).optional(),default:E().optional()}),oD=Te([tD,rD]),sD=j({type:q("array"),title:E().optional(),description:E().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({type:q("string"),enum:le(E())}),default:le(E()).optional()}),iD=j({type:q("array"),title:E().optional(),description:E().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:j({anyOf:le(j({const:E(),title:E()}))}),default:le(E()).optional()}),aD=Te([sD,iD]),cD=Te([nD,oD,aD]),uD=Te([cD,X1,Q1,eD]),lD=Fi.extend({mode:q("form").optional(),message:E(),requestedSchema:j({type:q("object"),properties:Ee(E(),uD),required:le(E()).optional()})}),dD=Fi.extend({mode:q("url"),message:E(),elicitationId:E(),url:E().url()}),pD=Te([lD,dD]),mD=nt.extend({method:q("elicitation/create"),params:pD}),fD=Jt.extend({elicitationId:E()}),hD=Yt.extend({method:q("notifications/elicitation/complete"),params:fD}),ks=ot.extend({action:Rt(["accept","decline","cancel"]),content:Lf(t=>t===null?void 0:t,Ee(E(),Te([E(),ge(),Qe(),le(E())])).optional())}),gD=j({type:q("ref/resource"),uri:E()}),yD=j({type:q("ref/prompt"),name:E()}),_D=zt.extend({ref:Te([yD,gD]),argument:j({name:E(),value:E()}),context:j({arguments:Ee(E(),E()).optional()}).optional()}),_u=nt.extend({method:q("completion/complete"),params:_D});vD=ot.extend({completion:_t({values:le(E()).max(100),total:De(ge().int()),hasMore:De(Qe())})}),bD=j({uri:E().startsWith("file://"),name:E().optional(),_meta:Ee(E(),Ne()).optional()}),xD=nt.extend({method:q("roots/list"),params:zt.optional()}),rh=ot.extend({roots:le(bD)}),SD=Yt.extend({method:q("notifications/roots/list_changed"),params:Jt.optional()}),UV=Te([au,Vf,_u,eh,gu,bs,_s,vs,hu,x1,k1,Ss,xs,uu,du,pu,fu]),HV=Te([iu,cu,Wf,SD,Vi]),ZV=Te([su,Ki,th,ks,rh,lu,mu,gs]),BV=Te([au,Y1,mD,xD,uu,du,pu,fu]),qV=Te([iu,cu,Z1,E1,v1,F1,D1,Vi,hD]),VV=Te([su,c1,vD,N1,P1,h1,g1,_1,yu,z1,lu,mu,gs]),Z=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===W.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ff(o.elicitations,r)}return new t(e,r,n)}},Ff=class extends Z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Tn(t){return t==="completed"||t==="failed"||t==="cancelled"}var xk=x(()=>{});var kk,Sk,wk,vu=x(()=>{kk=Symbol("Let zodToJsonSchema decide on which parser to use"),Sk={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"},wk=t=>typeof t=="string"?{...Sk,name:t}:{...Sk,...t}});var Ek,nh=x(()=>{vu();Ek=t=>{let e=wk(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function oh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function de(t,e,r,n,o){t[e]=r,oh(t,e,n,o)}var Pn=x(()=>{});var bu,xu=x(()=>{bu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Me(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?bu(e,t.currentPath):e.join("/")}}var Xt=x(()=>{xu()});function $k(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==I.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&de(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&de(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(de(r,"minItems",t.exactLength.value,t.exactLength.message,e),de(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var sh=x(()=>{wi();Pn();We()});function Tk(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var ih=x(()=>{Pn()});function Pk(){return{type:"boolean"}}var ah=x(()=>{});function Su(t,e){return Y(t.type._def,e)}var ku=x(()=>{We()});var Rk,ch=x(()=>{We();Rk=(t,e)=>Y(t.innerType._def,e)});function uh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>uh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return kD(t,e)}}var kD,lh=x(()=>{Pn();kD=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":de(r,"minimum",n.value,n.message,e);break;case"max":de(r,"maximum",n.value,n.message,e);break}return r}});function Ck(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var dh=x(()=>{We()});function Ok(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Me(e)}var ph=x(()=>{We();Xt()});function Ik(t){return{type:"string",enum:Array.from(t.values)}}var mh=x(()=>{});function Ak(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(wD(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var wD,fh=x(()=>{We();wD=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Nk(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var hh=x(()=>{});function wu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":fr(r,"email",n.message,e);break;case"format:idn-email":fr(r,"idn-email",n.message,e);break;case"pattern:zod":vt(r,mr.email,n.message,e);break}break;case"url":fr(r,"uri",n.message,e);break;case"uuid":fr(r,"uuid",n.message,e);break;case"regex":vt(r,n.regex,n.message,e);break;case"cuid":vt(r,mr.cuid,n.message,e);break;case"cuid2":vt(r,mr.cuid2,n.message,e);break;case"startsWith":vt(r,RegExp(`^${yh(n.value,e)}`),n.message,e);break;case"endsWith":vt(r,RegExp(`${yh(n.value,e)}$`),n.message,e);break;case"datetime":fr(r,"date-time",n.message,e);break;case"date":fr(r,"date",n.message,e);break;case"time":fr(r,"time",n.message,e);break;case"duration":fr(r,"duration",n.message,e);break;case"length":de(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),de(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{vt(r,RegExp(yh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&fr(r,"ipv4",n.message,e),n.version!=="v4"&&fr(r,"ipv6",n.message,e);break}case"base64url":vt(r,mr.base64url,n.message,e);break;case"jwt":vt(r,mr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&vt(r,mr.ipv4Cidr,n.message,e),n.version!=="v4"&&vt(r,mr.ipv6Cidr,n.message,e);break}case"emoji":vt(r,mr.emoji(),n.message,e);break;case"ulid":{vt(r,mr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{fr(r,"binary",n.message,e);break}case"contentEncoding:base64":{de(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{vt(r,mr.base64,n.message,e);break}}break}case"nanoid":vt(r,mr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function yh(t,e){return e.patternStrategy==="escape"?$D(t):t}function $D(t){let e="";for(let r=0;r<t.length;r++)ED.has(t[r])||(e+="\\"),e+=t[r];return e}function fr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):de(t,"format",e,r,n)}function vt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Dk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):de(t,"pattern",Dk(e,n),r,n)}function Dk(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
185
|
+
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
186
|
+
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
67
187
|
`:`[${n[c]}\r
|
|
68
|
-
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}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 s}var th,dr,R1,au=x(()=>{bn();dr={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:()=>(th===void 0&&(th=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),th),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-_]*$/};R1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function cu(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===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=iu(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===I.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===I.ZodBranded&&t.keyType._def.type._def.typeName===I.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=su(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var uu=x(()=>{ci();Ve();au();ou();Jt()});function ok(t,e){if(e.mapStrategy==="record")return cu(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var nh=x(()=>{Ve();uu();Jt()});function ik(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var sh=x(()=>{});function ak(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var oh=x(()=>{Jt()});function ck(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ih=x(()=>{});function lk(t,e){if(e.target==="openApi3")return uk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ni&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Ni[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return uk(t,e)}var Ni,uk,lu=x(()=>{Ve();Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};uk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function dk(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:Ni[t.innerType._def.typeName],nullable:!0}:{type:[Ni[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var ah=x(()=>{Ve();lu()});function pk(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Zf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var ch=x(()=>{bn()});function mk(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=I1(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=J(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||s.push(a))}s.length&&(n.required=s);let i=O1(t,e);return i!==void 0&&(n.additionalProperties=i),n}function O1(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 I1(t){try{return t.isOptional()}catch{return!0}}var uh=x(()=>{Ve()});var fk,lh=x(()=>{Ve();Jt();fk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(e)},r]}:je(e)}});var hk,dh=x(()=>{Ve();hk=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let r=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function gk(t,e){return J(t.type._def,e)}var ph=x(()=>{Ve()});function yk(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var mh=x(()=>{bn();Ve()});function _k(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>J(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var fh=x(()=>{Ve()});function vk(t){return{not:je(t)}}var hh=x(()=>{Jt()});function bk(t){return je(t)}var gh=x(()=>{Jt()});var xk,yh=x(()=>{Ve();xk=(t,e)=>J(t.innerType._def,e)});var Sk,_h=x(()=>{ci();Jt();Bf();qf();Vf();ou();Wf();Kf();Jf();Yf();Xf();Qf();eh();nh();sh();oh();ih();ah();ch();uh();lh();dh();ph();uu();mh();au();fh();hh();lu();gh();yh();Sk=(t,e,r)=>{switch(e){case I.ZodString:return iu(t,r);case I.ZodNumber:return pk(t,r);case I.ZodObject:return mk(t,r);case I.ZodBigInt:return JS(t,r);case I.ZodBoolean:return YS();case I.ZodDate:return Gf(t,r);case I.ZodUndefined:return vk(r);case I.ZodNull:return ck(r);case I.ZodArray:return KS(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return lk(t,r);case I.ZodIntersection:return rk(t,r);case I.ZodTuple:return _k(t,r);case I.ZodRecord:return cu(t,r);case I.ZodLiteral:return nk(t,r);case I.ZodEnum:return tk(t);case I.ZodNativeEnum:return ik(t);case I.ZodNullable:return dk(t,r);case I.ZodOptional:return fk(t,r);case I.ZodMap:return ok(t,r);case I.ZodSet:return yk(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return gk(t,r);case I.ZodNaN:case I.ZodNever:return ak(r);case I.ZodEffects:return ek(t,r);case I.ZodAny:return je(r);case I.ZodUnknown:return bk(r);case I.ZodDefault:return QS(t,r);case I.ZodBranded:return su(t,r);case I.ZodReadonly:return xk(t,r);case I.ZodCatch:return XS(t,r);case I.ZodPipeline:return hk(t,r);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(n=>{})(e)}}});function J(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==VS)return a}if(n&&!r){let a=A1(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=Sk(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&N1(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var A1,N1,Ve=x(()=>{tu();_h();nu();Jt();A1=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ru(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},N1=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var kk=x(()=>{});var vh,bh=x(()=>{Ve();Hf();Jt();vh=(t,e)=>{let r=GS(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:J(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??je(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var wk=x(()=>{tu();Hf();bn();nu();Ve();kk();Jt();Bf();qf();Vf();ou();Wf();Kf();Jf();Yf();Xf();Qf();eh();nh();sh();oh();ih();ah();ch();uh();lh();dh();ph();yh();uu();mh();au();fh();hh();lu();gh();_h();bh();bh()});function D1(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function xh(t,e){return Wt(t)?cf(t,{target:D1(e?.target),io:e?.pipeStrategy??"input"}):vh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Sh(t){let r=yn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Dc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function kh(t,e){let r=gn(t,e);if(!r.success)throw r.error;return r.data}var wh=x(()=>{df();xi();wk()});function Ek(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function $k(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];Ek(i)&&Ek(o)?r[s]={...i,...o}:r[s]=o}return r}var M1,du,Tk=x(()=>{xi();hs();BS();wh();M1=6e4,du=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(Hc,r=>{this._oncancel(r)}),this.setNotificationHandler(Bc,r=>{this._onprogress(r)}),this.setRequestHandler(Zc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Wc,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new H(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${o}`);if(!vn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(vn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[_n]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Gc,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new H(V.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Jc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(vn(s.status))throw new H(V.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof H?s:new H(V.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),H.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Ei(o)||AS(o)?this._onresponse(o):Pf(o)?this._onrequest(o,i):IS(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[_n]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:V.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):s?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=RS(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};o&&(l.relatedTask={taskId:o}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new H(V.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let p=f.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:V.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId):await s?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ei(e))n(e);else{let i=new H(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ei(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),Ei(e))s(e);else{let i=H.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}return}let o;try{let i=await this.request(e,ro,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},vn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new H(V.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(V.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof H?i:new H(V.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[_n]:c}});let p=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let _=v instanceof H?v:new H(V.RequestTimeout,String(v));d(_)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let _=gn(r,v.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??M1,g=()=>p(H.fromError(V.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=_=>{let b=this._responseHandlers.get(m);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Vc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Kc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},MS,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[_n]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[_n]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[_n]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Sh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=kh(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Sh(e);this._notificationHandlers.set(n,s=>{let o=kh(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Pf(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new H(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new H(V.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new H(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new H(V.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=Ci.parse({method:"notifications/tasks/status",params:a});await this.notification(c),vn(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new H(V.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(vn(a.status))throw new H(V.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=Ci.parse({method:"notifications/tasks/status",params:c});await this.notification(u),vn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var ji=M(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 Di=class{};he._CodeOrName=Di;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var gs=class extends Di{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=gs;var Yt=class extends Di{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof gs&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Yt;he.nil=new Yt("");function Pk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)$h(r,e[n]),r.push(t[++n]);return new Yt(r)}he._=Pk;var Eh=new Yt("+");function Rk(t,...e){let r=[Mi(t[0])],n=0;for(;n<e.length;)r.push(Eh),$h(r,e[n]),r.push(Eh,Mi(t[++n]));return j1(r),new Yt(r)}he.str=Rk;function $h(t,e){e instanceof Yt?t.push(...e._items):e instanceof gs?t.push(e):t.push(F1(e))}he.addCodeArg=$h;function j1(t){let e=1;for(;e<t.length-1;){if(t[e]===Eh){let r=z1(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function z1(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof gs||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 gs))return`"${t}${e.slice(1)}`}function L1(t,e){return e.emptyStr()?t:t.emptyStr()?e:Rk`${t}${e}`}he.strConcat=L1;function F1(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Mi(Array.isArray(t)?t.join(","):t)}function U1(t){return new Yt(Mi(t))}he.stringify=U1;function Mi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Mi;function H1(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Yt(`.${t}`):Pk`[${t}]`}he.getProperty=H1;function Z1(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Z1;function B1(t){return new Yt(t.toString())}he.regexpCode=B1});var Rh=M(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.ValueScope=Rt.ValueScopeName=Rt.Scope=Rt.varKinds=Rt.UsedValueState=void 0;var Pt=ji(),Th=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},pu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(pu||(Rt.UsedValueState=pu={}));Rt.varKinds={const:new Pt.Name("const"),let:new Pt.Name("let"),var:new Pt.Name("var")};var mu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Pt.Name?e:this.name(e)}name(e){return new Pt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Rt.Scope=mu;var fu=class extends Pt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Pt._)`.${new Pt.Name(r)}[${n}]`}};Rt.ValueScopeName=fu;var q1=(0,Pt._)`\n`,Ph=class extends mu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?q1:Pt.nil}}get(){return this._scope}name(e){return new fu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(i);if(d)return d}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Pt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=Pt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,pu.Started);let d=r(u);if(d){let l=this.opts.es5?Rt.varKinds.var:Rt.varKinds.const;o=(0,Pt._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,Pt._)`${o}${d}${this.opts._n}`;else throw new Th(u);c.set(u,pu.Completed)})}return o}};Rt.ValueScope=Ph});var re=M(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var de=ji(),mr=Rh(),xn=ji();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return xn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return xn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return xn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return xn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return xn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return xn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return xn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return xn.Name}});var _u=Rh();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return _u.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return _u.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return _u.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return _u.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var qr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ch=class extends qr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?mr.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=po(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},hu=class extends qr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=po(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return yu(e,this.rhs)}},Oh=class extends hu{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ih=class extends qr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ah=class extends qr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Nh=class extends qr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Dh=class extends qr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=po(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},zi=class extends qr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(V1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>vs(e,r.names),{})}},Vr=class extends zi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Mh=class extends zi{},lo=class extends Vr{};lo.kind="else";var ys=class t extends Vr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new lo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ck(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=po(this.condition,e,r),this}get names(){let e=super.names;return yu(e,this.condition),this.else&&vs(e,this.else.names),e}};ys.kind="if";var _s=class extends Vr{};_s.kind="for";var jh=class extends _s{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=po(this.iteration,e,r),this}get names(){return vs(super.names,this.iteration.names)}},zh=class extends _s{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?mr.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=yu(super.names,this.from);return yu(e,this.to)}},gu=class extends _s{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=po(this.iterable,e,r),this}get names(){return vs(super.names,this.iterable.names)}},Li=class extends Vr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Li.kind="func";var Fi=class extends zi{render(e){return"return "+super.render(e)}};Fi.kind="return";var Lh=class extends Vr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&vs(e,this.catch.names),this.finally&&vs(e,this.finally.names),e}},Ui=class extends Vr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ui.kind="catch";var Hi=class extends Vr{render(e){return"finally"+super.render(e)}};Hi.kind="finally";var Fh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
69
|
-
`:""},this._extScope=e,this._scope=new mr.Scope({parent:e}),this._nodes=[new Mh]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Ch(e,o,n)),o}const(e,r,n){return this._def(mr.varKinds.const,e,r,n)}let(e,r,n){return this._def(mr.varKinds.let,e,r,n)}var(e,r,n){return this._def(mr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new hu(e,r,n))}add(e,r){return this._leafNode(new Oh(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new Dh(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,s));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new ys(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new ys(e))}else(){return this._elseNode(new lo)}endIf(){return this._endBlockNode(ys,lo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new jh(e),r)}forRange(e,r,n,s,o=this.opts.es5?mr.varKinds.var:mr.varKinds.let){let i=this._scope.toName(e);return this._for(new zh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=mr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(o,(0,de._)`${i}[${a}]`),n(o)})}return this._for(new gu("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?mr.varKinds.var:mr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new gu("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(_s)}label(e){return this._leafNode(new Ih(e))}break(e){return this._leafNode(new Ah(e))}return(e){let r=new Fi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Fi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Lh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Ui(o),r(o)}return n&&(this._currNode=s.finally=new Hi,this.code(n)),this._endBlockNode(Ui,Hi)}throw(e){return this._leafNode(new Nh(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=de.nil,n,s){return this._blockNode(new Li(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Li)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof ys))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=Fh;function vs(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function yu(t,e){return e instanceof de._CodeOrName?vs(t,e.names):t}function po(t,e,r){if(t instanceof de.Name)return n(t);if(!s(t))return t;return new de._Code(t._items.reduce((o,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof de._Code&&o._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function V1(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ck(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${Uh(t)}`}ne.not=Ck;var W1=Ok(ne.operators.AND);function G1(...t){return t.reduce(W1)}ne.and=G1;var K1=Ok(ne.operators.OR);function J1(...t){return t.reduce(K1)}ne.or=J1;function Ok(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${Uh(e)} ${t} ${Uh(r)}`}function Uh(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var pe=M(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var xe=re(),Y1=ji();function X1(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=X1;function Q1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Nk(t,e),!Dk(e,t.self.RULES.all))}se.alwaysValidSchema=Q1;function Nk(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||zk(t,`unknown keyword: "${o}"`)}se.checkUnknownRules=Nk;function Dk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=Dk;function eD(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=eD;function tD({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(n)}`}se.schemaRefOrVal=tD;function rD(t){return Mk(decodeURIComponent(t))}se.unescapeFragment=rD;function nD(t){return encodeURIComponent(Zh(t))}se.escapeFragment=nD;function Zh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=Zh;function Mk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=Mk;function sD(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=sD;function Ik({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof xe.Name?(o instanceof xe.Name?t(s,o,i):e(s,o,i),i):o instanceof xe.Name?(e(s,i,o),o):r(o,i);return a===xe.Name&&!(c instanceof xe.Name)?n(s,c):c}}se.mergeEvaluated={props:Ik({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,xe._)`${r} || {}`),Bh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:jk}),items:Ik({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,xe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,xe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function jk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,xe._)`{}`);return e!==void 0&&Bh(t,r,e),r}se.evaluatedPropsToName=jk;function Bh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(n)}`,!0))}se.setEvaluated=Bh;var Ak={};function oD(t,e){return t.scopeValue("func",{ref:e,code:Ak[e.code]||(Ak[e.code]=new Y1._Code(e.code))})}se.useFunc=oD;var Hh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Hh||(se.Type=Hh={}));function iD(t,e,r){if(t instanceof xe.Name){let n=e===Hh.Num;return r?n?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:n?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(t).toString():"/"+Zh(t)}se.getErrorPath=iD;function zk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=zk});var Wr=M(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var lt=re(),aD={data:new lt.Name("data"),valCxt:new lt.Name("valCxt"),instancePath:new lt.Name("instancePath"),parentData:new lt.Name("parentData"),parentDataProperty:new lt.Name("parentDataProperty"),rootData:new lt.Name("rootData"),dynamicAnchors:new lt.Name("dynamicAnchors"),vErrors:new lt.Name("vErrors"),errors:new lt.Name("errors"),this:new lt.Name("this"),self:new lt.Name("self"),scope:new lt.Name("scope"),json:new lt.Name("json"),jsonPos:new lt.Name("jsonPos"),jsonLen:new lt.Name("jsonLen"),jsonPart:new lt.Name("jsonPart")};qh.default=aD});var Zi=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.extendErrors=dt.resetErrorsCount=dt.reportExtraError=dt.reportError=dt.keyword$DataError=dt.keywordError=void 0;var me=re(),vu=pe(),vt=Wr();dt.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};dt.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 cD(t,e=dt.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Uk(t,e,r);n??(i||a)?Lk(o,c):Fk(s,(0,me._)`[${c}]`)}dt.reportError=cD;function uD(t,e=dt.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Uk(t,e,r);Lk(s,a),o||i||Fk(n,vt.default.vErrors)}dt.reportExtraError=uD;function lD(t,e){t.assign(vt.default.errors,e),t.if((0,me._)`${vt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${vt.default.vErrors}.length`,e),()=>t.assign(vt.default.vErrors,null)))}dt.resetErrorsCount=lD;function dD({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,vt.default.errors,a=>{t.const(i,(0,me._)`${vt.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(vt.default.instancePath,o.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,me._)`${i}.schema`,r),t.assign((0,me._)`${i}.data`,n))})}dt.extendErrors=dD;function Lk(t,e){let r=t.const("err",e);t.if((0,me._)`${vt.default.vErrors} === null`,()=>t.assign(vt.default.vErrors,(0,me._)`[${r}]`),(0,me._)`${vt.default.vErrors}.push(${r})`),t.code((0,me._)`${vt.default.errors}++`)}function Fk(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,me._)`new ${t.ValidationError}(${e})`):(r.assign((0,me._)`${n}.errors`,e),r.return(!1))}var bs={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 Uk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,me._)`{}`:pD(t,e,r)}function pD(t,e,r={}){let{gen:n,it:s}=t,o=[mD(s,r),fD(t,r)];return hD(t,e,o),n.object(...o)}function mD({errorPath:t},{instancePath:e}){let r=e?(0,me.str)`${t}${(0,vu.getErrorPath)(e,vu.Type.Str)}`:t;return[vt.default.instancePath,(0,me.strConcat)(vt.default.instancePath,r)]}function fD({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,me.str)`${e}/${t}`;return r&&(s=(0,me.str)`${s}${(0,vu.getErrorPath)(r,vu.Type.Str)}`),[bs.schemaPath,s]}function hD(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([bs.keyword,s],[bs.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&n.push([bs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([bs.schema,i],[bs.parentSchema,(0,me._)`${d}${l}`],[vt.default.data,o]),u&&n.push([bs.propertyName,u])}});var Zk=M(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.boolOrEmptySchema=mo.topBoolOrEmptySchema=void 0;var gD=Zi(),yD=re(),_D=Wr(),vD={message:"boolean schema is false"};function bD(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Hk(t,!1):typeof r=="object"&&r.$async===!0?e.return(_D.default.data):(e.assign((0,yD._)`${n}.errors`,null),e.return(!0))}mo.topBoolOrEmptySchema=bD;function xD(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Hk(t)):r.var(e,!0)}mo.boolOrEmptySchema=xD;function Hk(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gD.reportError)(s,vD,void 0,e)}});var Vh=M(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.getRules=fo.isJSONType=void 0;var SD=["string","number","integer","boolean","null","object","array"],kD=new Set(SD);function wD(t){return typeof t=="string"&&kD.has(t)}fo.isJSONType=wD;function ED(){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:{}}}fo.getRules=ED});var Wh=M(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.shouldUseRule=Sn.shouldUseGroup=Sn.schemaHasRulesForType=void 0;function $D({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Bk(t,n)}Sn.schemaHasRulesForType=$D;function Bk(t,e){return e.rules.some(r=>qk(t,r))}Sn.shouldUseGroup=Bk;function qk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Sn.shouldUseRule=qk});var Bi=M(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.reportTypeError=pt.checkDataTypes=pt.checkDataType=pt.coerceAndCheckDataType=pt.getJSONTypes=pt.getSchemaTypes=pt.DataType=void 0;var TD=Vh(),PD=Wh(),RD=Zi(),ee=re(),Vk=pe(),ho;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ho||(pt.DataType=ho={}));function CD(t){let e=Wk(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}pt.getSchemaTypes=CD;function Wk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(TD.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}pt.getJSONTypes=Wk;function OD(t,e){let{gen:r,data:n,opts:s}=t,o=ID(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,PD.schemaHasRulesForType)(t,e[0]));if(i){let a=Kh(e,n,s.strictNumbers,ho.Wrong);r.if(a,()=>{o.length?AD(t,e,o):Jh(t)})}return i}pt.coerceAndCheckDataType=OD;var Gk=new Set(["string","number","integer","boolean","null"]);function ID(t,e){return e?t.filter(r=>Gk.has(r)||e==="array"&&r==="array"):[]}function AD(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,ee._)`typeof ${s}`),a=n.let("coerced",(0,ee._)`undefined`);o.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,ee._)`${s}[0]`).assign(i,(0,ee._)`typeof ${s}`).if(Kh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(Gk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Jh(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(s,a),ND(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${s}`).elseIf((0,ee._)`${s} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${s} === null
|
|
70
|
-
|| (${i} == "string" && ${
|
|
71
|
-
|| (${i} === "string" && ${
|
|
72
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function ND({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function Gh(t,e,r,n=ho.Correct){let s=n===ho.Correct?ee.operators.EQ:ee.operators.NEQ,o;switch(t){case"null":return(0,ee._)`${e} ${s} null`;case"array":o=(0,ee._)`Array.isArray(${e})`;break;case"object":o=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,ee._)`typeof ${e} ${s} ${t}`}return n===ho.Correct?o:(0,ee.not)(o);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}pt.checkDataType=Gh;function Kh(t,e,r,n){if(t.length===1)return Gh(t[0],e,r,n);let s,o=(0,Vk.toHash)(t);if(o.array&&o.object){let i=(0,ee._)`typeof ${e} != "object"`;s=o.null?i:(0,ee._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=ee.nil;o.number&&delete o.integer;for(let i in o)s=(0,ee.and)(s,Gh(i,e,r,n));return s}pt.checkDataTypes=Kh;var DD={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function Jh(t){let e=MD(t);(0,RD.reportError)(e,DD)}pt.reportTypeError=Jh;function MD(t){let{gen:e,data:r,schema:n}=t,s=(0,Vk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Jk=M(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.assignDefaults=void 0;var go=re(),jD=pe();function zD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Kk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Kk(t,o,s.default))}bu.assignDefaults=zD;function Kk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,go._)`${o}${(0,go.getProperty)(e)}`;if(s){(0,jD.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,go._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,go._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,go._)`${a} = ${(0,go.stringify)(r)}`)}});var Xt=M(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Re=re(),Yh=pe(),kn=Wr(),LD=pe();function FD(t,e){let{gen:r,data:n,it:s}=t;r.if(Qh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}be.checkReportMissingProp=FD;function UD({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(Qh(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}be.checkMissingProp=UD;function HD(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=HD;function Yk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Yk;function Xh(t,e,r){return(0,Re._)`${Yk(t)}.call(${e}, ${r})`}be.isOwnProperty=Xh;function ZD(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${Xh(t,e,r)}`:s}be.propertyInData=ZD;function Qh(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(Xh(t,e,r))):s}be.noPropertyInData=Qh;function Xk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Xk;function BD(t,e){return Xk(e).filter(r=>!(0,Yh.alwaysValidSchema)(t,e[r]))}be.schemaProperties=BD;function qD({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Re._)`${t}, ${e}, ${n}${s}`:e,l=[[kn.default.instancePath,(0,Re.strConcat)(kn.default.instancePath,o)],[kn.default.parentData,i.parentData],[kn.default.parentDataProperty,i.parentDataProperty],[kn.default.rootData,kn.default.rootData]];i.opts.dynamicRef&&l.push([kn.default.dynamicAnchors,kn.default.dynamicAnchors]);let m=(0,Re._)`${d}, ${r.object(...l)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${m})`:(0,Re._)`${a}(${m})`}be.callValidateCode=qD;var VD=(0,Re._)`new RegExp`;function WD({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Re._)`${s.code==="new RegExp"?VD:(0,LD.useFunc)(t,s)}(${r}, ${n})`})}be.usePattern=WD;function GD(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Yh.Type.Num},o),e.if((0,Re.not)(o),a)})}}be.validateArray=GD;function KD(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Yh.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Re._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=KD});var t0=M(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.validateKeywordUsage=Rr.validSchemaType=Rr.funcKeywordCode=Rr.macroKeywordCode=void 0;var bt=re(),xs=Wr(),JD=Xt(),YD=Zi();function XD(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=e0(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:bt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rr.macroKeywordCode=XD;function QD(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;tM(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=e0(n,s,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)h(),e.modifying&&Qk(t),g(()=>t.error());else{let y=e.async?f():p();e.modifying&&Qk(t),g(()=>eM(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,bt._)`await `),v=>n.assign(l,!1).if((0,bt._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,bt._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,bt._)`${d}.errors`;return n.assign(y,null),h(bt.nil),y}function h(y=e.async?(0,bt._)`await `:bt.nil){let v=c.opts.passContext?xs.default.this:xs.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,bt._)`${y}${(0,JD.callValidateCode)(t,d,v,_)}`,e.modifying)}function g(y){var v;n.if((0,bt.not)((v=e.valid)!==null&&v!==void 0?v:l),y)}}Rr.funcKeywordCode=QD;function Qk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,bt._)`${n.parentData}[${n.parentDataProperty}]`))}function eM(t,e){let{gen:r}=t;r.if((0,bt._)`Array.isArray(${e})`,()=>{r.assign(xs.default.vErrors,(0,bt._)`${xs.default.vErrors} === null ? ${e} : ${xs.default.vErrors}.concat(${e})`).assign(xs.default.errors,(0,bt._)`${xs.default.vErrors}.length`),(0,YD.extendErrors)(t)},()=>t.error())}function tM({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function e0(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,bt.stringify)(r)})}function rM(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Rr.validSchemaType=rM;function nM({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Rr.validateKeywordUsage=nM});var n0=M(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.extendSubschemaMode=wn.extendSubschemaData=wn.getSubschema=void 0;var Cr=re(),r0=pe();function sM(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Cr._)`${t.schemaPath}${(0,Cr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Cr._)`${t.schemaPath}${(0,Cr.getProperty)(e)}${(0,Cr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,r0.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}wn.getSubschema=sM;function oM(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,m=a.let("data",(0,Cr._)`${e.data}${(0,Cr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Cr.str)`${u}${(0,r0.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Cr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Cr.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}wn.extendSubschemaData=oM;function iM(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}wn.extendSubschemaMode=iM});var eg=M((r5,s0)=>{"use strict";s0.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var i0=M((n5,o0)=>{"use strict";var En=o0.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};xu(e,n,s,t,"",t)};En.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};En.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};En.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};En.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 xu(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in En.arrayKeywords)for(var m=0;m<l.length;m++)xu(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in En.propsKeywords){if(l&&typeof l=="object")for(var f in l)xu(t,e,r,l[f],s+"/"+d+"/"+aM(f),o,s,d,n,f)}else(d in En.keywords||t.allKeys&&!(d in En.skipKeywords))&&xu(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function aM(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var qi=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getSchemaRefs=Ct.resolveUrl=Ct.normalizeId=Ct._getFullPath=Ct.getFullPath=Ct.inlineRef=void 0;var cM=pe(),uM=eg(),lM=i0(),dM=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function pM(t,e=!0){return typeof t=="boolean"?!0:e===!0?!tg(t):e?a0(t)<=e:!1}Ct.inlineRef=pM;var mM=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function tg(t){for(let e in t){if(mM.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(tg)||typeof r=="object"&&tg(r))return!0}return!1}function a0(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!dM.has(r)&&(typeof t[r]=="object"&&(0,cM.eachItem)(t[r],n=>e+=a0(n)),e===1/0))return 1/0}return e}function c0(t,e="",r){r!==!1&&(e=yo(e));let n=t.parse(e);return u0(t,n)}Ct.getFullPath=c0;function u0(t,e){return t.serialize(e).split("#")[0]+"#"}Ct._getFullPath=u0;var fM=/#\/?$/;function yo(t){return t?t.replace(fM,""):""}Ct.normalizeId=yo;function hM(t,e,r){return r=yo(r),t.resolve(e,r)}Ct.resolveUrl=hM;var gM=/^[a-z_][-a-z0-9._]*$/i;function yM(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=yo(t[r]||e),o={"":s},i=c0(n,s,!1),a={},c=new Set;return lM(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=o[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),o[m]=g;function y(_){let b=this.opts.uriResolver.resolve;if(_=yo(g?b(g,_):_),c.has(_))throw d(_);c.add(_);let S=this.refs[_];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,_):_!==yo(h)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!gM.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,f){if(m!==void 0&&!uM(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Ct.getSchemaRefs=yM});var Gi=M($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.getData=$n.KeywordCxt=$n.validateFunctionCode=void 0;var f0=Zk(),l0=Bi(),ng=Wh(),Su=Bi(),_M=Jk(),Wi=t0(),rg=n0(),B=re(),Y=Wr(),vM=qi(),Gr=pe(),Vi=Zi();function bM(t){if(y0(t)&&(_0(t),g0(t))){kM(t);return}h0(t,()=>(0,f0.topBoolOrEmptySchema)(t))}$n.validateFunctionCode=bM;function h0({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,B._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,B._)`"use strict"; ${d0(r,s)}`),SM(t,s),t.code(o)}):t.func(e,(0,B._)`${Y.default.data}, ${xM(s)}`,n.$async,()=>t.code(d0(r,s)).code(o))}function xM(t){return(0,B._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,B._)`, ${Y.default.dynamicAnchors}={}`:B.nil}}={}`}function SM(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,B._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,B._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,B._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,B._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,B._)`""`),t.var(Y.default.parentData,(0,B._)`undefined`),t.var(Y.default.parentDataProperty,(0,B._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,B._)`{}`)})}function kM(t){let{schema:e,opts:r,gen:n}=t;h0(t,()=>{r.$comment&&e.$comment&&b0(t),PM(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&wM(t),v0(t),OM(t)})}function wM(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,B._)`${r}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function d0(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${r} */`:B.nil}function EM(t,e){if(y0(t)&&(_0(t),g0(t))){$M(t,e);return}(0,f0.boolOrEmptySchema)(t,e)}function g0({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function y0(t){return typeof t.schema!="boolean"}function $M(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&b0(t),RM(t),CM(t);let o=n.const("_errs",Y.default.errors);v0(t,o),n.var(e,(0,B._)`${o} === ${Y.default.errors}`)}function _0(t){(0,Gr.checkUnknownRules)(t),TM(t)}function v0(t,e){if(t.opts.jtd)return p0(t,[],!1,e);let r=(0,l0.getSchemaTypes)(t.schema),n=(0,l0.coerceAndCheckDataType)(t,r);p0(t,r,!n,e)}function TM(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Gr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function PM(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Gr.checkStrictMode)(t,"default is ignored in the schema root")}function RM(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,vM.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function CM(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function b0({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,B._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,B.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function OM(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,B._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,B._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&IM(t),e.return((0,B._)`${Y.default.errors} === 0`))}function IM({gen:t,evaluated:e,props:r,items:n}){r instanceof B.Name&&t.assign((0,B._)`${e}.props`,r),n instanceof B.Name&&t.assign((0,B._)`${e}.items`,n)}function p0(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Gr.schemaHasRulesButRef)(o,d))){s.block(()=>S0(t,"$ref",d.all.$ref.definition));return}c.jtd||AM(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,ng.shouldUseGroup)(o,m)&&(m.type?(s.if((0,Su.checkDataType)(m.type,i,c.strictNumbers)),m0(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,Su.reportTypeError)(t)),s.endIf()):m0(t,m),a||s.if((0,B._)`${Y.default.errors} === ${n||0}`))}}function m0(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,_M.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,ng.shouldUseRule)(n,o)&&S0(t,o.keyword,o.definition,e.type)})}function AM(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(NM(t,e),t.opts.allowUnionTypes||DM(t,e),MM(t,t.dataTypes))}function NM(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{x0(t.dataTypes,r)||sg(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),zM(t,e)}}function DM(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&sg(t,"use allowUnionTypes to allow union type keyword")}function MM(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,ng.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>jM(e,i))&&sg(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function jM(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function x0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function zM(t,e){let r=[];for(let n of t.dataTypes)x0(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function sg(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Gr.checkStrictMode)(t,e,t.opts.strictTypes)}var ku=class{constructor(e,r,n){if((0,Wi.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Gr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",k0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Wi.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,r,n){this.failResult((0,B.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,B.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,B._)`${r} !== undefined && (${(0,B.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Vi.reportExtraError:Vi.reportError)(this,this.def.error,r)}$dataError(){(0,Vi.reportError)(this,this.def.$dataError||Vi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Vi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=B.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=B.nil,r=B.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,B.or)((0,B._)`${s} === undefined`,r)),e!==B.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,B.or)(i(),a());function i(){if(n.length){if(!(r instanceof B.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,B._)`${(0,Su.checkDataTypes)(c,r,o.opts.strictNumbers,Su.DataType.Wrong)}`}return B.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,B._)`!${c}(${r})`}return B.nil}}subschema(e,r){let n=(0,rg.getSubschema)(this.it,e);(0,rg.extendSubschemaData)(n,this.it,e),(0,rg.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return EM(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Gr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Gr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,B.Name)),!0}};$n.KeywordCxt=ku;function S0(t,e,r,n){let s=new ku(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Wi.funcKeywordCode)(s,r):"macro"in r?(0,Wi.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Wi.funcKeywordCode)(s,r)}var LM=/^\/(?:[^~]|~0|~1)*$/,FM=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function k0(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!LM.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=FM.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(o=r[e-d],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,B._)`${o}${(0,B.getProperty)((0,Gr.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}$n.getData=k0});var wu=M(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var og=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ig.default=og});var Ki=M(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var ag=qi(),cg=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,ag.resolveUrl)(e,r,n),this.missingSchema=(0,ag.normalizeId)((0,ag.getFullPath)(e,this.missingRef))}};ug.default=cg});var $u=M(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.resolveSchema=Qt.getCompilingSchema=Qt.resolveRef=Qt.compileSchema=Qt.SchemaEnv=void 0;var fr=re(),UM=wu(),Ss=Wr(),hr=qi(),w0=pe(),HM=Gi(),_o=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,hr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Qt.SchemaEnv=_o;function dg(t){let e=E0.call(this,t);if(e)return e;let r=(0,hr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new fr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:UM.default,code:(0,fr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Ss.default.data,parentData:Ss.default.parentData,parentDataProperty:Ss.default.parentDataProperty,dataNames:[Ss.default.data],dataPathArr:[fr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,fr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:fr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,fr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,HM.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(Ss.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${Ss.default.self}`,`${Ss.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof fr.Name?void 0:p,items:h instanceof fr.Name?void 0:h,dynamicProps:p instanceof fr.Name,dynamicItems:h instanceof fr.Name},f.source&&(f.source.evaluated=(0,fr.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Qt.compileSchema=dg;function ZM(t,e,r){var n;r=(0,hr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=VM.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new _o({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=BM.call(this,o)}Qt.resolveRef=ZM;function BM(t){return(0,hr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:dg.call(this,t)}function E0(t){for(let e of this._compilations)if(qM(e,t))return e}Qt.getCompilingSchema=E0;function qM(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function VM(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Eu.call(this,t,e)}function Eu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,hr._getFullPath)(this.opts.uriResolver,r),s=(0,hr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return lg.call(this,r,t);let o=(0,hr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Eu.call(this,t,i);return typeof a?.schema!="object"?void 0:lg.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||dg.call(this,i),o===(0,hr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,hr.resolveUrl)(this.opts.uriResolver,s,u)),new _o({schema:a,schemaId:c,root:t,baseId:s})}return lg.call(this,r,i)}}Qt.resolveSchema=Eu;var WM=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function lg(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,w0.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!WM.has(a)&&u&&(e=(0,hr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,w0.schemaHasRulesButRef)(r,this.RULES)){let a=(0,hr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Eu.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new _o({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var $0=M((u5,GM)=>{GM.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 mg=M((l5,C0)=>{"use strict";var KM=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),P0=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function pg(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var JM=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function T0(t){return t.length=0,!0}function YM(t,e,r){if(t.length){let n=pg(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function XM(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=YM;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=T0}else{s.push(u);continue}}return s.length&&(a===T0?r.zone=s.join(""):i?n.push(s.join("")):n.push(pg(s))),r.address=n.join(""),r}function R0(t){if(QM(t,":")<2)return{host:t,isIPV6:!1};let e=XM(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function QM(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function ej(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function tj(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function rj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!P0(r)){let n=R0(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}C0.exports={nonSimpleDomain:JM,recomposeAuthority:rj,normalizeComponentEncoding:tj,removeDotSegments:ej,isIPv4:P0,isUUID:KM,normalizeIPv6:R0,stringArrayToHexStripped:pg}});var D0=M((d5,N0)=>{"use strict";var{isUUID:nj}=mg(),sj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oj=["http","https","ws","wss","urn","urn:uuid"];function ij(t){return oj.indexOf(t)!==-1}function fg(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 O0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function I0(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 aj(t){return t.secure=fg(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cj(t){if((t.port===(fg(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function uj(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(sj);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=hg(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function lj(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=hg(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function dj(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!nj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function pj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var A0={scheme:"http",domainHost:!0,parse:O0,serialize:I0},mj={scheme:"https",domainHost:A0.domainHost,parse:O0,serialize:I0},Tu={scheme:"ws",domainHost:!0,parse:aj,serialize:cj},fj={scheme:"wss",domainHost:Tu.domainHost,parse:Tu.parse,serialize:Tu.serialize},hj={scheme:"urn",parse:uj,serialize:lj,skipNormalize:!0},gj={scheme:"urn:uuid",parse:dj,serialize:pj,skipNormalize:!0},Pu={http:A0,https:mj,ws:Tu,wss:fj,urn:hj,"urn:uuid":gj};Object.setPrototypeOf(Pu,null);function hg(t){return t&&(Pu[t]||Pu[t.toLowerCase()])||void 0}N0.exports={wsIsSecure:fg,SCHEMES:Pu,isValidSchemeName:ij,getSchemeHandler:hg}});var z0=M((p5,Cu)=>{"use strict";var{normalizeIPv6:yj,removeDotSegments:Ji,recomposeAuthority:_j,normalizeComponentEncoding:Ru,isIPv4:vj,nonSimpleDomain:bj}=mg(),{SCHEMES:xj,getSchemeHandler:M0}=D0();function Sj(t,e){return typeof t=="string"?t=Or(Kr(t,e),e):typeof t=="object"&&(t=Kr(Or(t,e),e)),t}function kj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=j0(Kr(t,n),Kr(e,n),n,!0);return n.skipEscape=!0,Or(s,n)}function j0(t,e,r,n){let s={};return n||(t=Kr(Or(t,r),r),e=Kr(Or(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ji(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Ji(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ji(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Ji(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function wj(t,e,r){return typeof t=="string"?(t=unescape(t),t=Or(Ru(Kr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Or(Ru(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Or(Ru(Kr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Or(Ru(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Or(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=M0(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=_j(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Ji(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var Ej=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Kr(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(Ej);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(vj(n.host)===!1){let c=yj(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=M0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&bj(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var gg={SCHEMES:xj,normalize:Sj,resolve:kj,resolveComponent:j0,equal:wj,serialize:Or,parse:Kr};Cu.exports=gg;Cu.exports.default=gg;Cu.exports.fastUri=gg});var F0=M(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var L0=z0();L0.code='require("ajv/dist/runtime/uri").default';yg.default=L0});var G0=M(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.CodeGen=rt.Name=rt.nil=rt.stringify=rt.str=rt._=rt.KeywordCxt=void 0;var $j=Gi();Object.defineProperty(rt,"KeywordCxt",{enumerable:!0,get:function(){return $j.KeywordCxt}});var vo=re();Object.defineProperty(rt,"_",{enumerable:!0,get:function(){return vo._}});Object.defineProperty(rt,"str",{enumerable:!0,get:function(){return vo.str}});Object.defineProperty(rt,"stringify",{enumerable:!0,get:function(){return vo.stringify}});Object.defineProperty(rt,"nil",{enumerable:!0,get:function(){return vo.nil}});Object.defineProperty(rt,"Name",{enumerable:!0,get:function(){return vo.Name}});Object.defineProperty(rt,"CodeGen",{enumerable:!0,get:function(){return vo.CodeGen}});var Tj=wu(),q0=Ki(),Pj=Vh(),Yi=$u(),Rj=re(),Xi=qi(),Ou=Bi(),vg=pe(),U0=$0(),Cj=F0(),V0=(t,e)=>new RegExp(t,e);V0.code="new RegExp";var Oj=["removeAdditional","useDefaults","coerceTypes"],Ij=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Aj={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."},Nj={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},H0=200;function Dj(t){var e,r,n,s,o,i,a,c,u,d,l,m,f,p,h,g,y,v,_,b,S,T,$,R,N;let P=t.strict,C=(e=t.code)===null||e===void 0?void 0:e.optimize,L=C===!0||C===void 0?1:C||0,X=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:V0,fe=(s=t.uriResolver)!==null&&s!==void 0?s:Cj.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:P)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:P)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:P)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:P)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:P)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:L,regExp:X}:{optimize:L,regExp:X},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:H0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:H0,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(T=t.validateSchema)!==null&&T!==void 0?T:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(R=t.unicodeRegExp)!==null&&R!==void 0?R:!0,int32range:(N=t.int32range)!==null&&N!==void 0?N:!0,uriResolver:fe}}var Qi=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,...Dj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Rj.ValueScope({scope:{},prefixes:Ij,es5:r,lines:n}),this.logger=Uj(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Pj.getRules)(),Z0.call(this,Aj,e,"NOT SUPPORTED"),Z0.call(this,Nj,e,"DEPRECATED","warn"),this._metaOpts=Lj.call(this),e.formats&&jj.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&zj.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Mj.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=U0;n==="id"&&(s={...U0},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,l){await o.call(this,d.$schema);let m=this._addSchema(d,l);return m.validate||i.call(this,m)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof q0.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await o.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Xi.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=B0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Yi.SchemaEnv({schema:{},schemaId:n});if(r=Yi.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=B0.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Xi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Zj.call(this,n,r),!r)return(0,vg.eachItem)(n,o=>_g.call(this,o)),this;qj.call(this,r);let s={...r,type:(0,Ou.getJSONTypes)(r.type),schemaType:(0,Ou.getJSONTypes)(r.schemaType)};return(0,vg.eachItem)(n,s.type.length===0?o=>_g.call(this,o,s):o=>s.type.forEach(i=>_g.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=W0(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Xi.normalizeId)(i||n);let u=Xi.getSchemaRefs.call(this,e,n);return c=new Yi.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):Yi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Yi.compileSchema.call(this,e)}finally{this.opts=r}}};Qi.ValidationError=Tj.default;Qi.MissingRefError=q0.default;rt.default=Qi;function Z0(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function B0(t){return t=(0,Xi.normalizeId)(t),this.schemas[t]||this.refs[t]}function Mj(){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 jj(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function zj(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Lj(){let t={...this.opts};for(let e of Oj)delete t[e];return t}var Fj={log(){},warn(){},error(){}};function Uj(t){if(t===!1)return Fj;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 Hj=/^[a-z_$][a-z0-9_$:-]*$/i;function Zj(t,e){let{RULES:r}=this;if((0,vg.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Hj.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function _g(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ou.getJSONTypes)(e.type),schemaType:(0,Ou.getJSONTypes)(e.schemaType)}};e.before?Bj.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Bj(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function qj(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=W0(e)),t.validateSchema=this.compile(e,!0))}var Vj={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function W0(t){return{anyOf:[t,Vj]}}});var K0=M(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Wj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};bg.default=Wj});var Q0=M(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.callRef=ks.getValidate=void 0;var Gj=Ki(),J0=Xt(),Ot=re(),bo=Wr(),Y0=$u(),Iu=pe(),Kj={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return l();let d=Y0.resolveRef.call(c,u,s,r);if(d===void 0)throw new Gj.default(n.opts.uriResolver,s,r);if(d instanceof Y0.SchemaEnv)return m(d);return f(d);function l(){if(o===u)return Au(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return Au(t,(0,Ot._)`${p}.validate`,u,u.$async)}function m(p){let h=X0(t,p);Au(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Ot.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Ot.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function X0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ot._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ks.getValidate=X0;function Au(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?bo.default.this:Ot.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,Ot._)`await ${(0,J0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(p,!0)},h=>{s.if((0,Ot._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),m(h),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,J0.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,Ot._)`${p}.errors`;s.assign(bo.default.vErrors,(0,Ot._)`${bo.default.vErrors} === null ? ${h} : ${bo.default.vErrors}.concat(${h})`),s.assign(bo.default.errors,(0,Ot._)`${bo.default.vErrors}.length`)}function f(p){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Iu.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,Ot._)`${p}.evaluated.props`);o.props=Iu.mergeEvaluated.props(s,y,o.props,Ot.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Iu.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,Ot._)`${p}.evaluated.items`);o.items=Iu.mergeEvaluated.items(s,y,o.items,Ot.Name)}}}ks.callRef=Au;ks.default=Kj});var ew=M(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var Jj=K0(),Yj=Q0(),Xj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Jj.default,Yj.default];xg.default=Xj});var tw=M(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var Nu=re(),Tn=Nu.operators,Du={maximum:{okStr:"<=",ok:Tn.LTE,fail:Tn.GT},minimum:{okStr:">=",ok:Tn.GTE,fail:Tn.LT},exclusiveMaximum:{okStr:"<",ok:Tn.LT,fail:Tn.GTE},exclusiveMinimum:{okStr:">",ok:Tn.GT,fail:Tn.LTE}},Qj={message:({keyword:t,schemaCode:e})=>(0,Nu.str)`must be ${Du[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Nu._)`{comparison: ${Du[t].okStr}, limit: ${e}}`},ez={keyword:Object.keys(Du),type:"number",schemaType:"number",$data:!0,error:Qj,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Nu._)`${r} ${Du[e].fail} ${n} || isNaN(${r})`)}};Sg.default=ez});var rw=M(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var ea=re(),tz={message:({schemaCode:t})=>(0,ea.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ea._)`{multipleOf: ${t}}`},rz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:tz,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ea._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ea._)`${i} !== parseInt(${i})`;t.fail$data((0,ea._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};kg.default=rz});var sw=M(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});function nw(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}wg.default=nw;nw.code='require("ajv/dist/runtime/ucs2length").default'});var ow=M(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var ws=re(),nz=pe(),sz=sw(),oz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ws.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ws._)`{limit: ${t}}`},iz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:oz,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ws.operators.GT:ws.operators.LT,i=s.opts.unicode===!1?(0,ws._)`${r}.length`:(0,ws._)`${(0,nz.useFunc)(t.gen,sz.default)}(${r})`;t.fail$data((0,ws._)`${i} ${o} ${n}`)}};Eg.default=iz});var iw=M($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var az=Xt(),cz=pe(),xo=re(),uz={message:({schemaCode:t})=>(0,xo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xo._)`{pattern: ${t}}`},lz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:uz,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,xo._)`new RegExp`:(0,cz.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,xo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,xo._)`!${d}`)}else{let c=(0,az.usePattern)(t,s);t.fail$data((0,xo._)`!${c}.test(${r})`)}}};$g.default=lz});var aw=M(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var ta=re(),dz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ta.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ta._)`{limit: ${t}}`},pz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:dz,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?ta.operators.GT:ta.operators.LT;t.fail$data((0,ta._)`Object.keys(${r}).length ${s} ${n}`)}};Tg.default=pz});var cw=M(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var ra=Xt(),na=re(),mz=pe(),fz={message:({params:{missingProperty:t}})=>(0,na.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,na._)`{missingProperty: ${t}}`},hz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:fz,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,mz.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(na.nil,l);else for(let f of r)(0,ra.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,ra.checkMissingProp)(t,r,f)),(0,ra.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ra.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,ra.propertyInData)(e,s,f,a.ownProperties)),e.if((0,na.not)(p),()=>{t.error(),e.break()})},na.nil)}}};Pg.default=hz});var uw=M(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var sa=re(),gz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,sa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,sa._)`{limit: ${t}}`},yz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:gz,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?sa.operators.GT:sa.operators.LT;t.fail$data((0,sa._)`${r}.length ${s} ${n}`)}};Rg.default=yz});var Mu=M(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var lw=eg();lw.code='require("ajv/dist/runtime/equal").default';Cg.default=lw});var dw=M(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var Og=Bi(),nt=re(),_z=pe(),vz=Mu(),bz={message:({params:{i:t,j:e}})=>(0,nt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,nt._)`{i: ${t}, j: ${e}}`},xz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bz,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,Og.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,nt._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,nt._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,nt._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),y=(0,Og.checkDataTypes)(u,g,a.opts.strictNumbers,Og.DataType.Wrong),v=e.const("indices",(0,nt._)`{}`);e.for((0,nt._)`;${p}--;`,()=>{e.let(g,(0,nt._)`${r}[${p}]`),e.if(y,(0,nt._)`continue`),u.length>1&&e.if((0,nt._)`typeof ${g} == "string"`,(0,nt._)`${g} += "_"`),e.if((0,nt._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,nt._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,nt._)`${v}[${g}] = ${p}`)})}function f(p,h){let g=(0,_z.useFunc)(e,vz.default),y=e.name("outer");e.label(y).for((0,nt._)`;${p}--;`,()=>e.for((0,nt._)`${h} = ${p}; ${h}--;`,()=>e.if((0,nt._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Ig.default=xz});var pw=M(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var Ag=re(),Sz=pe(),kz=Mu(),wz={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ag._)`{allowedValue: ${t}}`},Ez={keyword:"const",$data:!0,error:wz,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Ag._)`!${(0,Sz.useFunc)(e,kz.default)}(${r}, ${s})`):t.fail((0,Ag._)`${o} !== ${r}`)}};Ng.default=Ez});var mw=M(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var oa=re(),$z=pe(),Tz=Mu(),Pz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,oa._)`{allowedValues: ${t}}`},Rz={keyword:"enum",schemaType:"array",$data:!0,error:Pz,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,$z.useFunc)(e,Tz.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,oa.or)(...s.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,oa._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=s[p];return typeof h=="object"&&h!==null?(0,oa._)`${u()}(${r}, ${f}[${p}])`:(0,oa._)`${r} === ${h}`}}};Dg.default=Rz});var fw=M(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Cz=tw(),Oz=rw(),Iz=ow(),Az=iw(),Nz=aw(),Dz=cw(),Mz=uw(),jz=dw(),zz=pw(),Lz=mw(),Fz=[Cz.default,Oz.default,Iz.default,Az.default,Nz.default,Dz.default,Mz.default,jz.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},zz.default,Lz.default];Mg.default=Fz});var zg=M(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.validateAdditionalItems=void 0;var Es=re(),jg=pe(),Uz={message:({params:{len:t}})=>(0,Es.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Es._)`{limit: ${t}}`},Hz={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Uz,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,jg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}hw(t,n)}};function hw(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,Es._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Es._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,jg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Es._)`${a} <= ${e.length}`);r.if((0,Es.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:jg.Type.Num},u),i.allErrors||r.if((0,Es.not)(u),()=>r.break())})}}ia.validateAdditionalItems=hw;ia.default=Hz});var Lg=M(aa=>{"use strict";Object.defineProperty(aa,"__esModule",{value:!0});aa.validateTuple=void 0;var gw=re(),ju=pe(),Zz=Xt(),Bz={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return yw(t,"additionalItems",e);r.items=!0,!(0,ju.alwaysValidSchema)(r,e)&&t.ok((0,Zz.validateArray)(t))}};function yw(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;d(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ju.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,gw._)`${o}.length`);r.forEach((l,m)=>{(0,ju.alwaysValidSchema)(a,l)||(n.if((0,gw._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ju.checkStrictMode)(a,g,m.strictTuples)}}}aa.validateTuple=yw;aa.default=Bz});var _w=M(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var qz=Lg(),Vz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,qz.validateTuple)(t,"items")};Fg.default=Vz});var bw=M(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var vw=re(),Wz=pe(),Gz=Xt(),Kz=zg(),Jz={message:({params:{len:t}})=>(0,vw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,vw._)`{limit: ${t}}`},Yz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Jz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Wz.alwaysValidSchema)(n,e)&&(s?(0,Kz.validateAdditionalItems)(t,s):t.ok((0,Gz.validateArray)(t)))}};Ug.default=Yz});var xw=M(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var er=re(),zu=pe(),Xz={message:({params:{min:t,max:e}})=>e===void 0?(0,er.str)`must contain at least ${t} valid item(s)`:(0,er.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,er._)`{minContains: ${t}}`:(0,er._)`{minContains: ${t}, maxContains: ${e}}`},Qz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Xz,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,er._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,zu.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,zu.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,zu.alwaysValidSchema)(o,r)){let h=(0,er._)`${d} >= ${i}`;a!==void 0&&(h=(0,er._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,er._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:zu.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,er._)`${h}++`),a===void 0?e.if((0,er._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,er._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,er._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};Hg.default=Qz});var ww=M(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateSchemaDeps=Ir.validatePropertyDeps=Ir.error=void 0;var Zg=re(),eL=pe(),ca=Xt();Ir.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zg._)`{property: ${t},
|
|
188
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var gh,mr,ED,Eu=x(()=>{Pn();mr={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:()=>(gh===void 0&&(gh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gh),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-_]*$/};ED=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function $u(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===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Me(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=wu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===I.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===I.ZodBranded&&t.keyType._def.type._def.typeName===I.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Su(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Tu=x(()=>{wi();We();Eu();ku();Xt()});function Mk(t,e){if(e.mapStrategy==="record")return $u(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Me(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Me(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var _h=x(()=>{We();Tu();Xt()});function jk(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var vh=x(()=>{});function zk(t){return t.target==="openAi"?void 0:{not:Me({...t,currentPath:[...t.currentPath,"not"]})}}var bh=x(()=>{Xt()});function Lk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xh=x(()=>{});function Uk(t,e){if(e.target==="openApi3")return Fk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ji&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Ji[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Fk(t,e)}var Ji,Fk,Pu=x(()=>{We();Ji={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Hk(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:Ji[t.innerType._def.typeName],nullable:!0}:{type:[Ji[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Sh=x(()=>{We();Pu()});function Zk(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",oh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(r,"minimum",n.value,n.message,e):de(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),de(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(r,"maximum",n.value,n.message,e):de(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),de(r,"maximum",n.value,n.message,e));break;case"multipleOf":de(r,"multipleOf",n.value,n.message,e);break}return r}var kh=x(()=>{Pn()});function Bk(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=PD(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=TD(t,e);return i!==void 0&&(n.additionalProperties=i),n}function TD(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 PD(t){try{return t.isOptional()}catch{return!0}}var wh=x(()=>{We()});var qk,Eh=x(()=>{We();Xt();qk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Me(e)},r]}:Me(e)}});var Vk,$h=x(()=>{We();Vk=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Wk(t,e){return Y(t.type._def,e)}var Th=x(()=>{We()});function Gk(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&de(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&de(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Ph=x(()=>{Pn();We()});function Kk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Rh=x(()=>{We()});function Jk(t){return{not:Me(t)}}var Ch=x(()=>{Xt()});function Yk(t){return Me(t)}var Oh=x(()=>{Xt()});var Xk,Ih=x(()=>{We();Xk=(t,e)=>Y(t.innerType._def,e)});var Qk,Ah=x(()=>{wi();Xt();sh();ih();ah();ku();ch();lh();dh();ph();mh();fh();hh();_h();vh();bh();xh();Sh();kh();wh();Eh();$h();Th();Tu();Ph();Eu();Rh();Ch();Pu();Oh();Ih();Qk=(t,e,r)=>{switch(e){case I.ZodString:return wu(t,r);case I.ZodNumber:return Zk(t,r);case I.ZodObject:return Bk(t,r);case I.ZodBigInt:return Tk(t,r);case I.ZodBoolean:return Pk();case I.ZodDate:return uh(t,r);case I.ZodUndefined:return Jk(r);case I.ZodNull:return Lk(r);case I.ZodArray:return $k(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return Uk(t,r);case I.ZodIntersection:return Ak(t,r);case I.ZodTuple:return Kk(t,r);case I.ZodRecord:return $u(t,r);case I.ZodLiteral:return Nk(t,r);case I.ZodEnum:return Ik(t);case I.ZodNativeEnum:return jk(t);case I.ZodNullable:return Hk(t,r);case I.ZodOptional:return qk(t,r);case I.ZodMap:return Mk(t,r);case I.ZodSet:return Gk(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return Wk(t,r);case I.ZodNaN:case I.ZodNever:return zk(r);case I.ZodEffects:return Ok(t,r);case I.ZodAny:return Me(r);case I.ZodUnknown:return Yk(r);case I.ZodDefault:return Ck(t,r);case I.ZodBranded:return Su(t,r);case I.ZodReadonly:return Xk(t,r);case I.ZodCatch:return Rk(t,r);case I.ZodPipeline:return Vk(t,r);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==kk)return a}if(n&&!r){let a=RD(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Qk(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&CD(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var RD,CD,We=x(()=>{vu();Ah();xu();Xt();RD=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:bu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Me(e)):e.$refStrategy==="seen"?Me(e):void 0}},CD=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var e0=x(()=>{});var Nh,Dh=x(()=>{We();nh();Xt();Nh=(t,e)=>{let r=Ek(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:Y(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Me(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Me(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var t0=x(()=>{vu();nh();Pn();xu();We();e0();Xt();sh();ih();ah();ku();ch();lh();dh();ph();mh();fh();hh();_h();vh();bh();xh();Sh();kh();wh();Eh();$h();Th();Ih();Tu();Ph();Eu();Rh();Ch();Pu();Oh();Ah();Dh();Dh()});function OD(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Mh(t,e){return Kt(t)?kf(t,{target:OD(e?.target),io:e?.pipeStrategy??"input"}):Nh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function jh(t){let r=En(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zh(t,e){let r=wn(t,e);if(!r.success)throw r.error;return r.data}var Lh=x(()=>{$f();ji();t0()});function r0(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function n0(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];r0(i)&&r0(s)?r[o]={...i,...s}:r[o]=s}return r}var ID,Ru,o0=x(()=>{ji();ko();xk();Lh();ID=6e4,Ru=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(iu,r=>{this._oncancel(r)}),this.setNotificationHandler(cu,r=>{this._onprogress(r)}),this.setRequestHandler(au,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(uu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(W.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(du,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new Z(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Z(W.InvalidParams,`Task not found: ${s}`);if(!Tn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Tn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[$n]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(pu,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Z(W.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(fu,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tn(o.status))throw new Z(W.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Z(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Z?o:new Z(W.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Z.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ui(s)||lk(s)?this._onresponse(s):Zf(s)?this._onrequest(s,i):uk(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[$n]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:W.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=ik(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 d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new Z(W.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let p=f.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:W.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ui(e))n(e);else{let i=new Z(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Ui(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Ui(e))o(e);else{let i=Z.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(W.InternalError,String(i))}}return}let s;try{let i=await this.request(e,gs,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Z(W.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Tn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(W.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(W.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Z?i:new Z(W.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=v=>{d(v)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(v){l(v);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[$n]:c}});let p=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let _=v instanceof Z?v:new Z(W.RequestTimeout,String(v));d(_)};this._responseHandlers.set(m,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return d(v);try{let _=wn(r,v.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??ID,g=()=>p(Z.fromError(W.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=_=>{let b=this._responseHandlers.get(m);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(m),d(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},lu,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},mu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},mk,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[$n]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[$n]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[$n]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=jh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=zh(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=jh(e);this._notificationHandlers.set(n,o=>{let s=zh(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Zf(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Z(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Z(W.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Z(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new Z(W.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Vi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Tn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new Z(W.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Tn(a.status))throw new Z(W.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Vi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Qi=D(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 Yi=class{};he._CodeOrName=Yi;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var wo=class extends Yi{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 Qt=class extends Yi{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof wo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Qt;he.nil=new Qt("");function s0(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Uh(r,e[n]),r.push(t[++n]);return new Qt(r)}he._=s0;var Fh=new Qt("+");function i0(t,...e){let r=[Xi(t[0])],n=0;for(;n<e.length;)r.push(Fh),Uh(r,e[n]),r.push(Fh,Xi(t[++n]));return AD(r),new Qt(r)}he.str=i0;function Uh(t,e){e instanceof Qt?t.push(...e._items):e instanceof wo?t.push(e):t.push(MD(e))}he.addCodeArg=Uh;function AD(t){let e=1;for(;e<t.length-1;){if(t[e]===Fh){let r=ND(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function ND(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 DD(t,e){return e.emptyStr()?t:t.emptyStr()?e:i0`${t}${e}`}he.strConcat=DD;function MD(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xi(Array.isArray(t)?t.join(","):t)}function jD(t){return new Qt(Xi(t))}he.stringify=jD;function Xi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Xi;function zD(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Qt(`.${t}`):s0`[${t}]`}he.getProperty=zD;function LD(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Qt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=LD;function FD(t){return new Qt(t.toString())}he.regexpCode=FD});var Bh=D(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.ValueScope=Ot.ValueScopeName=Ot.Scope=Ot.varKinds=Ot.UsedValueState=void 0;var Ct=Qi(),Hh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Cu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Cu||(Ot.UsedValueState=Cu={}));Ot.varKinds={const:new Ct.Name("const"),let:new Ct.Name("let"),var:new Ct.Name("var")};var Ou=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ct.Name?e:this.name(e)}name(e){return new Ct.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ot.Scope=Ou;var Iu=class extends Ct.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ct._)`.${new Ct.Name(r)}[${n}]`}};Ot.ValueScopeName=Iu;var UD=(0,Ct._)`\n`,Zh=class extends Ou{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?UD:Ct.nil}}get(){return this._scope}name(e){return new Iu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ct._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ct.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Cu.Started);let d=r(u);if(d){let l=this.opts.es5?Ot.varKinds.var:Ot.varKinds.const;s=(0,Ct._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ct._)`${s}${d}${this.opts._n}`;else throw new Hh(u);c.set(u,Cu.Completed)})}return s}};Ot.ValueScope=Zh});var re=D(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var pe=Qi(),hr=Bh(),Rn=Qi();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return Rn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return Rn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return Rn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return Rn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return Rn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return Rn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return Rn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return Rn.Name}});var Mu=Bh();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Mu.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Mu.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Mu.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Mu.varKinds}});ne.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 Jr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},qh=class extends Jr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?hr.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Es(this.rhs,e,r)),this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}},Au=class extends Jr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Es(this.rhs,e,r),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return Du(e,this.rhs)}},Vh=class extends Au{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wh=class extends Jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gh=class extends Jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Kh=class extends Jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Jh=class extends Jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Es(this.code,e,r),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}},ea=class extends Jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(HD(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>To(e,r.names),{})}},Yr=class extends ea{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Yh=class extends ea{},ws=class extends Yr{};ws.kind="else";var Eo=class t extends Yr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new ws(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(a0(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Es(this.condition,e,r),this}get names(){let e=super.names;return Du(e,this.condition),this.else&&To(e,this.else.names),e}};Eo.kind="if";var $o=class extends Yr{};$o.kind="for";var Xh=class extends $o{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Es(this.iteration,e,r),this}get names(){return To(super.names,this.iteration.names)}},Qh=class extends $o{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?hr.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Du(super.names,this.from);return Du(e,this.to)}},Nu=class extends $o{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Es(this.iterable,e,r),this}get names(){return To(super.names,this.iterable.names)}},ta=class extends Yr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ta.kind="func";var ra=class extends ea{render(e){return"return "+super.render(e)}};ra.kind="return";var eg=class extends Yr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&To(e,this.catch.names),this.finally&&To(e,this.finally.names),e}},na=class extends Yr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};na.kind="catch";var oa=class extends Yr{render(e){return"finally"+super.render(e)}};oa.kind="finally";var tg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
189
|
+
`:""},this._extScope=e,this._scope=new hr.Scope({parent:e}),this._nodes=[new Yh]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new qh(e,s,n)),s}const(e,r,n){return this._def(hr.varKinds.const,e,r,n)}let(e,r,n){return this._def(hr.varKinds.let,e,r,n)}var(e,r,n){return this._def(hr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Au(e,r,n))}add(e,r){return this._leafNode(new Vh(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==pe.nil&&this._leafNode(new Jh(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,pe.addCodeArg)(r,o));return r.push("}"),new pe._Code(r)}if(e,r,n){if(this._blockNode(new Eo(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Eo(e))}else(){return this._elseNode(new ws)}endIf(){return this._endBlockNode(Eo,ws)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Xh(e),r)}forRange(e,r,n,o,s=this.opts.es5?hr.varKinds.var:hr.varKinds.let){let i=this._scope.toName(e);return this._for(new Qh(s,i,r,n),()=>o(i))}forOf(e,r,n,o=hr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof pe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,pe._)`${i}.length`,a=>{this.var(s,(0,pe._)`${i}[${a}]`),n(s)})}return this._for(new Nu("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?hr.varKinds.var:hr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,pe._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Nu("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode($o)}label(e){return this._leafNode(new Wh(e))}break(e){return this._leafNode(new Gh(e))}return(e){let r=new ra;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ra)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new eg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new na(s),r(s)}return n&&(this._currNode=o.finally=new oa,this.code(n)),this._endBlockNode(na,oa)}throw(e){return this._leafNode(new Kh(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=pe.nil,n,o){return this._blockNode(new ta(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ta)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Eo))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};ne.CodeGen=tg;function To(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Du(t,e){return e instanceof pe._CodeOrName?To(t,e.names):t}function Es(t,e,r){if(t instanceof pe.Name)return n(t);if(!o(t))return t;return new pe._Code(t._items.reduce((s,i)=>(i instanceof pe.Name&&(i=n(i)),i instanceof pe._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof pe._Code&&s._items.some(i=>i instanceof pe.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function HD(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function a0(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,pe._)`!${rg(t)}`}ne.not=a0;var ZD=c0(ne.operators.AND);function BD(...t){return t.reduce(ZD)}ne.and=BD;var qD=c0(ne.operators.OR);function VD(...t){return t.reduce(qD)}ne.or=VD;function c0(t){return(e,r)=>e===pe.nil?r:r===pe.nil?e:(0,pe._)`${rg(e)} ${t} ${rg(r)}`}function rg(t){return t instanceof pe.Name?t:(0,pe._)`(${t})`}});var me=D(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.checkStrictMode=oe.getErrorPath=oe.Type=oe.useFunc=oe.setEvaluated=oe.evaluatedPropsToName=oe.mergeEvaluated=oe.eachItem=oe.unescapeJsonPointer=oe.escapeJsonPointer=oe.escapeFragment=oe.unescapeFragment=oe.schemaRefOrVal=oe.schemaHasRulesButRef=oe.schemaHasRules=oe.checkUnknownRules=oe.alwaysValidSchema=oe.toHash=void 0;var xe=re(),WD=Qi();function GD(t){let e={};for(let r of t)e[r]=!0;return e}oe.toHash=GD;function KD(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(d0(t,e),!p0(e,t.self.RULES.all))}oe.alwaysValidSchema=KD;function d0(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||h0(t,`unknown keyword: "${s}"`)}oe.checkUnknownRules=d0;function p0(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}oe.schemaHasRules=p0;function JD(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}oe.schemaHasRulesButRef=JD;function YD({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(n)}`}oe.schemaRefOrVal=YD;function XD(t){return m0(decodeURIComponent(t))}oe.unescapeFragment=XD;function QD(t){return encodeURIComponent(og(t))}oe.escapeFragment=QD;function og(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}oe.escapeJsonPointer=og;function m0(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}oe.unescapeJsonPointer=m0;function eM(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}oe.eachItem=eM;function u0({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):r(s,i);return a===xe.Name&&!(c instanceof xe.Name)?n(o,c):c}}oe.mergeEvaluated={props:u0({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,xe._)`${r} || {}`),sg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:f0}),items:u0({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,xe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,xe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function f0(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,xe._)`{}`);return e!==void 0&&sg(t,r,e),r}oe.evaluatedPropsToName=f0;function sg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(n)}`,!0))}oe.setEvaluated=sg;var l0={};function tM(t,e){return t.scopeValue("func",{ref:e,code:l0[e.code]||(l0[e.code]=new WD._Code(e.code))})}oe.useFunc=tM;var ng;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ng||(oe.Type=ng={}));function rM(t,e,r){if(t instanceof xe.Name){let n=e===ng.Num;return r?n?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:n?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(t).toString():"/"+og(t)}oe.getErrorPath=rM;function h0(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}oe.checkStrictMode=h0});var Xr=D(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var ut=re(),nM={data:new ut.Name("data"),valCxt:new ut.Name("valCxt"),instancePath:new ut.Name("instancePath"),parentData:new ut.Name("parentData"),parentDataProperty:new ut.Name("parentDataProperty"),rootData:new ut.Name("rootData"),dynamicAnchors:new ut.Name("dynamicAnchors"),vErrors:new ut.Name("vErrors"),errors:new ut.Name("errors"),this:new ut.Name("this"),self:new ut.Name("self"),scope:new ut.Name("scope"),json:new ut.Name("json"),jsonPos:new ut.Name("jsonPos"),jsonLen:new ut.Name("jsonLen"),jsonPart:new ut.Name("jsonPart")};ig.default=nM});var sa=D(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.extendErrors=lt.resetErrorsCount=lt.reportExtraError=lt.reportError=lt.keyword$DataError=lt.keywordError=void 0;var fe=re(),ju=me(),bt=Xr();lt.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};lt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function oM(t,e=lt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=_0(t,e,r);n??(i||a)?g0(s,c):y0(o,(0,fe._)`[${c}]`)}lt.reportError=oM;function sM(t,e=lt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=_0(t,e,r);g0(o,a),s||i||y0(n,bt.default.vErrors)}lt.reportExtraError=sM;function iM(t,e){t.assign(bt.default.errors,e),t.if((0,fe._)`${bt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${bt.default.vErrors}.length`,e),()=>t.assign(bt.default.vErrors,null)))}lt.resetErrorsCount=iM;function aM({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,bt.default.errors,a=>{t.const(i,(0,fe._)`${bt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(bt.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}lt.extendErrors=aM;function g0(t,e){let r=t.const("err",e);t.if((0,fe._)`${bt.default.vErrors} === null`,()=>t.assign(bt.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${bt.default.vErrors}.push(${r})`),t.code((0,fe._)`${bt.default.errors}++`)}function y0(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var Po={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function _0(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:cM(t,e,r)}function cM(t,e,r={}){let{gen:n,it:o}=t,s=[uM(o,r),lM(t,r)];return dM(t,e,s),n.object(...s)}function uM({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,ju.getErrorPath)(e,ju.Type.Str)}`:t;return[bt.default.instancePath,(0,fe.strConcat)(bt.default.instancePath,r)]}function lM({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,ju.getErrorPath)(r,ju.Type.Str)}`),[Po.schemaPath,o]}function dM(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([Po.keyword,o],[Po.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([Po.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Po.schema,i],[Po.parentSchema,(0,fe._)`${d}${l}`],[bt.default.data,s]),u&&n.push([Po.propertyName,u])}});var b0=D($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.boolOrEmptySchema=$s.topBoolOrEmptySchema=void 0;var pM=sa(),mM=re(),fM=Xr(),hM={message:"boolean schema is false"};function gM(t){let{gen:e,schema:r,validateName:n}=t;r===!1?v0(t,!1):typeof r=="object"&&r.$async===!0?e.return(fM.default.data):(e.assign((0,mM._)`${n}.errors`,null),e.return(!0))}$s.topBoolOrEmptySchema=gM;function yM(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),v0(t)):r.var(e,!0)}$s.boolOrEmptySchema=yM;function v0(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,pM.reportError)(o,hM,void 0,e)}});var ag=D(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.getRules=Ts.isJSONType=void 0;var _M=["string","number","integer","boolean","null","object","array"],vM=new Set(_M);function bM(t){return typeof t=="string"&&vM.has(t)}Ts.isJSONType=bM;function xM(){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:{}}}Ts.getRules=xM});var cg=D(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.shouldUseRule=Cn.shouldUseGroup=Cn.schemaHasRulesForType=void 0;function SM({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&x0(t,n)}Cn.schemaHasRulesForType=SM;function x0(t,e){return e.rules.some(r=>S0(t,r))}Cn.shouldUseGroup=x0;function S0(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Cn.shouldUseRule=S0});var ia=D(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.reportTypeError=dt.checkDataTypes=dt.checkDataType=dt.coerceAndCheckDataType=dt.getJSONTypes=dt.getSchemaTypes=dt.DataType=void 0;var kM=ag(),wM=cg(),EM=sa(),ee=re(),k0=me(),Ps;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ps||(dt.DataType=Ps={}));function $M(t){let e=w0(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}dt.getSchemaTypes=$M;function w0(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(kM.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}dt.getJSONTypes=w0;function TM(t,e){let{gen:r,data:n,opts:o}=t,s=PM(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,wM.schemaHasRulesForType)(t,e[0]));if(i){let a=lg(e,n,o.strictNumbers,Ps.Wrong);r.if(a,()=>{s.length?RM(t,e,s):dg(t)})}return i}dt.coerceAndCheckDataType=TM;var E0=new Set(["string","number","integer","boolean","null"]);function PM(t,e){return e?t.filter(r=>E0.has(r)||e==="array"&&r==="array"):[]}function RM(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ee._)`typeof ${o}`),a=n.let("coerced",(0,ee._)`undefined`);s.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ee._)`${o}[0]`).assign(i,(0,ee._)`typeof ${o}`).if(lg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(E0.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),dg(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(o,a),CM(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${o}`).elseIf((0,ee._)`${o} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${o} === null
|
|
190
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ee._)`+${o}`);return;case"integer":n.elseIf((0,ee._)`${i} === "boolean" || ${o} === null
|
|
191
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ee._)`+${o}`);return;case"boolean":n.elseIf((0,ee._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ee._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ee._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
|
|
192
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ee._)`[${o}]`)}}}function CM({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function ug(t,e,r,n=Ps.Correct){let o=n===Ps.Correct?ee.operators.EQ:ee.operators.NEQ,s;switch(t){case"null":return(0,ee._)`${e} ${o} null`;case"array":s=(0,ee._)`Array.isArray(${e})`;break;case"object":s=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ee._)`typeof ${e} ${o} ${t}`}return n===Ps.Correct?s:(0,ee.not)(s);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}dt.checkDataType=ug;function lg(t,e,r,n){if(t.length===1)return ug(t[0],e,r,n);let o,s=(0,k0.toHash)(t);if(s.array&&s.object){let i=(0,ee._)`typeof ${e} != "object"`;o=s.null?i:(0,ee._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ee.nil;s.number&&delete s.integer;for(let i in s)o=(0,ee.and)(o,ug(i,e,r,n));return o}dt.checkDataTypes=lg;var OM={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function dg(t){let e=IM(t);(0,EM.reportError)(e,OM)}dt.reportTypeError=dg;function IM(t){let{gen:e,data:r,schema:n}=t,o=(0,k0.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var T0=D(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.assignDefaults=void 0;var Rs=re(),AM=me();function NM(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$0(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$0(t,s,o.default))}zu.assignDefaults=NM;function $0(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Rs._)`${s}${(0,Rs.getProperty)(e)}`;if(o){(0,AM.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Rs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Rs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Rs._)`${a} = ${(0,Rs.stringify)(r)}`)}});var er=D(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Pe=re(),pg=me(),On=Xr(),DM=me();function MM(t,e){let{gen:r,data:n,it:o}=t;r.if(fg(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}be.checkReportMissingProp=MM;function jM({gen:t,data:e,it:{opts:r}},n,o){return(0,Pe.or)(...n.map(s=>(0,Pe.and)(fg(t,e,s,r.ownProperties),(0,Pe._)`${o} = ${s}`)))}be.checkMissingProp=jM;function zM(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=zM;function P0(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=P0;function mg(t,e,r){return(0,Pe._)`${P0(t)}.call(${e}, ${r})`}be.isOwnProperty=mg;function LM(t,e,r,n){let o=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${o} && ${mg(t,e,r)}`:o}be.propertyInData=LM;function fg(t,e,r,n){let o=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(o,(0,Pe.not)(mg(t,e,r))):o}be.noPropertyInData=fg;function R0(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=R0;function FM(t,e){return R0(e).filter(r=>!(0,pg.alwaysValidSchema)(t,e[r]))}be.schemaProperties=FM;function UM({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${o}`:e,l=[[On.default.instancePath,(0,Pe.strConcat)(On.default.instancePath,s)],[On.default.parentData,i.parentData],[On.default.parentDataProperty,i.parentDataProperty],[On.default.rootData,On.default.rootData]];i.opts.dynamicRef&&l.push([On.default.dynamicAnchors,On.default.dynamicAnchors]);let m=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${m})`:(0,Pe._)`${a}(${m})`}be.callValidateCode=UM;var HM=(0,Pe._)`new RegExp`;function ZM({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Pe._)`${o.code==="new RegExp"?HM:(0,DM.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=ZM;function BM(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:pg.Type.Num},s),e.if((0,Pe.not)(s),a)})}}be.validateArray=BM;function qM(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,pg.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=qM});var I0=D(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.validateKeywordUsage=Ar.validSchemaType=Ar.funcKeywordCode=Ar.macroKeywordCode=void 0;var xt=re(),Ro=Xr(),VM=er(),WM=sa();function GM(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=O0(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:xt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ar.macroKeywordCode=GM;function KM(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;YM(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=O0(n,o,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)h(),e.modifying&&C0(t),g(()=>t.error());else{let y=e.async?f():p();e.modifying&&C0(t),g(()=>JM(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,xt._)`await `),v=>n.assign(l,!1).if((0,xt._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,xt._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,xt._)`${d}.errors`;return n.assign(y,null),h(xt.nil),y}function h(y=e.async?(0,xt._)`await `:xt.nil){let v=c.opts.passContext?Ro.default.this:Ro.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,xt._)`${y}${(0,VM.callValidateCode)(t,d,v,_)}`,e.modifying)}function g(y){var v;n.if((0,xt.not)((v=e.valid)!==null&&v!==void 0?v:l),y)}}Ar.funcKeywordCode=KM;function C0(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,xt._)`${n.parentData}[${n.parentDataProperty}]`))}function JM(t,e){let{gen:r}=t;r.if((0,xt._)`Array.isArray(${e})`,()=>{r.assign(Ro.default.vErrors,(0,xt._)`${Ro.default.vErrors} === null ? ${e} : ${Ro.default.vErrors}.concat(${e})`).assign(Ro.default.errors,(0,xt._)`${Ro.default.vErrors}.length`),(0,WM.extendErrors)(t)},()=>t.error())}function YM({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function O0(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,xt.stringify)(r)})}function XM(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ar.validSchemaType=XM;function QM({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ar.validateKeywordUsage=QM});var N0=D(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.extendSubschemaMode=In.extendSubschemaData=In.getSubschema=void 0;var Nr=re(),A0=me();function ej(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Nr._)`${t.schemaPath}${(0,Nr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Nr._)`${t.schemaPath}${(0,Nr.getProperty)(e)}${(0,Nr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,A0.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}In.getSubschema=ej;function tj(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,m=a.let("data",(0,Nr._)`${e.data}${(0,Nr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Nr.str)`${u}${(0,A0.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Nr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Nr.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]}}In.extendSubschemaData=tj;function rj(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}In.extendSubschemaMode=rj});var hg=D((cW,D0)=>{"use strict";D0.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var j0=D((uW,M0)=>{"use strict";var An=M0.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Lu(e,n,o,t,"",t)};An.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};An.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};An.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};An.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 Lu(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in An.arrayKeywords)for(var m=0;m<l.length;m++)Lu(t,e,r,l[m],o+"/"+d+"/"+m,s,o,d,n,m)}else if(d in An.propsKeywords){if(l&&typeof l=="object")for(var f in l)Lu(t,e,r,l[f],o+"/"+d+"/"+nj(f),s,o,d,n,f)}else(d in An.keywords||t.allKeys&&!(d in An.skipKeywords))&&Lu(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function nj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var aa=D(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.getSchemaRefs=It.resolveUrl=It.normalizeId=It._getFullPath=It.getFullPath=It.inlineRef=void 0;var oj=me(),sj=hg(),ij=j0(),aj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cj(t,e=!0){return typeof t=="boolean"?!0:e===!0?!gg(t):e?z0(t)<=e:!1}It.inlineRef=cj;var uj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gg(t){for(let e in t){if(uj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(gg)||typeof r=="object"&&gg(r))return!0}return!1}function z0(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!aj.has(r)&&(typeof t[r]=="object"&&(0,oj.eachItem)(t[r],n=>e+=z0(n)),e===1/0))return 1/0}return e}function L0(t,e="",r){r!==!1&&(e=Cs(e));let n=t.parse(e);return F0(t,n)}It.getFullPath=L0;function F0(t,e){return t.serialize(e).split("#")[0]+"#"}It._getFullPath=F0;var lj=/#\/?$/;function Cs(t){return t?t.replace(lj,""):""}It.normalizeId=Cs;function dj(t,e,r){return r=Cs(r),t.resolve(e,r)}It.resolveUrl=dj;var pj=/^[a-z_][-a-z0-9._]*$/i;function mj(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Cs(t[r]||e),s={"":o},i=L0(n,o,!1),a={},c=new Set;return ij(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=s[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),v.call(this,l.$anchor),v.call(this,l.$dynamicAnchor),s[m]=g;function y(_){let b=this.opts.uriResolver.resolve;if(_=Cs(g?b(g,_):_),c.has(_))throw d(_);c.add(_);let S=this.refs[_];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,_):_!==Cs(h)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!pj.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,f){if(m!==void 0&&!sj(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}It.getSchemaRefs=mj});var la=D(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.getData=Nn.KeywordCxt=Nn.validateFunctionCode=void 0;var q0=b0(),U0=ia(),_g=cg(),Fu=ia(),fj=T0(),ua=I0(),yg=N0(),V=re(),X=Xr(),hj=aa(),Qr=me(),ca=sa();function gj(t){if(G0(t)&&(K0(t),W0(t))){vj(t);return}V0(t,()=>(0,q0.topBoolOrEmptySchema)(t))}Nn.validateFunctionCode=gj;function V0({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,V._)`${X.default.data}, ${X.default.valCxt}`,n.$async,()=>{t.code((0,V._)`"use strict"; ${H0(r,o)}`),_j(t,o),t.code(s)}):t.func(e,(0,V._)`${X.default.data}, ${yj(o)}`,n.$async,()=>t.code(H0(r,o)).code(s))}function yj(t){return(0,V._)`{${X.default.instancePath}="", ${X.default.parentData}, ${X.default.parentDataProperty}, ${X.default.rootData}=${X.default.data}${t.dynamicRef?(0,V._)`, ${X.default.dynamicAnchors}={}`:V.nil}}={}`}function _j(t,e){t.if(X.default.valCxt,()=>{t.var(X.default.instancePath,(0,V._)`${X.default.valCxt}.${X.default.instancePath}`),t.var(X.default.parentData,(0,V._)`${X.default.valCxt}.${X.default.parentData}`),t.var(X.default.parentDataProperty,(0,V._)`${X.default.valCxt}.${X.default.parentDataProperty}`),t.var(X.default.rootData,(0,V._)`${X.default.valCxt}.${X.default.rootData}`),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,V._)`${X.default.valCxt}.${X.default.dynamicAnchors}`)},()=>{t.var(X.default.instancePath,(0,V._)`""`),t.var(X.default.parentData,(0,V._)`undefined`),t.var(X.default.parentDataProperty,(0,V._)`undefined`),t.var(X.default.rootData,X.default.data),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,V._)`{}`)})}function vj(t){let{schema:e,opts:r,gen:n}=t;V0(t,()=>{r.$comment&&e.$comment&&Y0(t),wj(t),n.let(X.default.vErrors,null),n.let(X.default.errors,0),r.unevaluated&&bj(t),J0(t),Tj(t)})}function bj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,V._)`${r}.evaluated`),e.if((0,V._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${t.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${t.evaluated}.items`,(0,V._)`undefined`))}function H0(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${r} */`:V.nil}function xj(t,e){if(G0(t)&&(K0(t),W0(t))){Sj(t,e);return}(0,q0.boolOrEmptySchema)(t,e)}function W0({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function G0(t){return typeof t.schema!="boolean"}function Sj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Y0(t),Ej(t),$j(t);let s=n.const("_errs",X.default.errors);J0(t,s),n.var(e,(0,V._)`${s} === ${X.default.errors}`)}function K0(t){(0,Qr.checkUnknownRules)(t),kj(t)}function J0(t,e){if(t.opts.jtd)return Z0(t,[],!1,e);let r=(0,U0.getSchemaTypes)(t.schema),n=(0,U0.coerceAndCheckDataType)(t,r);Z0(t,r,!n,e)}function kj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Qr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function wj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Qr.checkStrictMode)(t,"default is ignored in the schema root")}function Ej(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,hj.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function $j(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Y0({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,V._)`${X.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,V.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,V._)`${X.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Tj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,V._)`${X.default.errors} === 0`,()=>e.return(X.default.data),()=>e.throw((0,V._)`new ${o}(${X.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,X.default.vErrors),s.unevaluated&&Pj(t),e.return((0,V._)`${X.default.errors} === 0`))}function Pj({gen:t,evaluated:e,props:r,items:n}){r instanceof V.Name&&t.assign((0,V._)`${e}.props`,r),n instanceof V.Name&&t.assign((0,V._)`${e}.items`,n)}function Z0(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Qr.schemaHasRulesButRef)(s,d))){o.block(()=>Q0(t,"$ref",d.all.$ref.definition));return}c.jtd||Rj(t,e),o.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,_g.shouldUseGroup)(s,m)&&(m.type?(o.if((0,Fu.checkDataType)(m.type,i,c.strictNumbers)),B0(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,Fu.reportTypeError)(t)),o.endIf()):B0(t,m),a||o.if((0,V._)`${X.default.errors} === ${n||0}`))}}function B0(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,fj.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,_g.shouldUseRule)(n,s)&&Q0(t,s.keyword,s.definition,e.type)})}function Rj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Cj(t,e),t.opts.allowUnionTypes||Oj(t,e),Ij(t,t.dataTypes))}function Cj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{X0(t.dataTypes,r)||vg(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Nj(t,e)}}function Oj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vg(t,"use allowUnionTypes to allow union type keyword")}function Ij(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,_g.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Aj(e,i))&&vg(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Aj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function X0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Nj(t,e){let r=[];for(let n of t.dataTypes)X0(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function vg(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Qr.checkStrictMode)(t,e,t.opts.strictTypes)}var Uu=class{constructor(e,r,n){if((0,ua.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Qr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",ew(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ua.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",X.default.errors))}result(e,r,n){this.failResult((0,V.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,V.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,V._)`${r} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ca.reportExtraError:ca.reportError)(this,this.def.error,r)}$dataError(){(0,ca.reportError)(this,this.def.$dataError||ca.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ca.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=V.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=V.nil,r=V.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,V.or)((0,V._)`${o} === undefined`,r)),e!==V.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,V.or)(i(),a());function i(){if(n.length){if(!(r instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,Fu.checkDataTypes)(c,r,s.opts.strictNumbers,Fu.DataType.Wrong)}`}return V.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,V._)`!${c}(${r})`}return V.nil}}subschema(e,r){let n=(0,yg.getSubschema)(this.it,e);(0,yg.extendSubschemaData)(n,this.it,e),(0,yg.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return xj(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Qr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Qr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,V.Name)),!0}};Nn.KeywordCxt=Uu;function Q0(t,e,r,n){let o=new Uu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ua.funcKeywordCode)(o,r):"macro"in r?(0,ua.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ua.funcKeywordCode)(o,r)}var Dj=/^\/(?:[^~]|~0|~1)*$/,Mj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ew(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return X.default.rootData;if(t[0]==="/"){if(!Dj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=X.default.rootData}else{let u=Mj.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,V._)`${s}${(0,V.getProperty)((0,Qr.unescapeJsonPointer)(u))}`,i=(0,V._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Nn.getData=ew});var Hu=D(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var bg=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xg.default=bg});var da=D(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var Sg=aa(),kg=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Sg.resolveUrl)(e,r,n),this.missingSchema=(0,Sg.normalizeId)((0,Sg.getFullPath)(e,this.missingRef))}};wg.default=kg});var Bu=D(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.resolveSchema=tr.getCompilingSchema=tr.resolveRef=tr.compileSchema=tr.SchemaEnv=void 0;var gr=re(),jj=Hu(),Co=Xr(),yr=aa(),tw=me(),zj=la(),Os=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,yr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};tr.SchemaEnv=Os;function $g(t){let e=rw.call(this,t);if(e)return e;let r=(0,yr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new gr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:jj.default,code:(0,gr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Co.default.data,parentData:Co.default.parentData,parentDataProperty:Co.default.parentDataProperty,dataNames:[Co.default.data],dataPathArr:[gr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,gr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:gr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,zj.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(Co.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${Co.default.self}`,`${Co.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof gr.Name?void 0:p,items:h instanceof gr.Name?void 0:h,dynamicProps:p instanceof gr.Name,dynamicItems:h instanceof gr.Name},f.source&&(f.source.evaluated=(0,gr.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}tr.compileSchema=$g;function Lj(t,e,r){var n;r=(0,yr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Hj.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Os({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Fj.call(this,s)}tr.resolveRef=Lj;function Fj(t){return(0,yr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:$g.call(this,t)}function rw(t){for(let e of this._compilations)if(Uj(e,t))return e}tr.getCompilingSchema=rw;function Uj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Hj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Zu.call(this,t,e)}function Zu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,yr._getFullPath)(this.opts.uriResolver,r),o=(0,yr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Eg.call(this,r,t);let s=(0,yr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Zu.call(this,t,i);return typeof a?.schema!="object"?void 0:Eg.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||$g.call(this,i),s===(0,yr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,yr.resolveUrl)(this.opts.uriResolver,o,u)),new Os({schema:a,schemaId:c,root:t,baseId:o})}return Eg.call(this,r,i)}}tr.resolveSchema=Zu;var Zj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eg(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,tw.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Zj.has(a)&&u&&(e=(0,yr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,tw.schemaHasRulesButRef)(r,this.RULES)){let a=(0,yr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Zu.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Os({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var nw=D((hW,Bj)=>{Bj.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 Pg=D((gW,aw)=>{"use strict";var qj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),sw=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Tg(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Vj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ow(t){return t.length=0,!0}function Wj(t,e,r){if(t.length){let n=Tg(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Gj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Wj;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=ow}else{o.push(u);continue}}return o.length&&(a===ow?r.zone=o.join(""):i?n.push(o.join("")):n.push(Tg(o))),r.address=n.join(""),r}function iw(t){if(Kj(t,":")<2)return{host:t,isIPV6:!1};let e=Gj(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Kj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Jj(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function Yj(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function Xj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!sw(r)){let n=iw(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}aw.exports={nonSimpleDomain:Vj,recomposeAuthority:Xj,normalizeComponentEncoding:Yj,removeDotSegments:Jj,isIPv4:sw,isUUID:qj,normalizeIPv6:iw,stringArrayToHexStripped:Tg}});var pw=D((yW,dw)=>{"use strict";var{isUUID:Qj}=Pg(),ez=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,tz=["http","https","ws","wss","urn","urn:uuid"];function rz(t){return tz.indexOf(t)!==-1}function Rg(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 cw(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function uw(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 nz(t){return t.secure=Rg(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function oz(t){if((t.port===(Rg(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function sz(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(ez);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Cg(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function iz(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Cg(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function az(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Qj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function cz(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var lw={scheme:"http",domainHost:!0,parse:cw,serialize:uw},uz={scheme:"https",domainHost:lw.domainHost,parse:cw,serialize:uw},qu={scheme:"ws",domainHost:!0,parse:nz,serialize:oz},lz={scheme:"wss",domainHost:qu.domainHost,parse:qu.parse,serialize:qu.serialize},dz={scheme:"urn",parse:sz,serialize:iz,skipNormalize:!0},pz={scheme:"urn:uuid",parse:az,serialize:cz,skipNormalize:!0},Vu={http:lw,https:uz,ws:qu,wss:lz,urn:dz,"urn:uuid":pz};Object.setPrototypeOf(Vu,null);function Cg(t){return t&&(Vu[t]||Vu[t.toLowerCase()])||void 0}dw.exports={wsIsSecure:Rg,SCHEMES:Vu,isValidSchemeName:rz,getSchemeHandler:Cg}});var hw=D((_W,Gu)=>{"use strict";var{normalizeIPv6:mz,removeDotSegments:pa,recomposeAuthority:fz,normalizeComponentEncoding:Wu,isIPv4:hz,nonSimpleDomain:gz}=Pg(),{SCHEMES:yz,getSchemeHandler:mw}=pw();function _z(t,e){return typeof t=="string"?t=Dr(en(t,e),e):typeof t=="object"&&(t=en(Dr(t,e),e)),t}function vz(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=fw(en(t,n),en(e,n),n,!0);return n.skipEscape=!0,Dr(o,n)}function fw(t,e,r,n){let o={};return n||(t=en(Dr(t,r),r),e=en(Dr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pa(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=pa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=pa(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=pa(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 bz(t,e,r){return typeof t=="string"?(t=unescape(t),t=Dr(Wu(en(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Dr(Wu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Dr(Wu(en(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Dr(Wu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Dr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=mw(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=fz(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=pa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var xz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function en(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(xz);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(hz(n.host)===!1){let c=mz(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=mw(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&gz(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Og={SCHEMES:yz,normalize:_z,resolve:vz,resolveComponent:fw,equal:bz,serialize:Dr,parse:en};Gu.exports=Og;Gu.exports.default=Og;Gu.exports.fastUri=Og});var yw=D(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var gw=hw();gw.code='require("ajv/dist/runtime/uri").default';Ig.default=gw});var Ew=D(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.CodeGen=st.Name=st.nil=st.stringify=st.str=st._=st.KeywordCxt=void 0;var Sz=la();Object.defineProperty(st,"KeywordCxt",{enumerable:!0,get:function(){return Sz.KeywordCxt}});var Is=re();Object.defineProperty(st,"_",{enumerable:!0,get:function(){return Is._}});Object.defineProperty(st,"str",{enumerable:!0,get:function(){return Is.str}});Object.defineProperty(st,"stringify",{enumerable:!0,get:function(){return Is.stringify}});Object.defineProperty(st,"nil",{enumerable:!0,get:function(){return Is.nil}});Object.defineProperty(st,"Name",{enumerable:!0,get:function(){return Is.Name}});Object.defineProperty(st,"CodeGen",{enumerable:!0,get:function(){return Is.CodeGen}});var kz=Hu(),Sw=da(),wz=ag(),ma=Bu(),Ez=re(),fa=aa(),Ku=ia(),Ng=me(),_w=nw(),$z=yw(),kw=(t,e)=>new RegExp(t,e);kw.code="new RegExp";var Tz=["removeAdditional","useDefaults","coerceTypes"],Pz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Rz={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."},Cz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},vw=200;function Oz(t){var e,r,n,o,s,i,a,c,u,d,l,m,f,p,h,g,y,v,_,b,S,P,$,R,A;let z=t.strict,w=(e=t.code)===null||e===void 0?void 0:e.optimize,H=w===!0||w===void 0?1:w||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:kw,ae=(o=t.uriResolver)!==null&&o!==void 0?o:$z.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:z)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:z)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:z)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:z)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:z)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:H,regExp:F}:{optimize:H,regExp:F},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:vw,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:vw,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(R=t.unicodeRegExp)!==null&&R!==void 0?R:!0,int32range:(A=t.int32range)!==null&&A!==void 0?A:!0,uriResolver:ae}}var ha=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,...Oz(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Ez.ValueScope({scope:{},prefixes:Pz,es5:r,lines:n}),this.logger=jz(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,wz.getRules)(),bw.call(this,Rz,e,"NOT SUPPORTED"),bw.call(this,Cz,e,"DEPRECATED","warn"),this._metaOpts=Dz.call(this),e.formats&&Az.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Nz.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Iz.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=_w;n==="id"&&(o={..._w},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let m=this._addSchema(d,l);return m.validate||i.call(this,m)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Sw.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,fa.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=xw.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ma.SchemaEnv({schema:{},schemaId:n});if(r=ma.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=xw.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,fa.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Lz.call(this,n,r),!r)return(0,Ng.eachItem)(n,s=>Ag.call(this,s)),this;Uz.call(this,r);let o={...r,type:(0,Ku.getJSONTypes)(r.type),schemaType:(0,Ku.getJSONTypes)(r.schemaType)};return(0,Ng.eachItem)(n,o.type.length===0?s=>Ag.call(this,s,o):s=>o.type.forEach(i=>Ag.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=ww(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,fa.normalizeId)(i||n);let u=fa.getSchemaRefs.call(this,e,n);return c=new ma.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ma.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ma.compileSchema.call(this,e)}finally{this.opts=r}}};ha.ValidationError=kz.default;ha.MissingRefError=Sw.default;st.default=ha;function bw(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function xw(t){return t=(0,fa.normalizeId)(t),this.schemas[t]||this.refs[t]}function Iz(){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 Az(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Nz(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Dz(){let t={...this.opts};for(let e of Tz)delete t[e];return t}var Mz={log(){},warn(){},error(){}};function jz(t){if(t===!1)return Mz;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 zz=/^[a-z_$][a-z0-9_$:-]*$/i;function Lz(t,e){let{RULES:r}=this;if((0,Ng.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!zz.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Ag(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ku.getJSONTypes)(e.type),schemaType:(0,Ku.getJSONTypes)(e.schemaType)}};e.before?Fz.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Fz(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Uz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=ww(e)),t.validateSchema=this.compile(e,!0))}var Hz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ww(t){return{anyOf:[t,Hz]}}});var $w=D(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var Zz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Dg.default=Zz});var Cw=D(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.callRef=Oo.getValidate=void 0;var Bz=da(),Tw=er(),At=re(),As=Xr(),Pw=Bu(),Ju=me(),qz={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=Pw.resolveRef.call(c,u,o,r);if(d===void 0)throw new Bz.default(n.opts.uriResolver,o,r);if(d instanceof Pw.SchemaEnv)return m(d);return f(d);function l(){if(s===u)return Yu(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return Yu(t,(0,At._)`${p}.validate`,u,u.$async)}function m(p){let h=Rw(t,p);Yu(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,At.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:At.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function Rw(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,At._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Oo.getValidate=Rw;function Yu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?As.default.this:At.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,At._)`await ${(0,Tw.callValidateCode)(t,e,u)}`),f(e),i||o.assign(p,!0)},h=>{o.if((0,At._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(p,!1)}),t.ok(p)}function l(){t.result((0,Tw.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,At._)`${p}.errors`;o.assign(As.default.vErrors,(0,At._)`${As.default.vErrors} === null ? ${h} : ${As.default.vErrors}.concat(${h})`),o.assign(As.default.errors,(0,At._)`${As.default.vErrors}.length`)}function f(p){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Ju.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,At._)`${p}.evaluated.props`);s.props=Ju.mergeEvaluated.props(o,y,s.props,At.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Ju.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,At._)`${p}.evaluated.items`);s.items=Ju.mergeEvaluated.items(o,y,s.items,At.Name)}}}Oo.callRef=Yu;Oo.default=qz});var Ow=D(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Vz=$w(),Wz=Cw(),Gz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Vz.default,Wz.default];Mg.default=Gz});var Iw=D(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var Xu=re(),Dn=Xu.operators,Qu={maximum:{okStr:"<=",ok:Dn.LTE,fail:Dn.GT},minimum:{okStr:">=",ok:Dn.GTE,fail:Dn.LT},exclusiveMaximum:{okStr:"<",ok:Dn.LT,fail:Dn.GTE},exclusiveMinimum:{okStr:">",ok:Dn.GT,fail:Dn.LTE}},Kz={message:({keyword:t,schemaCode:e})=>(0,Xu.str)`must be ${Qu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Xu._)`{comparison: ${Qu[t].okStr}, limit: ${e}}`},Jz={keyword:Object.keys(Qu),type:"number",schemaType:"number",$data:!0,error:Kz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Xu._)`${r} ${Qu[e].fail} ${n} || isNaN(${r})`)}};jg.default=Jz});var Aw=D(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var ga=re(),Yz={message:({schemaCode:t})=>(0,ga.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ga._)`{multipleOf: ${t}}`},Xz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Yz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ga._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ga._)`${i} !== parseInt(${i})`;t.fail$data((0,ga._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zg.default=Xz});var Dw=D(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});function Nw(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Lg.default=Nw;Nw.code='require("ajv/dist/runtime/ucs2length").default'});var Mw=D(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var Io=re(),Qz=me(),eL=Dw(),tL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Io.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Io._)`{limit: ${t}}`},rL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Io.operators.GT:Io.operators.LT,i=o.opts.unicode===!1?(0,Io._)`${r}.length`:(0,Io._)`${(0,Qz.useFunc)(t.gen,eL.default)}(${r})`;t.fail$data((0,Io._)`${i} ${s} ${n}`)}};Fg.default=rL});var jw=D(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var nL=er(),oL=me(),Ns=re(),sL={message:({schemaCode:t})=>(0,Ns.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ns._)`{pattern: ${t}}`},iL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:sL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Ns._)`new RegExp`:(0,oL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Ns._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ns._)`!${d}`)}else{let c=(0,nL.usePattern)(t,o);t.fail$data((0,Ns._)`!${c}.test(${r})`)}}};Ug.default=iL});var zw=D(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var ya=re(),aL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ya.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ya._)`{limit: ${t}}`},cL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:aL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ya.operators.GT:ya.operators.LT;t.fail$data((0,ya._)`Object.keys(${r}).length ${o} ${n}`)}};Hg.default=cL});var Lw=D(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var _a=er(),va=re(),uL=me(),lL={message:({params:{missingProperty:t}})=>(0,va.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,va._)`{missingProperty: ${t}}`},dL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,uL.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(va.nil,l);else for(let f of r)(0,_a.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,_a.checkMissingProp)(t,r,f)),(0,_a.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,_a.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,_a.propertyInData)(e,o,f,a.ownProperties)),e.if((0,va.not)(p),()=>{t.error(),e.break()})},va.nil)}}};Zg.default=dL});var Fw=D(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var ba=re(),pL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ba.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ba._)`{limit: ${t}}`},mL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ba.operators.GT:ba.operators.LT;t.fail$data((0,ba._)`${r}.length ${o} ${n}`)}};Bg.default=mL});var el=D(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var Uw=hg();Uw.code='require("ajv/dist/runtime/equal").default';qg.default=Uw});var Hw=D(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var Vg=ia(),it=re(),fL=me(),hL=el(),gL={message:({params:{i:t,j:e}})=>(0,it.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,it._)`{i: ${t}, j: ${e}}`},yL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gL,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Vg.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,it._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,it._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,it._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),y=(0,Vg.checkDataTypes)(u,g,a.opts.strictNumbers,Vg.DataType.Wrong),v=e.const("indices",(0,it._)`{}`);e.for((0,it._)`;${p}--;`,()=>{e.let(g,(0,it._)`${r}[${p}]`),e.if(y,(0,it._)`continue`),u.length>1&&e.if((0,it._)`typeof ${g} == "string"`,(0,it._)`${g} += "_"`),e.if((0,it._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,it._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,it._)`${v}[${g}] = ${p}`)})}function f(p,h){let g=(0,fL.useFunc)(e,hL.default),y=e.name("outer");e.label(y).for((0,it._)`;${p}--;`,()=>e.for((0,it._)`${h} = ${p}; ${h}--;`,()=>e.if((0,it._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Wg.default=yL});var Zw=D(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Gg=re(),_L=me(),vL=el(),bL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Gg._)`{allowedValue: ${t}}`},xL={keyword:"const",$data:!0,error:bL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Gg._)`!${(0,_L.useFunc)(e,vL.default)}(${r}, ${o})`):t.fail((0,Gg._)`${s} !== ${r}`)}};Kg.default=xL});var Bw=D(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var xa=re(),SL=me(),kL=el(),wL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xa._)`{allowedValues: ${t}}`},EL={keyword:"enum",schemaType:"array",$data:!0,error:wL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,SL.useFunc)(e,kL.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);d=(0,xa.or)(...o.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,xa._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=o[p];return typeof h=="object"&&h!==null?(0,xa._)`${u()}(${r}, ${f}[${p}])`:(0,xa._)`${r} === ${h}`}}};Jg.default=EL});var qw=D(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var $L=Iw(),TL=Aw(),PL=Mw(),RL=jw(),CL=zw(),OL=Lw(),IL=Fw(),AL=Hw(),NL=Zw(),DL=Bw(),ML=[$L.default,TL.default,PL.default,RL.default,CL.default,OL.default,IL.default,AL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NL.default,DL.default];Yg.default=ML});var Qg=D(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.validateAdditionalItems=void 0;var Ao=re(),Xg=me(),jL={message:({params:{len:t}})=>(0,Ao.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ao._)`{limit: ${t}}`},zL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:jL,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Xg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vw(t,n)}};function Vw(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Ao._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ao._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Xg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Ao._)`${a} <= ${e.length}`);r.if((0,Ao.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:Xg.Type.Num},u),i.allErrors||r.if((0,Ao.not)(u),()=>r.break())})}}Sa.validateAdditionalItems=Vw;Sa.default=zL});var ey=D(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.validateTuple=void 0;var Ww=re(),tl=me(),LL=er(),FL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Gw(t,"additionalItems",e);r.items=!0,!(0,tl.alwaysValidSchema)(r,e)&&t.ok((0,LL.validateArray)(t))}};function Gw(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=tl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Ww._)`${s}.length`);r.forEach((l,m)=>{(0,tl.alwaysValidSchema)(a,l)||(n.if((0,Ww._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,tl.checkStrictMode)(a,g,m.strictTuples)}}}ka.validateTuple=Gw;ka.default=FL});var Kw=D(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var UL=ey(),HL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,UL.validateTuple)(t,"items")};ty.default=HL});var Yw=D(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});var Jw=re(),ZL=me(),BL=er(),qL=Qg(),VL={message:({params:{len:t}})=>(0,Jw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Jw._)`{limit: ${t}}`},WL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:VL,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,ZL.alwaysValidSchema)(n,e)&&(o?(0,qL.validateAdditionalItems)(t,o):t.ok((0,BL.validateArray)(t)))}};ry.default=WL});var Xw=D(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var rr=re(),rl=me(),GL={message:({params:{min:t,max:e}})=>e===void 0?(0,rr.str)`must contain at least ${t} valid item(s)`:(0,rr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,rr._)`{minContains: ${t}}`:(0,rr._)`{minContains: ${t}, maxContains: ${e}}`},KL={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GL,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,rr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,rl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,rl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,rl.alwaysValidSchema)(s,r)){let h=(0,rr._)`${d} >= ${i}`;a!==void 0&&(h=(0,rr._)`${h} && ${d} <= ${a}`),t.pass(h);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,rr._)`${o}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:rl.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,rr._)`${h}++`),a===void 0?e.if((0,rr._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,rr._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,rr._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};ny.default=KL});var tE=D(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.validateSchemaDeps=Mr.validatePropertyDeps=Mr.error=void 0;var oy=re(),JL=me(),wa=er();Mr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,oy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,oy._)`{property: ${t},
|
|
73
193
|
missingProperty: ${n},
|
|
74
194
|
depsCount: ${e},
|
|
75
|
-
deps: ${r}}`};var tL={keyword:"dependencies",type:"object",schemaType:"object",error:Ir.error,code(t){let[e,r]=rL(t);Sw(t,e),kw(t,r)}};function rL({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function Sw(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,ca.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,ca.checkReportMissingProp)(t,u)}):(r.if((0,Zg._)`${c} && (${(0,ca.checkMissingProp)(t,a,o)})`),(0,ca.reportMissingProp)(t,o),r.else())}}Ir.validatePropertyDeps=Sw;function kw(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,eL.alwaysValidSchema)(o,e[a])||(r.if((0,ca.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ir.validateSchemaDeps=kw;Ir.default=tL});var $w=M(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var Ew=re(),nL=pe(),sL={message:"property name must be valid",params:({params:t})=>(0,Ew._)`{propertyName: ${t.propertyName}}`},oL={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:sL,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,nL.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Ew.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Bg.default=oL});var Vg=M(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var Lu=Xt(),gr=re(),iL=Wr(),Fu=pe(),aL={message:"must NOT have additional properties",params:({params:t})=>(0,gr._)`{additionalProperty: ${t.additionalProperty}}`},cL={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aL,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Fu.alwaysValidSchema)(i,r))return;let u=(0,Lu.allSchemaProperties)(n.properties),d=(0,Lu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,gr._)`${o} === ${iL.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let v=(0,Fu.schemaRefOrVal)(i,n.properties,"properties");y=(0,Lu.isOwnProperty)(e,v,g)}else u.length?y=(0,gr.or)(...u.map(v=>(0,gr._)`${g} === ${v}`)):y=gr.nil;return d.length&&(y=(0,gr.or)(y,...d.map(v=>(0,gr._)`${(0,Lu.usePattern)(t,v)}.test(${g})`))),(0,gr.not)(y)}function f(g){e.code((0,gr._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Fu.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,gr.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,gr.not)(y),()=>e.break()))}}function h(g,y,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:Fu.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};qg.default=cL});var Rw=M(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var uL=Gi(),Tw=Xt(),Wg=pe(),Pw=Vg(),lL={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Pw.default.code(new uL.KeywordCxt(o,Pw.default,"additionalProperties"));let i=(0,Tw.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Wg.mergeEvaluated.props(e,(0,Wg.toHash)(i),o.props));let a=i.filter(l=>!(0,Wg.alwaysValidSchema)(o,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,Tw.propertyInData)(e,s,l,o.opts.ownProperties)),d(l),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return o.opts.useDefaults&&!o.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};Gg.default=lL});var Aw=M(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Cw=Xt(),Uu=re(),Ow=pe(),Iw=pe(),dL={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Cw.allSchemaProperties)(r),c=a.filter(h=>(0,Ow.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof Uu.Name)&&(o.props=(0,Iw.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let h of a)u&&f(h),o.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,Ow.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,Uu._)`${(0,Cw.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Iw.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,Uu._)`${l}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,Uu.not)(d),()=>e.break())})})}}};Kg.default=dL});var Nw=M(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var pL=pe(),mL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,pL.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Jg.default=mL});var Dw=M(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var fL=Xt(),hL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fL.validateUnion,error:{message:"must match a schema in anyOf"}};Yg.default=hL});var Mw=M(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var Hu=re(),gL=pe(),yL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Hu._)`{passingSchemas: ${t.passing}}`},_L={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yL,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,l)=>{let m;(0,gL.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Hu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Hu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,Hu.Name)})})}}};Xg.default=_L});var jw=M(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});var vL=pe(),bL={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,vL.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Qg.default=bL});var Fw=M(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});var Zu=re(),Lw=pe(),xL={message:({params:t})=>(0,Zu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Zu._)`{failingKeyword: ${t.ifClause}}`},SL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:xL,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Lw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=zw(n,"then"),o=zw(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else s?e.if(a,u("then")):e.if((0,Zu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,Zu._)`${d}`):t.setParams({ifClause:d})}}}};function zw(t,e){let r=t.schema[e];return r!==void 0&&!(0,Lw.alwaysValidSchema)(t,r)}ey.default=SL});var Uw=M(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var kL=pe(),wL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,kL.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ty.default=wL});var Hw=M(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});var EL=zg(),$L=_w(),TL=Lg(),PL=bw(),RL=xw(),CL=ww(),OL=$w(),IL=Vg(),AL=Rw(),NL=Aw(),DL=Nw(),ML=Dw(),jL=Mw(),zL=jw(),LL=Fw(),FL=Uw();function UL(t=!1){let e=[DL.default,ML.default,jL.default,zL.default,LL.default,FL.default,OL.default,IL.default,CL.default,AL.default,NL.default];return t?e.push($L.default,PL.default):e.push(EL.default,TL.default),e.push(RL.default),e}ry.default=UL});var Zw=M(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var qe=re(),HL={message:({schemaCode:t})=>(0,qe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,qe._)`{format: ${t}}`},ZL={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:HL,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;s?m():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,qe._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,qe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,qe._)`${h}.type || "string"`).assign(y,(0,qe._)`${h}.validate`),()=>r.assign(g,(0,qe._)`"string"`).assign(y,h)),t.fail$data((0,qe.or)(v(),_()));function v(){return c.strictSchema===!1?qe.nil:(0,qe._)`${i} && !${y}`}function _(){let b=d.$async?(0,qe._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,qe._)`${y}(${n})`,S=(0,qe._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${n}))`;return(0,qe._)`${y} && ${y} !== true && ${g} === ${e} && !${S}`}}function f(){let p=l.formats[o];if(!p){v();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(b());function v(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(S){let T=S instanceof RegExp?(0,qe.regexpCode)(S):c.code.formats?(0,qe._)`${c.code.formats}${(0,qe.getProperty)(o)}`:void 0,$=r.scopeValue("formats",{key:o,ref:S,code:T});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,qe._)`${$}.validate`]:["string",S,$]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,qe._)`await ${y}(${n})`}return typeof g=="function"?(0,qe._)`${y}(${n})`:(0,qe._)`${y}.test(${n})`}}}};ny.default=ZL});var Bw=M(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});var BL=Zw(),qL=[BL.default];sy.default=qL});var qw=M(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.contentVocabulary=So.metadataVocabulary=void 0;So.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];So.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ww=M(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});var VL=ew(),WL=fw(),GL=Hw(),KL=Bw(),Vw=qw(),JL=[VL.default,WL.default,(0,GL.default)(),KL.default,Vw.metadataVocabulary,Vw.contentVocabulary];oy.default=JL});var Kw=M(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.DiscrError=void 0;var Gw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Gw||(Bu.DiscrError=Gw={}))});var Yw=M(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var ko=re(),iy=Kw(),Jw=$u(),YL=Ki(),XL=pe(),QL={message:({params:{discrError:t,tagName:e}})=>t===iy.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ko._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},eF={keyword:"discriminator",type:"object",schemaType:"object",error:QL,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ko._)`${r}${(0,ko.getProperty)(a)}`);e.if((0,ko._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:iy.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,ko._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:iy.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,ko.Name),p}function m(){var f;let p={},h=y(s),g=!0;for(let b=0;b<i.length;b++){let S=i[b];if(S?.$ref&&!(0,XL.schemaHasRulesButRef)(S,o.self.RULES)){let $=S.$ref;if(S=Jw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,$),S instanceof Jw.SchemaEnv&&(S=S.schema),S===void 0)throw new YL.default(o.opts.uriResolver,o.baseId,$)}let T=(f=S?.properties)===null||f===void 0?void 0:f[a];if(typeof T!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(S)),v(T,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,S){if(b.const)_(b.const,S);else if(b.enum)for(let T of b.enum)_(T,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(b,S){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=S}}}};ay.default=eF});var Xw=M((eW,tF)=>{tF.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 uy=M((Ce,cy)=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.MissingRefError=Ce.ValidationError=Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=Ce.Ajv=void 0;var rF=G0(),nF=Ww(),sF=Yw(),Qw=Xw(),oF=["/properties"],qu="http://json-schema.org/draft-07/schema",wo=class extends rF.default{_addVocabularies(){super._addVocabularies(),nF.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(sF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Qw,oF):Qw;this.addMetaSchema(e,qu,!1),this.refs["http://json-schema.org/schema"]=qu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qu)?qu:void 0)}};Ce.Ajv=wo;cy.exports=Ce=wo;cy.exports.Ajv=wo;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.default=wo;var iF=Gi();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return iF.KeywordCxt}});var Eo=re();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Eo._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Eo.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Eo.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Eo.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Eo.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Eo.CodeGen}});var aF=wu();Object.defineProperty(Ce,"ValidationError",{enumerable:!0,get:function(){return aF.default}});var cF=Ki();Object.defineProperty(Ce,"MissingRefError",{enumerable:!0,get:function(){return cF.default}})});var aE=M(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.formatNames=Nr.fastFormats=Nr.fullFormats=void 0;function Ar(t,e){return{validate:t,compare:e}}Nr.fullFormats={date:Ar(nE,my),time:Ar(dy(!0),fy),"date-time":Ar(eE(!0),oE),"iso-time":Ar(dy(),sE),"iso-date-time":Ar(eE(),iE),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fF,"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:xF,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:hF,int32:{type:"number",validate:_F},int64:{type:"number",validate:vF},float:{type:"number",validate:rE},double:{type:"number",validate:rE},password:!0,binary:!0};Nr.fastFormats={...Nr.fullFormats,date:Ar(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,my),time:Ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,fy),"date-time":Ar(/^\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,oE),"iso-time":Ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sE),"iso-date-time":Ar(/^\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,iE),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};Nr.formatNames=Object.keys(Nr.fullFormats);function uF(t){return t%4===0&&(t%100!==0||t%400===0)}var lF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nE(t){let e=lF.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&uF(r)?29:dF[n])}function my(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ly=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function dy(t){return function(r){let n=ly.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let l=o-d*c,m=s-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function fy(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function sE(t,e){if(!(t&&e))return;let r=ly.exec(t),n=ly.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var py=/t|\s/i;function eE(t){let e=dy(t);return function(n){let s=n.split(py);return s.length===2&&nE(s[0])&&e(s[1])}}function oE(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function iE(t,e){if(!(t&&e))return;let[r,n]=t.split(py),[s,o]=e.split(py),i=my(r,s);if(i!==void 0)return i||fy(n,o)}var pF=/\/|:/,mF=/^(?:[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 fF(t){return pF.test(t)&&mF.test(t)}var tE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hF(t){return tE.lastIndex=0,tE.test(t)}var gF=-(2**31),yF=2**31-1;function _F(t){return Number.isInteger(t)&&t<=yF&&t>=gF}function vF(t){return Number.isInteger(t)}function rE(){return!0}var bF=/[^\\]\\Z/;function xF(t){if(bF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var cE=M($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.formatLimitDefinition=void 0;var SF=uy(),yr=re(),Pn=yr.operators,Vu={formatMaximum:{okStr:"<=",ok:Pn.LTE,fail:Pn.GT},formatMinimum:{okStr:">=",ok:Pn.GTE,fail:Pn.LT},formatExclusiveMaximum:{okStr:"<",ok:Pn.LT,fail:Pn.GTE},formatExclusiveMinimum:{okStr:">",ok:Pn.GT,fail:Pn.LTE}},kF={message:({keyword:t,schemaCode:e})=>(0,yr.str)`should be ${Vu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,yr._)`{comparison: ${Vu[t].okStr}, limit: ${e}}`};$o.formatLimitDefinition={keyword:Object.keys(Vu),type:"string",schemaType:"string",$data:!0,error:kF,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new SF.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,yr._)`${m}[${c.schemaCode}]`);t.fail$data((0,yr.or)((0,yr._)`typeof ${f} != "object"`,(0,yr._)`${f} instanceof RegExp`,(0,yr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,yr._)`${i.code.formats}${(0,yr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,yr._)`${m}.compare(${r}, ${n}) ${Vu[s].fail} 0`}},dependencies:["format"]};var wF=t=>(t.addKeyword($o.formatLimitDefinition),t);$o.default=wF});var pE=M((ua,dE)=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});var To=aE(),EF=cE(),hy=re(),uE=new hy.Name("fullFormats"),$F=new hy.Name("fastFormats"),gy=(t,e={keywords:!0})=>{if(Array.isArray(e))return lE(t,e,To.fullFormats,uE),t;let[r,n]=e.mode==="fast"?[To.fastFormats,$F]:[To.fullFormats,uE],s=e.formats||To.formatNames;return lE(t,s,r,n),e.keywords&&(0,EF.default)(t),t};gy.get=(t,e="full")=>{let n=(e==="fast"?To.fastFormats:To.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function lE(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,hy._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}dE.exports=ua=gy;Object.defineProperty(ua,"__esModule",{value:!0});ua.default=gy});function TF(){let t=new mE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,fE.default)(t),t}var mE,fE,Wu,hE=x(()=>{mE=Ho(uy(),1),fE=Ho(pE(),1);Wu=class{constructor(e){this._ajv=e??TF()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Gu,gE=x(()=>{hs();Gu=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.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(d=>d.type==="tool_use");if(i){if(o.some(d=>d.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 d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ai,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},uo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function yE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function _E(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var vE=x(()=>{});var Ku,bE=x(()=>{Tk();hs();hE();xi();gE();vE();Ku=class extends du{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ii.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Wu,this.setRequestHandler(Of,n=>this._oninitialize(n)),this.setNotificationHandler(If,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Lf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ii.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Gu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=$k(this._capabilities,e)}setRequestHandler(e,r){let s=yn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Wt(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let d=gn(co,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=gn(ro,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new H(V.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=gn(Qc,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){_E(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&yE(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:$S.includes(r)?r:$f,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"},Uc)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.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(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(s.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},Ff,r):this.request({method:"sampling/createMessage",params:e},Ai,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},uo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},uo,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new H(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(V.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Uf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function yy(t){return!!t&&typeof t=="object"&&SE in t}function kE(t){return t[SE]?.complete}var SE,xE,wE=x(()=>{SE=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(xE||(xE={}))});var EE=x(()=>{});function RF(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"),!PF.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function CF(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function _y(t){let e=RF(t);return CF(t,e.warnings),e.isValid}var PF,$E=x(()=>{PF=/^[A-Za-z0-9._-]{1,128}$/});var Ju,TE=x(()=>{Ju=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}});var vy=x(()=>{dc();dc()});function CE(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function OE(t){return"_def"in t||"_zod"in t||CE(t)}function by(t){return typeof t!="object"||t===null||OE(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(CE)}function PE(t){if(t){if(by(t))return fs(t);if(!OE(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function IF(t){let e=yn(t);return e?Object.entries(e).map(([r,n])=>{let s=Yx(n),o=Xx(n);return{name:r,description:s,required:!o}}):[]}function Rn(t){let r=yn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Dc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function RE(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Yu,OF,la,IE=x(()=>{bE();xi();wh();hs();wE();EE();$E();TE();vy();Yu=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ku(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ju(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Rn(ao)),this.server.assertCanSetRequestHandler(Rn(co)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ao,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=eo(r.inputSchema);return s?xh(s,{strictUnions:!0,pipeStrategy:"input"}):OF})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=eo(r.outputSchema);s&&(n.outputSchema=xh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(co,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new H(V.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new H(V.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new H(V.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof H&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=eo(e.inputSchema)??e.inputSchema,i=await Ac(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Nc(a);throw new H(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new H(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=eo(e.outputSchema),o=await Ac(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Nc(i);throw new H(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new H(V.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Rn(eu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(eu,async e=>{switch(e.params.ref.type){case"ref/prompt":return HS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return ZS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(V.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new H(V.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return la;let o=yn(n.argsSchema)?.[e.params.argument.name];if(!yy(o))return la;let i=kE(o);if(!i)return la;let a=await i(e.params.argument.value,e.params.context);return RE(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return la;throw new H(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return la;let o=await s(e.params.argument.value,e.params.context);return RE(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Rn(so)),this.server.assertCanSetRequestHandler(Rn(oo)),this.server.assertCanSetRequestHandler(Rn(Yc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(so,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(oo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Yc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new H(V.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new H(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Rn(io)),this.server.assertCanSetRequestHandler(Rn(Xc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(io,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?IF(r.argsSchema):void 0}))})),this.server.setRequestHandler(Xc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=eo(n.argsSchema),o=await Ac(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=Nc(c);throw new H(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:fs(s),callback:o,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=fs(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,s&&Object.values(s).some(c=>{let u=c instanceof Et?c._def?.innerType:c;return yy(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){_y(e);let d={title:r,description:n,inputSchema:PE(s),outputSchema:PE(o),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&_y(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=fs(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=fs(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(by(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!by(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,s,o,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},OF={type:"object",properties:{}};la={completion:{values:[],hasMore:!1}}});function AF(t){return NS.parse(JSON.parse(t))}function AE(t){return JSON.stringify(t)+`
|
|
76
|
-
`}var
|
|
77
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
78
|
-
${t}`}function
|
|
195
|
+
deps: ${r}}`};var YL={keyword:"dependencies",type:"object",schemaType:"object",error:Mr.error,code(t){let[e,r]=XL(t);Qw(t,e),eE(t,r)}};function XL({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Qw(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,wa.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,wa.checkReportMissingProp)(t,u)}):(r.if((0,oy._)`${c} && (${(0,wa.checkMissingProp)(t,a,s)})`),(0,wa.reportMissingProp)(t,s),r.else())}}Mr.validatePropertyDeps=Qw;function eE(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,JL.alwaysValidSchema)(s,e[a])||(r.if((0,wa.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Mr.validateSchemaDeps=eE;Mr.default=YL});var nE=D(sy=>{"use strict";Object.defineProperty(sy,"__esModule",{value:!0});var rE=re(),QL=me(),eF={message:"property name must be valid",params:({params:t})=>(0,rE._)`{propertyName: ${t.propertyName}}`},tF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:eF,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,QL.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,rE.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};sy.default=tF});var ay=D(iy=>{"use strict";Object.defineProperty(iy,"__esModule",{value:!0});var nl=er(),_r=re(),rF=Xr(),ol=me(),nF={message:"must NOT have additional properties",params:({params:t})=>(0,_r._)`{additionalProperty: ${t.additionalProperty}}`},oF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nF,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ol.alwaysValidSchema)(i,r))return;let u=(0,nl.allSchemaProperties)(n.properties),d=(0,nl.allSchemaProperties)(n.patternProperties);l(),t.ok((0,_r._)`${s} === ${rF.default.errors}`);function l(){e.forIn("key",o,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let v=(0,ol.schemaRefOrVal)(i,n.properties,"properties");y=(0,nl.isOwnProperty)(e,v,g)}else u.length?y=(0,_r.or)(...u.map(v=>(0,_r._)`${g} === ${v}`)):y=_r.nil;return d.length&&(y=(0,_r.or)(y,...d.map(v=>(0,_r._)`${(0,nl.usePattern)(t,v)}.test(${g})`))),(0,_r.not)(y)}function f(g){e.code((0,_r._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ol.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,_r.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,_r.not)(y),()=>e.break()))}}function h(g,y,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:ol.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};iy.default=oF});var iE=D(uy=>{"use strict";Object.defineProperty(uy,"__esModule",{value:!0});var sF=la(),oE=er(),cy=me(),sE=ay(),iF={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&sE.default.code(new sF.KeywordCxt(s,sE.default,"additionalProperties"));let i=(0,oE.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=cy.mergeEvaluated.props(e,(0,cy.toHash)(i),s.props));let a=i.filter(l=>!(0,cy.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,oE.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};uy.default=iF});var lE=D(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});var aE=er(),sl=re(),cE=me(),uE=me(),aF={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,aE.allSchemaProperties)(r),c=a.filter(h=>(0,cE.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof sl.Name)&&(s.props=(0,uE.evaluatedPropsToName)(e,s.props));let{props:l}=s;m();function m(){for(let h of a)u&&f(h),s.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,cE.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,sl._)`${(0,aE.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:uE.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,sl._)`${l}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,sl.not)(d),()=>e.break())})})}}};ly.default=aF});var dE=D(dy=>{"use strict";Object.defineProperty(dy,"__esModule",{value:!0});var cF=me(),uF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,cF.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};dy.default=uF});var pE=D(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var lF=er(),dF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lF.validateUnion,error:{message:"must match a schema in anyOf"}};py.default=dF});var mE=D(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});var il=re(),pF=me(),mF={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,il._)`{passingSchemas: ${t.passing}}`},fF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mF,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let m;(0,pF.alwaysValidSchema)(o,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,il._)`${c} && ${i}`).assign(i,!1).assign(a,(0,il._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,il.Name)})})}}};my.default=fF});var fE=D(fy=>{"use strict";Object.defineProperty(fy,"__esModule",{value:!0});var hF=me(),gF={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,hF.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};fy.default=gF});var yE=D(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});var al=re(),gE=me(),yF={message:({params:t})=>(0,al.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,al._)`{failingKeyword: ${t.ifClause}}`},_F={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yF,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,gE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=hE(n,"then"),s=hE(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,al.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,al._)`${d}`):t.setParams({ifClause:d})}}}};function hE(t,e){let r=t.schema[e];return r!==void 0&&!(0,gE.alwaysValidSchema)(t,r)}hy.default=_F});var _E=D(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});var vF=me(),bF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,vF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};gy.default=bF});var vE=D(yy=>{"use strict";Object.defineProperty(yy,"__esModule",{value:!0});var xF=Qg(),SF=Kw(),kF=ey(),wF=Yw(),EF=Xw(),$F=tE(),TF=nE(),PF=ay(),RF=iE(),CF=lE(),OF=dE(),IF=pE(),AF=mE(),NF=fE(),DF=yE(),MF=_E();function jF(t=!1){let e=[OF.default,IF.default,AF.default,NF.default,DF.default,MF.default,TF.default,PF.default,$F.default,RF.default,CF.default];return t?e.push(SF.default,wF.default):e.push(xF.default,kF.default),e.push(EF.default),e}yy.default=jF});var bE=D(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var Ve=re(),zF={message:({schemaCode:t})=>(0,Ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ve._)`{format: ${t}}`},LF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zF,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?m():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,Ve._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ve._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ve._)`${h}.type || "string"`).assign(y,(0,Ve._)`${h}.validate`),()=>r.assign(g,(0,Ve._)`"string"`).assign(y,h)),t.fail$data((0,Ve.or)(v(),_()));function v(){return c.strictSchema===!1?Ve.nil:(0,Ve._)`${i} && !${y}`}function _(){let b=d.$async?(0,Ve._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ve._)`${y}(${n})`,S=(0,Ve._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${n}))`;return(0,Ve._)`${y} && ${y} !== true && ${g} === ${e} && !${S}`}}function f(){let p=l.formats[s];if(!p){v();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(b());function v(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(S){let P=S instanceof RegExp?(0,Ve.regexpCode)(S):c.code.formats?(0,Ve._)`${c.code.formats}${(0,Ve.getProperty)(s)}`:void 0,$=r.scopeValue("formats",{key:s,ref:S,code:P});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,Ve._)`${$}.validate`]:["string",S,$]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ve._)`await ${y}(${n})`}return typeof g=="function"?(0,Ve._)`${y}(${n})`:(0,Ve._)`${y}.test(${n})`}}}};_y.default=LF});var xE=D(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var FF=bE(),UF=[FF.default];vy.default=UF});var SE=D(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.contentVocabulary=Ds.metadataVocabulary=void 0;Ds.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ds.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var wE=D(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var HF=Ow(),ZF=qw(),BF=vE(),qF=xE(),kE=SE(),VF=[HF.default,ZF.default,(0,BF.default)(),qF.default,kE.metadataVocabulary,kE.contentVocabulary];by.default=VF});var $E=D(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.DiscrError=void 0;var EE;(function(t){t.Tag="tag",t.Mapping="mapping"})(EE||(cl.DiscrError=EE={}))});var PE=D(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var Ms=re(),xy=$E(),TE=Bu(),WF=da(),GF=me(),KF={message:({params:{discrError:t,tagName:e}})=>t===xy.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ms._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},JF={keyword:"discriminator",type:"object",schemaType:"object",error:KF,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Ms._)`${r}${(0,Ms.getProperty)(a)}`);e.if((0,Ms._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:xy.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,Ms._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:xy.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,Ms.Name),p}function m(){var f;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let S=i[b];if(S?.$ref&&!(0,GF.schemaHasRulesButRef)(S,s.self.RULES)){let $=S.$ref;if(S=TE.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,$),S instanceof TE.SchemaEnv&&(S=S.schema),S===void 0)throw new WF.default(s.opts.uriResolver,s.baseId,$)}let P=(f=S?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(S)),v(P,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,S){if(b.const)_(b.const,S);else if(b.enum)for(let P of b.enum)_(P,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(b,S){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=S}}}};Sy.default=JF});var RE=D((iG,YF)=>{YF.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 wy=D((Re,ky)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var XF=Ew(),QF=wE(),e2=PE(),CE=RE(),t2=["/properties"],ul="http://json-schema.org/draft-07/schema",js=class extends XF.default{_addVocabularies(){super._addVocabularies(),QF.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(e2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(CE,t2):CE;this.addMetaSchema(e,ul,!1),this.refs["http://json-schema.org/schema"]=ul}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ul)?ul:void 0)}};Re.Ajv=js;ky.exports=Re=js;ky.exports.Ajv=js;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=js;var r2=la();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return r2.KeywordCxt}});var zs=re();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return zs._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return zs.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return zs.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return zs.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return zs.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return zs.CodeGen}});var n2=Hu();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return n2.default}});var o2=da();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return o2.default}})});var zE=D(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.formatNames=zr.fastFormats=zr.fullFormats=void 0;function jr(t,e){return{validate:t,compare:e}}zr.fullFormats={date:jr(NE,Py),time:jr($y(!0),Ry),"date-time":jr(OE(!0),ME),"iso-time":jr($y(),DE),"iso-date-time":jr(OE(),jE),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:l2,"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:y2,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:d2,int32:{type:"number",validate:f2},int64:{type:"number",validate:h2},float:{type:"number",validate:AE},double:{type:"number",validate:AE},password:!0,binary:!0};zr.fastFormats={...zr.fullFormats,date:jr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Py),time:jr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ry),"date-time":jr(/^\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,ME),"iso-time":jr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,DE),"iso-date-time":jr(/^\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,jE),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zr.formatNames=Object.keys(zr.fullFormats);function s2(t){return t%4===0&&(t%100!==0||t%400===0)}var i2=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,a2=[0,31,28,31,30,31,30,31,31,30,31,30,31];function NE(t){let e=i2.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&s2(r)?29:a2[n])}function Py(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ey=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function $y(t){return function(r){let n=Ey.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,m=o-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function Ry(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function DE(t,e){if(!(t&&e))return;let r=Ey.exec(t),n=Ey.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Ty=/t|\s/i;function OE(t){let e=$y(t);return function(n){let o=n.split(Ty);return o.length===2&&NE(o[0])&&e(o[1])}}function ME(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function jE(t,e){if(!(t&&e))return;let[r,n]=t.split(Ty),[o,s]=e.split(Ty),i=Py(r,o);if(i!==void 0)return i||Ry(n,s)}var c2=/\/|:/,u2=/^(?:[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 l2(t){return c2.test(t)&&u2.test(t)}var IE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function d2(t){return IE.lastIndex=0,IE.test(t)}var p2=-(2**31),m2=2**31-1;function f2(t){return Number.isInteger(t)&&t<=m2&&t>=p2}function h2(t){return Number.isInteger(t)}function AE(){return!0}var g2=/[^\\]\\Z/;function y2(t){if(g2.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var LE=D(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.formatLimitDefinition=void 0;var _2=wy(),vr=re(),Mn=vr.operators,ll={formatMaximum:{okStr:"<=",ok:Mn.LTE,fail:Mn.GT},formatMinimum:{okStr:">=",ok:Mn.GTE,fail:Mn.LT},formatExclusiveMaximum:{okStr:"<",ok:Mn.LT,fail:Mn.GTE},formatExclusiveMinimum:{okStr:">",ok:Mn.GT,fail:Mn.LTE}},v2={message:({keyword:t,schemaCode:e})=>(0,vr.str)`should be ${ll[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vr._)`{comparison: ${ll[t].okStr}, limit: ${e}}`};Ls.formatLimitDefinition={keyword:Object.keys(ll),type:"string",schemaType:"string",$data:!0,error:v2,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new _2.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,vr._)`${m}[${c.schemaCode}]`);t.fail$data((0,vr.or)((0,vr._)`typeof ${f} != "object"`,(0,vr._)`${f} instanceof RegExp`,(0,vr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,vr._)`${i.code.formats}${(0,vr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,vr._)`${m}.compare(${r}, ${n}) ${ll[o].fail} 0`}},dependencies:["format"]};var b2=t=>(t.addKeyword(Ls.formatLimitDefinition),t);Ls.default=b2});var ZE=D((Ea,HE)=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var Fs=zE(),x2=LE(),Cy=re(),FE=new Cy.Name("fullFormats"),S2=new Cy.Name("fastFormats"),Oy=(t,e={keywords:!0})=>{if(Array.isArray(e))return UE(t,e,Fs.fullFormats,FE),t;let[r,n]=e.mode==="fast"?[Fs.fastFormats,S2]:[Fs.fullFormats,FE],o=e.formats||Fs.formatNames;return UE(t,o,r,n),e.keywords&&(0,x2.default)(t),t};Oy.get=(t,e="full")=>{let n=(e==="fast"?Fs.fastFormats:Fs.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function UE(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Cy._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}HE.exports=Ea=Oy;Object.defineProperty(Ea,"__esModule",{value:!0});Ea.default=Oy});function k2(){let t=new BE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qE.default)(t),t}var BE,qE,dl,VE=x(()=>{BE=Ys(wy(),1),qE=Ys(ZE(),1);dl=class{constructor(e){this._ajv=e??k2()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var pl,WE=x(()=>{ko();pl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(d=>d.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(d=>d.type==="tool_use");if(i){if(s.some(d=>d.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 d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ki,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},ks,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function GE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function KE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var JE=x(()=>{});var ml,YE=x(()=>{o0();ko();VE();ji();WE();JE();ml=class extends Ru{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Gi.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new dl,this.setRequestHandler(Vf,n=>this._oninitialize(n)),this.setNotificationHandler(Wf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(eh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Gi.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=n0(this._capabilities,e)}setRequestHandler(e,r){let o=En(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Kt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=wn(Ss,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new Z(W.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=wn(gs,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new Z(W.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=wn(yu,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new Z(W.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){KE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&GE(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nk.includes(r)?r:Uf,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"},su)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},th,r):this.request({method:"sampling/createMessage",params:e},Ki,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ks,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ks,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Z(W.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Z?i:new Z(W.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},rh,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Iy(t){return!!t&&typeof t=="object"&&QE in t}function e$(t){return t[QE]?.complete}var QE,XE,t$=x(()=>{QE=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(XE||(XE={}))});var r$=x(()=>{});function E2(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"),!w2.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function $2(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Ay(t){let e=E2(t);return $2(t,e.warnings),e.isValid}var w2,n$=x(()=>{w2=/^[A-Za-z0-9._-]{1,128}$/});var fl,o$=x(()=>{fl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Ny=x(()=>{Rc();Rc()});function a$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function c$(t){return"_def"in t||"_zod"in t||a$(t)}function Dy(t){return typeof t!="object"||t===null||c$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(a$)}function s$(t){if(t){if(Dy(t))return So(t);if(!c$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function P2(t){let e=En(t);return e?Object.entries(e).map(([r,n])=>{let o=PS(n),s=RS(n);return{name:r,description:o,required:!s}}):[]}function jn(t){let r=En(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function i$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var hl,T2,$a,u$=x(()=>{YE();ji();Lh();ko();t$();r$();n$();o$();Ny();hl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ml(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new fl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(xs)),this.server.assertCanSetRequestHandler(jn(Ss)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(xs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=fs(r.inputSchema);return o?Mh(o,{strictUnions:!0,pipeStrategy:"input"}):T2})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=fs(r.outputSchema);o&&(n.outputSchema=Mh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ss,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Z(W.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new Z(W.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Z(W.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof Z&&n.code===W.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=fs(e.inputSchema)??e.inputSchema,i=await Yc(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Xc(a);throw new Z(W.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(W.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=fs(e.outputSchema),s=await Yc(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Xc(i);throw new Z(W.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new Z(W.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(jn(_u)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_u,async e=>{switch(e.params.ref.type){case"ref/prompt":return vk(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return bk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(W.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(W.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return $a;let s=En(n.argsSchema)?.[e.params.argument.name];if(!Iy(s))return $a;let i=e$(s);if(!i)return $a;let a=await i(e.params.argument.value,e.params.context);return i$(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return $a;throw new Z(W.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return $a;let s=await o(e.params.argument.value,e.params.context);return i$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(_s)),this.server.assertCanSetRequestHandler(jn(vs)),this.server.assertCanSetRequestHandler(jn(hu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_s,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(vs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(hu,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(W.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new Z(W.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(bs)),this.server.assertCanSetRequestHandler(jn(gu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(bs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?P2(r.argsSchema):void 0}))})),this.server.setRequestHandler(gu,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Z(W.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Z(W.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=fs(n.argsSchema),s=await Yc(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Xc(c);throw new Z(W.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:So(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=So(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 Tt?c._def?.innerType:c;return Iy(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Ay(e);let d={title:r,description:n,inputSchema:s$(o),outputSchema:s$(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Ay(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=So(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=So(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Dy(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Dy(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},T2={type:"object",properties:{}};$a={completion:{values:[],hasMore:!1}}});function R2(t){return dk.parse(JSON.parse(t))}function l$(t){return JSON.stringify(t)+`
|
|
196
|
+
`}var gl,d$=x(()=>{ko();gl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
197
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),R2(r)}clear(){this._buffer=void 0}}});import p$ from"node:process";var yl,m$=x(()=>{d$();yl=class{constructor(e=p$.stdin,r=p$.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new gl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=l$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var k$={};Le(k$,{PolyglotExecutor:()=>Us,buildScriptFilename:()=>b$,buildShellScriptContent:()=>S$,buildSpawnOptions:()=>x$});import{spawn as f$,execSync as C2,execFileSync as _$}from"node:child_process";import{mkdtempSync as O2,writeFileSync as h$,rmSync as g$,existsSync as y$}from"node:fs";import{join as _l,resolve as v$}from"node:path";import{tmpdir as I2}from"node:os";function b$(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${A2[t]}`}function x$(t){return{windowsHide:t==="win32"}}function N2(t){return`'${t.replace(/'/g,"'\\''")}'`}function S$(t,e,r){return r==="win32"||!e?t:`export PATH=${N2(e)}
|
|
198
|
+
${t}`}function My(t){if(nr&&t.pid)try{C2(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var nr,A2,D2,Us,jy=x(()=>{"use strict";Xa();nr=process.platform==="win32",A2={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};D2=(()=>{if(nr)return process.env.TEMP??process.env.TMP??I2();try{let t=_$(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:v$(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();Us=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Lo()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(nr?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1}=e,i=O2(_l(D2,".ctx-mode-"));try{let a=this.#a(i,n,r),c=W_(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,o);let u=r==="shell"?this.#o:i,d=await this.#i(c,u,i,o,s);if(!d.backgrounded)try{g$(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{g$(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=v$(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
|
|
79
199
|
|
|
80
200
|
import "fmt"
|
|
81
201
|
|
|
@@ -83,22 +203,22 @@ func main() {
|
|
|
83
203
|
${r}
|
|
84
204
|
}
|
|
85
205
|
`),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
|
|
86
|
-
${r}`),n==="elixir"&&
|
|
206
|
+
${r}`),n==="elixir"&&y$(_l(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(_l(this.#o,"_build/dev/lib"))}, "*/ebin"))
|
|
87
207
|
|> Enum.each(&Code.prepend_path/1)
|
|
88
208
|
|
|
89
|
-
${r}`);let
|
|
90
|
-
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([
|
|
91
|
-
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:S,exitCode:m?1:_??1,timedOut:m})}),l.on("error",_=>{clearTimeout(p),!f&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),
|
|
209
|
+
${r}`);let o=_l(e,b$(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?h$(o,S$(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):h$(o,r,"utf-8"),o}async#c(e,r,n){let o=nr?".exe":"",s=e.replace(/\.rs$/,"")+o;try{_$("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
|
|
210
|
+
${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=nr&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;nr&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=nr?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!nr,...x$(process.platform)},l;if(a){let _=[c,...u].map(b=>/\s/.test(b)?JSON.stringify(b):b).join(" ");l=f$(_,[],{...d,shell:!0})}else l=f$(c,u,{...d,shell:!1});let m=!1,f=!1,p=o===void 0?void 0:setTimeout(()=>{if(m=!0,s){f=!0,l.pid&&this.#s.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let _=Buffer.concat(h).toString("utf-8"),b=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:b,exitCode:0,timedOut:!0,backgrounded:!0})}else My(l)},o),h=[],g=[],y=0,v=!1;l.stdout.on("data",_=>{y+=_.length,y<=this.#e?h.push(_):v||(v=!0,My(l))}),l.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):v||(v=!0,My(l))}),l.on("close",_=>{if(clearTimeout(p),f)return;let b=Buffer.concat(h).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");v&&(S+=`
|
|
211
|
+
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:S,exitCode:m?1:_??1,timedOut:m})}),l.on("error",_=>{clearTimeout(p),!f&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",nr&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=nr?"":"/usr/local/bin:/usr/bin:/bin"),nr){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=nr?[]:["/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(y$(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
|
|
92
212
|
const file_path = FILE_CONTENT_PATH;
|
|
93
213
|
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
|
|
94
|
-
${n}`;case"python":return`FILE_CONTENT_PATH = ${
|
|
214
|
+
${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
|
|
95
215
|
file_path = FILE_CONTENT_PATH
|
|
96
216
|
with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
|
|
97
217
|
FILE_CONTENT = _f.read()
|
|
98
|
-
${n}`;case"shell":{let
|
|
99
|
-
file_path=${
|
|
100
|
-
FILE_CONTENT=$(cat ${
|
|
101
|
-
${n}`}case"ruby":return`FILE_CONTENT_PATH = ${
|
|
218
|
+
${n}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
|
|
219
|
+
file_path=${s}
|
|
220
|
+
FILE_CONTENT=$(cat ${s})
|
|
221
|
+
${n}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
|
|
102
222
|
file_path = FILE_CONTENT_PATH
|
|
103
223
|
FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
|
|
104
224
|
${n}`;case"go":return`package main
|
|
@@ -108,7 +228,7 @@ import (
|
|
|
108
228
|
"os"
|
|
109
229
|
)
|
|
110
230
|
|
|
111
|
-
var FILE_CONTENT_PATH = ${
|
|
231
|
+
var FILE_CONTENT_PATH = ${o}
|
|
112
232
|
var file_path = FILE_CONTENT_PATH
|
|
113
233
|
|
|
114
234
|
func main() {
|
|
@@ -122,31 +242,31 @@ ${n}
|
|
|
122
242
|
use std::fs;
|
|
123
243
|
|
|
124
244
|
fn main() {
|
|
125
|
-
let file_content_path = ${
|
|
245
|
+
let file_content_path = ${o};
|
|
126
246
|
let file_path = file_content_path;
|
|
127
247
|
let file_content = fs::read_to_string(file_content_path).unwrap();
|
|
128
248
|
${n}
|
|
129
249
|
}
|
|
130
250
|
`;case"php":return`<?php
|
|
131
|
-
$FILE_CONTENT_PATH = ${
|
|
251
|
+
$FILE_CONTENT_PATH = ${o};
|
|
132
252
|
$file_path = $FILE_CONTENT_PATH;
|
|
133
253
|
$FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
|
|
134
|
-
${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${
|
|
254
|
+
${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
|
|
135
255
|
my $file_path = $FILE_CONTENT_PATH;
|
|
136
256
|
open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
|
|
137
257
|
my $FILE_CONTENT = do { local $/; <$fh> };
|
|
138
258
|
close($fh);
|
|
139
|
-
${n}`;case"r":return`FILE_CONTENT_PATH <- ${
|
|
259
|
+
${n}`;case"r":return`FILE_CONTENT_PATH <- ${o}
|
|
140
260
|
file_path <- FILE_CONTENT_PATH
|
|
141
261
|
FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
|
|
142
262
|
FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
143
|
-
${n}`;case"elixir":return`file_content_path = ${
|
|
263
|
+
${n}`;case"elixir":return`file_content_path = ${o}
|
|
144
264
|
file_path = file_content_path
|
|
145
265
|
file_content = File.read!(file_content_path)
|
|
146
|
-
${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${
|
|
266
|
+
${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
|
|
147
267
|
var file_path = FILE_CONTENT_PATH;
|
|
148
268
|
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
|
|
149
|
-
${n}`}}}});import{cpus as
|
|
269
|
+
${n}`}}}});import{cpus as M2}from"node:os";async function zy(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,M2().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let p=await t[f].run();u[f]={status:"fulfilled",value:p}}catch(p){u[f]={status:"rejected",reason:p}}o?.(f,u[f])}}let m=[];for(let f=0;f<a;f++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var w$=x(()=>{"use strict"});import{readFileSync as E$,readdirSync as O$,unlinkSync as Fy,existsSync as Ly,statSync as vl,openSync as $$,fstatSync as T$,closeSync as P$}from"node:fs";import{createHash as R$}from"node:crypto";import{tmpdir as I$}from"node:os";import{join as Uy}from"node:path";function A$(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function j2(t,e="AND"){let r=A$(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!Hs.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function z2(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=A$(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!Hs.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function L2(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function F2(t){return t<=4?1:t<=12?2:3}function Hy(){let t=I$(),e=0;try{let r=O$(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Uy(t,n);for(let a of["","-wal","-shm"])try{Fy(i+a)}catch{}e++}}}catch{}return e}function Zy(t,e){let r=0;try{if(!Ly(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=O$(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Uy(t,s),c=vl(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Ly(u))try{let d=vl(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Fy(i+u)}catch{}r++}}catch{}}catch{}return r}function U2(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function H2(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let d of i){let l=d+c,m=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function Z2(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var Hs,C$,bl,N$=x(()=>{"use strict";ln();Hs=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"]);C$=4096;bl=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#v;#b;#x;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Xe();this.#t=e??Uy(I$(),`context-mode-${process.pid}.db`),Ho(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),Uo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(oc(s)){nc(this.#t),Ho(this.#t);try{n=new r(this.#t,{timeout:3e4}),Uo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#H(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Fy(this.#t+e)}catch{}}#H(){this.#e.exec(`
|
|
150
270
|
CREATE TABLE IF NOT EXISTS sources (
|
|
151
271
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
152
272
|
label TEXT NOT NULL,
|
|
@@ -209,7 +329,7 @@ ${n}`}}}});import{cpus as FF}from"node:os";async function ky(t,e){let{concurrenc
|
|
|
209
329
|
timestamp UNINDEXED,
|
|
210
330
|
tokenize='trigram'
|
|
211
331
|
);
|
|
212
|
-
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#
|
|
332
|
+
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#f=this.#e.prepare(`
|
|
213
333
|
SELECT
|
|
214
334
|
chunks.title,
|
|
215
335
|
chunks.content,
|
|
@@ -386,192 +506,87 @@ ${n}`}}}});import{cpus as FF}from"node:os";async function ky(t,e){let{concurrenc
|
|
|
386
506
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
387
507
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
388
508
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
389
|
-
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:
|
|
390
|
-
`),
|
|
391
|
-
`).trim();if(d.length===0)return;let l=this.#Y(
|
|
509
|
+
`),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let m=$$(n,"r");try{if(!T$(m).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=E$(m,"utf-8")}finally{P$(m)}}let c=o??n??"untitled",u=this.#V(a),d=n??void 0,l=d?R$("sha256").update(a).digest("hex"):void 0;return un(()=>this.#d(u,c,a,d,l,s))}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#W(e,n);return un(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=C$,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#U(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):un(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(m=>m.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",l=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let h=this.#s.run(r,o??null,s??null);return Number(h.lastInsertRowid)}let m=this.#o.run(r,e.length,a,o??null,s??null),f=Number(m.lastInsertRowid),p=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,f,g,null,c,u,p),this.#c.run(h.title,h.content,f,g,null,c,u,p)}return f})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:l,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=j2(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#x,u=[a,s,r]):(c=this.#f,u=[a,r]),un(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=z2(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#v:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#w,u=[a,s,r]):(c=this.#y,u=[a,r]),un(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=F2(r.length),o=this.#b.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let d=L2(r,u);d<i&&(i=d,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),d=new Map,l=m=>`${m.source}::${m.title}`;for(let[m,f]of c.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}for(let[m,f]of u.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,f)=>f.score-m.score).slice(0,r).map(({result:m,score:f})=>({...m,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!Hs.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/s.length):0,l=0,m=0;if(s.length>=2){let f=i.content.toLowerCase(),p=s.map(h=>U2(f,h));if(!p.some(h=>h.length===0)){l=1/(1+Z2(p)/Math.max(f.length,1));let g=H2(p,s);m=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like"){this.#B();let i=this.#z(e,r,n,o,s);if(i.length>0)return this.#L(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!Hs.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,o,s);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!Ly(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=vl(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=$$(r.file_path,"r"),i;try{if(!T$(s).isFile())continue;i=E$(s,"utf-8")}finally{P$(s)}if(R$("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#T.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#R.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let d of this.#C.iterate(e)){let l=new Set(d.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(m=>m.length>=3&&!Hs.has(m)));for(let m of l)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=s&&d<=i).map(([d,l])=>{let m=Math.log(o/l),f=Math.min(d.length/20,.5),p=/[_]/.test(d),h=d.length>=12,g=p?1.5:h?.8:0;return{word:d,score:m+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return vl(this.#t).size}catch{return 0}}#F(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#F(),Zo(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Hs.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#V(e,r=C$){let n=[],o=e.split(`
|
|
510
|
+
`),s=[],i=[],a="",c=()=>{let d=i.join(`
|
|
511
|
+
`).trim();if(d.length===0)return;let l=this.#Y(s,a),m=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(d)<=r){n.push({title:l,content:d,hasCode:m}),i=[];return}let f=d.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
|
|
392
512
|
|
|
393
513
|
`).trim();if(y.length===0)return;let v=f.length>1?`${l} (${h})`:l;h++,n.push({title:v,content:y,hasCode:y.includes("```")}),p=[]};for(let y of f){p.push(y);let v=p.join(`
|
|
394
514
|
|
|
395
|
-
`);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<
|
|
396
|
-
`)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let
|
|
397
|
-
`);if(
|
|
398
|
-
`)})}return
|
|
515
|
+
`);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<o.length;){let d=o[u];if(/^[-_*]{3,}\s*$/.test(d)){c(),u++;continue}let l=d.match(/^(#{1,4})\s+(.+)$/);if(l){c();let f=l[1].length,p=l[2].trim();for(;s.length>0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:p}),a=p,i.push(d),u++;continue}let m=d.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[d];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(f)&&o[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
|
|
516
|
+
`)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let o=e.split(`
|
|
517
|
+
`);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let d=c+1,l=Math.min(c+u.length,o.length),m=u[0]?.trim().slice(0,80);s.push({title:m||`Lines ${d}-${l}`,content:u.join(`
|
|
518
|
+
`)})}return s}#U(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#K(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#J(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(s,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>o&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function By(t,e){return t===void 0?e:`${t}::${e}`}var D$=x(()=>{"use strict"});import{readFileSync as j$,realpathSync as B2}from"node:fs";import{resolve as Ta}from"node:path";function z$(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function q2(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function V2(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function M$(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function W2(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=V2(o),a=M$(s);r=`^${i}(\\s${a})?$`}else r=`^${M$(t)}$`;return new RegExp(r,e?"i":"")}function G2(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function K2(t,e,r=!1){for(let n of e){let o=z$(n);if(o&&W2(o,r).test(t))return n}return null}function J2(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function qy(t){let e;try{e=j$(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&z$(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function Vy(t,e){let r=[];if(t){let o=Ta(t,".claude","settings.local.json"),s=qy(o);s&&r.push(s);let i=Ta(t,".claude","settings.json"),a=qy(i);a&&r.push(a)}let n=e!==void 0?[e]:pp();for(let o of n){let s=qy(o);s&&r.push(s)}return r}function Wy(t,e,r){let n=[],o=i=>{let a;try{a=j$(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let m=q2(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=o(Ta(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Ta(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:pp();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function Gy(t,e,r=process.platform==="win32"){let n=J2(t);for(let o of n)for(let s of e){let i=K2(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Ky(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Ta(n,t);s.add(o(i));try{s.add(o(B2(i)))}catch{}}for(let i of e)for(let a of i){let c=G2(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function X2(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function L$(t,e){let r=Y2[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...X2(t)),n}var Y2,F$=x(()=>{"use strict";hn();Y2={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]}});function Jy(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
|
|
399
519
|
|
|
400
520
|
stdout:
|
|
401
521
|
${n}
|
|
402
522
|
|
|
403
523
|
stderr:
|
|
404
|
-
${
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
source_hook TEXT NOT NULL,
|
|
418
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
419
|
-
data_hash TEXT NOT NULL DEFAULT ''
|
|
420
|
-
);
|
|
421
|
-
|
|
422
|
-
CREATE INDEX IF NOT EXISTS idx_session_events_session ON session_events(session_id);
|
|
423
|
-
CREATE INDEX IF NOT EXISTS idx_session_events_type ON session_events(session_id, type);
|
|
424
|
-
CREATE INDEX IF NOT EXISTS idx_session_events_priority ON session_events(session_id, priority);
|
|
425
|
-
|
|
426
|
-
CREATE TABLE IF NOT EXISTS session_meta (
|
|
427
|
-
session_id TEXT PRIMARY KEY,
|
|
428
|
-
project_dir TEXT NOT NULL,
|
|
429
|
-
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
430
|
-
last_event_at TEXT,
|
|
431
|
-
event_count INTEGER NOT NULL DEFAULT 0,
|
|
432
|
-
compact_count INTEGER NOT NULL DEFAULT 0
|
|
433
|
-
);
|
|
434
|
-
|
|
435
|
-
CREATE TABLE IF NOT EXISTS session_resume (
|
|
436
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
437
|
-
session_id TEXT NOT NULL UNIQUE,
|
|
438
|
-
snapshot TEXT NOT NULL,
|
|
439
|
-
event_count INTEGER NOT NULL,
|
|
440
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
441
|
-
consumed INTEGER NOT NULL DEFAULT 0
|
|
442
|
-
);
|
|
443
|
-
|
|
444
|
-
CREATE TABLE IF NOT EXISTS tool_calls (
|
|
445
|
-
session_id TEXT NOT NULL,
|
|
446
|
-
tool TEXT NOT NULL,
|
|
447
|
-
calls INTEGER NOT NULL DEFAULT 0,
|
|
448
|
-
bytes_returned INTEGER NOT NULL DEFAULT 0,
|
|
449
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
450
|
-
PRIMARY KEY (session_id, tool)
|
|
451
|
-
);
|
|
452
|
-
|
|
453
|
-
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
|
|
454
|
-
`);try{let e=this.db.pragma("table_xinfo(session_events)"),r=new Set(e.map(n=>n.name));r.has("project_dir")||this.db.exec("ALTER TABLE session_events ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''"),r.has("attribution_source")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_source TEXT NOT NULL DEFAULT 'unknown'"),r.has("attribution_confidence")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_confidence REAL NOT NULL DEFAULT 0"),r.has("bytes_avoided")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_avoided INTEGER NOT NULL DEFAULT 0"),r.has("bytes_returned")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_returned INTEGER NOT NULL DEFAULT 0"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)")}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(q.insertEvent,`INSERT INTO session_events (
|
|
455
|
-
session_id, type, category, priority, data,
|
|
456
|
-
project_dir, attribution_source, attribution_confidence,
|
|
457
|
-
bytes_avoided, bytes_returned,
|
|
458
|
-
source_hook, data_hash
|
|
459
|
-
)
|
|
460
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(q.getEvents,`SELECT id, session_id, type, category, priority, data,
|
|
461
|
-
project_dir, attribution_source, attribution_confidence,
|
|
462
|
-
bytes_avoided, bytes_returned,
|
|
463
|
-
source_hook, created_at, data_hash
|
|
464
|
-
FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(q.getEventsByType,`SELECT id, session_id, type, category, priority, data,
|
|
465
|
-
project_dir, attribution_source, attribution_confidence,
|
|
466
|
-
bytes_avoided, bytes_returned,
|
|
467
|
-
source_hook, created_at, data_hash
|
|
468
|
-
FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(q.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
|
|
469
|
-
project_dir, attribution_source, attribution_confidence,
|
|
470
|
-
bytes_avoided, bytes_returned,
|
|
471
|
-
source_hook, created_at, data_hash
|
|
472
|
-
FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(q.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
|
|
473
|
-
project_dir, attribution_source, attribution_confidence,
|
|
474
|
-
bytes_avoided, bytes_returned,
|
|
475
|
-
source_hook, created_at, data_hash
|
|
476
|
-
FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(q.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(q.getLatestAttributedProject,`SELECT project_dir
|
|
477
|
-
FROM session_events
|
|
478
|
-
WHERE session_id = ? AND project_dir != ''
|
|
479
|
-
ORDER BY id DESC
|
|
480
|
-
LIMIT 1`),e(q.checkDuplicate,`SELECT 1 FROM (
|
|
481
|
-
SELECT type, data_hash FROM session_events
|
|
482
|
-
WHERE session_id = ? ORDER BY id DESC LIMIT ?
|
|
483
|
-
) AS recent
|
|
484
|
-
WHERE recent.type = ? AND recent.data_hash = ?
|
|
485
|
-
LIMIT 1`),e(q.evictLowestPriority,`DELETE FROM session_events WHERE id = (
|
|
486
|
-
SELECT id FROM session_events WHERE session_id = ?
|
|
487
|
-
ORDER BY priority ASC, id ASC LIMIT 1
|
|
488
|
-
)`),e(q.updateMetaLastEvent,`UPDATE session_meta
|
|
489
|
-
SET last_event_at = datetime('now'), event_count = event_count + 1
|
|
490
|
-
WHERE session_id = ?`),e(q.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(q.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
|
|
491
|
-
FROM session_meta WHERE session_id = ?`),e(q.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(q.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
|
|
492
|
-
VALUES (?, ?, ?)
|
|
493
|
-
ON CONFLICT(session_id) DO UPDATE SET
|
|
494
|
-
snapshot = excluded.snapshot,
|
|
495
|
-
event_count = excluded.event_count,
|
|
496
|
-
created_at = datetime('now'),
|
|
497
|
-
consumed = 0`),e(q.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(q.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(q.claimLatestUnconsumedResume,`UPDATE session_resume
|
|
498
|
-
SET consumed = 1
|
|
499
|
-
WHERE id = (
|
|
500
|
-
SELECT id FROM session_resume
|
|
501
|
-
WHERE consumed = 0
|
|
502
|
-
AND session_id != ?
|
|
503
|
-
ORDER BY created_at DESC, id DESC
|
|
504
|
-
LIMIT 1
|
|
505
|
-
)
|
|
506
|
-
RETURNING session_id, snapshot`),e(q.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(q.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(q.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(q.searchEvents,`SELECT id, session_id, category, type, data, created_at
|
|
507
|
-
FROM session_events
|
|
508
|
-
WHERE (project_dir = ? OR project_dir = '')
|
|
509
|
-
AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
|
|
510
|
-
AND (? IS NULL OR category = ?)
|
|
511
|
-
ORDER BY id ASC
|
|
512
|
-
LIMIT ?`),e(q.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(q.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
|
|
513
|
-
VALUES (?, ?, 1, ?)
|
|
514
|
-
ON CONFLICT(session_id, tool) DO UPDATE SET
|
|
515
|
-
calls = calls + 1,
|
|
516
|
-
bytes_returned = bytes_returned + excluded.bytes_returned,
|
|
517
|
-
updated_at = datetime('now')`),e(q.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
|
|
518
|
-
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
519
|
-
FROM tool_calls WHERE session_id = ?`),e(q.getToolCallByTool,`SELECT tool, calls, bytes_returned
|
|
520
|
-
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(q.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
521
|
-
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
522
|
-
FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=ha("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(s?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(s?.source??r.attribution_source??"unknown"),u=Number(s?.confidence??r.attribution_confidence??0),d=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,l=al(o?.bytesAvoided),m=al(o?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(q.checkDuplicate).get(e,v$,r.type,i))return;this.stmt(q.getEventCount).get(e).cnt>=_$&&this.stmt(q.evictLowestPriority).run(e),this.stmt(q.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",s,o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,s?.[0],o?.[0]);return}let i=r.map((c,u)=>{let d=ha("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],m=String(l?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=o?.[u],y=al(g?.bytesAvoided),v=al(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:f,attributionConfidence:h,bytesAvoided:y,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(q.getEventCount).get(e).cnt;for(let u of i)this.stmt(q.checkDuplicate).get(e,v$,u.event.type,u.dataHash)||(c>=_$?this.stmt(q.evictLowestPriority).run(e):c++,this.stmt(q.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(q.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(q.getEventsByType).all(e,s,n):o!==void 0?this.stmt(q.getEventsByPriority).all(e,o,n):this.stmt(q.getEvents).all(e,n)}getEventCount(e){return this.stmt(q.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(q.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(q.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(q.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(q.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(q.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(q.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(q.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(q.getResume).get(e)??null}markResumeConsumed(e){this.stmt(q.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(q.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(q.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(q.getToolCallTotals).get(e),n=this.stmt(q.getToolCallByTool).all(e),s={};for(let o of n)s[o.tool]={calls:o.calls,bytesReturned:o.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:s}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(q.deleteEvents).run(e),this.stmt(q.deleteResume).run(e),this.stmt(q.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(q.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.length}}});import{existsSync as Fy,unlinkSync as _2}from"node:fs";import{join as va}from"node:path";function Uy(t,e){try{return _2(t),e.push(t),!0}catch{return!1}}function dl(t,e){let r=!1;for(let n of v2)Uy(`${t}${n}`,e)&&n===""&&(r=!0);return r}function S$(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,contentHash:i,sessionId:a,scope:c}=t,u=[],d=[],l=c??(a?"session":"project");if(l==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(l==="session"&&a){let _=ll(e),b=Yr(e),S=Jr(e),T=b===S?[b]:[b,S],$=!1;for(let P of T){let C=va(r,`${P}${_}.db`);if(!Fy(C))continue;let L=null;try{L=new _r({dbPath:C});let X=L.getEvents(a).length;L.deleteSession(a),X>0&&($=!0)}catch{}finally{try{L?.close()}catch{}}}$&&u.push(`session rows for ${a}`);let R=[];if(n&&Fy(n)&&R.push(n),s){let P=Yr(e),C=Jr(e),L=P===C?[P]:[P,C];for(let X of L){let fe=va(s,`${X}.db`);Fy(fe)&&!R.includes(fe)&&R.push(fe)}}let N=!1;for(let P of R)try{let C=st(),L=new C(P,{timeout:3e4});try{let X=L.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;L.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),L.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),X>0&&(N=!0)}finally{try{L.close()}catch{}}}catch{}return N&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let m=!1;if(n&&dl(n,d)&&(m=!0),s){let _=Yr(e),b=Jr(e),S=_===b?[_]:[_,b];for(let T of S){let $=va(s,`${T}.db`);dl($,d)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=va(o,`${i}.db`);dl(_,d)}let f=ll(e),p=Yr(e),h=Jr(e),g=p===h?[p]:[p,h],y=!1,v=!1;for(let _ of g){let b=va(r,`${_}${f}`);dl(`${b}.db`,d)&&(y=!0),Uy(`${b}-events.md`,d)&&(v=!0),Uy(`${b}.cleanup`,d)}return y&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var v2,k$=x(()=>{"use strict";On();_a();v2=["","-wal","-shm"]});import{existsSync as b2}from"node:fs";function Hy(t,e){try{if(!b2(t))return;let r=new _r({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function w$(t){Hy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function E$(t){Hy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function $$(t){Hy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var T$=x(()=>{"use strict";_a()});import{existsSync as P$}from"node:fs";function R$(t,e,r){try{if(!P$(t))return;let n=new _r({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function C$(t){try{if(!P$(t))return null;let e=new _r({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),s={},o={};for(let[a,c]of Object.entries(n.byTool))s[a]=c.calls,o[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(s).length===0&&Object.keys(o).length===0?{calls:s,bytesReturned:o,sessionStart:i}:{calls:s,bytesReturned:o,sessionStart:i}}finally{e.close()}}catch{return null}}var O$=x(()=>{"use strict";_a()});import{existsSync as Zy,readFileSync as x2,readdirSync as S2,statSync as k2}from"node:fs";import{join as ba,isAbsolute as w2}from"node:path";function N$(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?A$(r,a):null)??n??Be(),d=s?.getMemoryDir(),l=d?A$(r,d):ba(u,"memory"),m=[];if(r)for(let f of i){let p=ba(r,f);Zy(p)&&m.push({path:p,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let p=ba(u,f);Zy(p)&&m.push({path:p,label:`user/${f}`})}if(l&&Zy(l))try{let f=S2(l).filter(p=>p.endsWith(".md"));for(let p of f)m.push({path:ba(l,p),label:`memory/${p}`})}catch(f){I$&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
|
|
523
|
-
`)}for(let f of m){if(o.length>=e)break;try{let p;try{if(p=k2(f.path),p.size>1e6)continue}catch{continue}let h=x2(f.path,"utf-8"),g=h.toLowerCase();for(let y of t){if(o.length>=e)break;let _=y.toLowerCase().split(/\s+/).filter(S=>S.length>=3);if(_.some(S=>{try{return new RegExp(`\\b${S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(h)}catch{return g.includes(S)}})){let S=_.reduce((C,L)=>{let X=g.indexOf(L);return X>=0&&(C<0||X<C)?X:C},-1),T=Math.max(0,S-200),$=Math.min(h.length,S+500),R=h.lastIndexOf(`
|
|
524
|
-
|
|
525
|
-
`,T),N=h.indexOf(`
|
|
526
|
-
|
|
527
|
-
`,$);R>=0&&(T=R+2),N>=0&&($=N);let P=h.slice(T,$).trim();o.push({title:`[auto-memory] ${f.label}`,content:P,source:f.label,origin:"auto-memory",timestamp:p.mtime.toISOString()});break}}}catch(p){I$&&process.stderr.write(`[ctx] auto-memory file read failed: ${p}
|
|
528
|
-
`)}}return o.slice(0,e)}function A$(t,e){return e?w2(e)||!t?e:ba(t,e):t??""}var I$,D$=x(()=>{"use strict";an();I$=process.env.DEBUG?.includes("context-mode")});function M$(t){let{query:e,limit:r,store:n,sort:s="relevance",source:o,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],m=new Date().toISOString();try{let f=n.searchWithFallback(e,r,o,i);l.push(...f.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(f){By&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
|
|
529
|
-
`)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){By&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
|
|
530
|
-
`)}try{let f=N$([e],r,c,u,d);l.push(...f)}catch(f){By&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
|
|
531
|
-
`)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var By,j$=x(()=>{"use strict";D$();By=process.env.DEBUG?.includes("context-mode")});import*as It from"node:fs";import*as Vy from"node:path";function qy(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function T2(t){if(!It.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of It.readdirSync(t.projectsRoot)){let s=Vy.join(t.projectsRoot,n),o;try{o=It.statSync(s)}catch{continue}if(!o.isDirectory())continue;let i;try{i=It.readdirSync(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=Vy.join(s,a);try{let u=It.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=It.openSync(e,"r");try{let s=Buffer.alloc(8192),o=It.readSync(n,s,0,s.length,0),i=s.subarray(0,o).toString("utf-8");for(let a of i.split(`
|
|
532
|
-
`).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{It.closeSync(n)}}catch{}}function z$(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s,transcriptMaxAgeMs:o,nowMs:i,strictPlatform:a}=t,c=a?[...Kd(a),...E2]:$2;for(let u of c){let d=e[u];if(d&&!qy(d))return d}if(s){let u=T2({projectsRoot:s,maxAgeMs:o,nowMs:i});if(u&&!qy(u))return u}return n&&!qy(n)?n:r}var E2,$2,L$=x(()=>{"use strict";un();E2=["CONTEXT_MODE_PROJECT_DIR"],$2=["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 P2}from"node:child_process";import{existsSync as Xr,readdirSync as No,statSync as R2}from"node:fs";import{homedir as gl}from"node:os";import{join as jt,sep as C2}from"node:path";function W$(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]??0)>(n[s]??0))return!0;if((r[s]??0)<(n[s]??0))return!1}return!1}function I2(t){let e=t?.home??gl();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,s])=>{let o=jt(e,...s,"context-mode");return{name:n,sessionsDir:jt(o,"sessions"),contentDir:jt(o,"content")}})}function A2(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function xa(t){let e=Be(),r=t?.sessionsDir??jt(e,"context-mode","sessions"),n=t?.memoryRoot??jt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Xr(r)){let f=[];try{f=No(r).filter(p=>p.endsWith(".db"))}catch{}if(f.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():st()}catch{}if(p)for(let h of f){let g=jt(r,h);try{let y=new p(g,{readonly:!0});try{let v=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=v?.cnt??0,o+=_?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let S of b)S.category&&(u[S.category]=(u[S.category]??0)+(S.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let S=b.t.endsWith("Z")?b.t:b.t+"Z",T=Date.parse(S);Number.isFinite(T)&&T<a&&(a=T)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let S of b)S.p&&c.add(S.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(Xr(n)){let f=[];try{f=No(n).filter(p=>{try{return R2(jt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of f){let h=jt(n,p,"memory");if(!Xr(h))continue;let g=[];try{g=No(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let v=A2(y);m[v]=(m[v]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function G$(t){let e=t.sessionsDir??jt(gl(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Xr(e))return n;let s=[];try{s=No(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():st()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,f=0,p=new Map,h=_=>Math.floor(_/864e5)*864e5;for(let _ of s){let b=jt(e,_),S=!1;try{let T=new o(b,{readonly:!0});try{let $=T.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let N of $)N.category&&(i[N.category]=(i[N.category]??0)+(N.cnt??0),a+=N.cnt??0,S=!0);let R=T.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(R?.mn){let N=Date.parse(R.mn+(R.mn.endsWith("Z")?"":"Z"));Number.isFinite(N)&&N<l&&(l=N)}if(R?.mx){let N=Date.parse(R.mx+(R.mx.endsWith("Z")?"":"Z"));Number.isFinite(N)&&N>m&&(m=N)}try{let N=T.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let P of N){if(!P.sec)continue;let C=parseInt(P.sec,10)*1e3;if(!Number.isFinite(C))continue;let L=h(C),X=p.get(L)??{count:0,rescueBytes:0};X.count+=P.cnt??0,p.set(L,X)}}catch{}try{let N=T.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(N?.bytes&&(u+=N.bytes),N?.n&&(d+=N.n),N?.lastSec){let P=parseInt(N.lastSec,10)*1e3;if(Number.isFinite(P)&&P>f&&(f=P),Number.isFinite(P)&&(N?.bytes??0)>0){let C=h(P),L=p.get(C)??{count:0,rescueBytes:0};L.rescueBytes=Math.max(L.rescueBytes,N.bytes),p.set(C,L)}}}catch{}}finally{T.close()}}catch{}S&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,b])=>({category:_,count:b,label:ml[_]||_})).sort((_,b)=>b.count-_.count),v=[...p.entries()].sort((_,b)=>_[0]-b[0]).map(([_,b])=>({ms:_,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:y,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:f>0?f:void 0,byDay:v}}function N2(t,e,r){if(!t||!e||!Xr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():st()}catch{return 0}if(!n)return 0;try{let s=new n(e,{readonly:!0});try{let o=s.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
533
|
-
FROM chunks WHERE session_id = ?`).get(t);return Number(o?.bytes??0)}finally{s.close()}}catch{return 0}}function K$(t,e){if(!t||!Xr(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():st()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let s=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
534
|
-
FROM chunks`).get();return Number(s?.bytes??0)}finally{n.close()}}catch{return 0}}function Wy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??jt(gl(),".claude","context-mode","sessions");if(!Xr(r))return e;let n=[];try{n=No(r).filter(l=>!(!l.endsWith(".db")||t.worktreeHash&&!l.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():st()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let l of n){let m=jt(r,l);try{let f=new s(m,{readonly:!0});try{if(t.sessionId){let p=f.prepare(`SELECT
|
|
524
|
+
${o}`}}var U$=x(()=>{"use strict"});import{execFileSync as Q2}from"node:child_process";function eU(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=Q2("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function tU(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??eU,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}function nU(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function H$(t){let e=t.checkIntervalMs??nU(),r=t.isParentAlive??rU,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var rU,Z$=x(()=>{"use strict";rU=tU()});function B$(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}var q$=x(()=>{"use strict"});import{existsSync as Yy,unlinkSync as oU}from"node:fs";import{join as Pa}from"node:path";function Xy(t,e){try{return oU(t),e.push(t),!0}catch{return!1}}function xl(t,e){let r=!1;for(let n of sU)Xy(`${t}${n}`,e)&&n===""&&(r=!0);return r}function V$(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],d=[],l=c??(a?"session":"project");if(l==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(l==="session"&&a){let _=cc(e),b=ht(e),S=Ur(e),P=b===S?[b]:[b,S],$=!1;for(let z of P){let w=Pa(r,`${z}${_}.db`);if(!Yy(w))continue;let H=null;try{H=new cr({dbPath:w});let F=H.getEvents(a).length;H.deleteSession(a),F>0&&($=!0)}catch{}finally{try{H?.close()}catch{}}}$&&u.push(`session rows for ${a}`);let R=[];if(n&&Yy(n)&&R.push(n),o){let z=ht(e),w=Ur(e),H=z===w?[z]:[z,w];for(let F of H){let ae=Pa(o,`${F}.db`);Yy(ae)&&!R.includes(ae)&&R.push(ae)}}let A=!1;for(let z of R)try{let w=Xe(),H=new w(z,{timeout:3e4});try{let F=H.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;H.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),H.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(A=!0)}finally{try{H.close()}catch{}}}catch{}return A&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let m=!1;if(n&&xl(n,d)&&(m=!0),o){let _=ht(e),b=Ur(e),S=_===b?[_]:[_,b];for(let P of S){let $=Pa(o,`${P}.db`);xl($,d)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=Pa(s,`${i}.db`);xl(_,d)}let f=cc(e),p=ht(e),h=Ur(e),g=p===h?[p]:[p,h],y=!1,v=!1;for(let _ of g){let b=Pa(r,`${_}${f}`);xl(`${b}.db`,d)&&(y=!0),Xy(`${b}-events.md`,d)&&(v=!0),Xy(`${b}.cleanup`,d)}return y&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var sU,W$=x(()=>{"use strict";ln();Tr();sU=["","-wal","-shm"]});import{existsSync as iU}from"node:fs";function Qy(t,e){try{if(!iU(t))return;let r=new cr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function G$(t){Qy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function K$(t){Qy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function J$(t){Qy(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}var Y$=x(()=>{"use strict";Tr()});import{existsSync as X$}from"node:fs";function Q$(t,e,r){try{if(!X$(t))return;let n=new cr({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function eT(t){try{if(!X$(t))return null;let e=new cr({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var tT=x(()=>{"use strict";Tr()});import{existsSync as e_,readFileSync as aU,readdirSync as cU,statSync as uU}from"node:fs";import{join as Zs,isAbsolute as lU}from"node:path";function oT(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?nT(r,a):null)??n??qe(),d=o?.getMemoryDir(r),l=Zs(u,"memory"),m=r?Zs(l,ht(r)):l,f=d?nT(r,d):m,p=[];if(r)for(let h of i){let g=Zs(r,h);e_(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let g=Zs(u,h);e_(g)&&p.push({path:g,label:`user/${h}`})}if(f&&e_(f))try{let h=cU(f).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:Zs(f,g),label:`memory/${g}`})}catch(h){rT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
|
|
525
|
+
`)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=uU(h.path),g.size>1e6)continue}catch{continue}let y=aU(h.path,"utf-8"),v=y.toLowerCase();for(let _ of t){if(s.length>=e)break;let S=_.toLowerCase().split(/\s+/).filter($=>$.length>=3);if(S.some($=>{try{return new RegExp(`\\b${$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return v.includes($)}})){let $=S.reduce((F,ae)=>{let Ze=v.indexOf(ae);return Ze>=0&&(F<0||Ze<F)?Ze:F},-1),R=Math.max(0,$-200),A=Math.min(y.length,$+500),z=y.lastIndexOf(`
|
|
526
|
+
|
|
527
|
+
`,R),w=y.indexOf(`
|
|
528
|
+
|
|
529
|
+
`,A);z>=0&&(R=z+2),w>=0&&(A=w);let H=y.slice(R,A).trim();s.push({title:`[auto-memory] ${h.label}`,content:H,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){rT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
|
|
530
|
+
`)}}return s.slice(0,e)}function nT(t,e){return e?lU(e)||!t?e:Zs(t,e):t??""}var rT,sT=x(()=>{"use strict";hn();Tr();rT=process.env.DEBUG?.includes("context-mode")});function iT(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:d}=t,l=[],m=new Date().toISOString();try{let f=n.searchWithFallback(e,r,s,i);l.push(...f.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(f){t_&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
|
|
531
|
+
`)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){t_&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
|
|
532
|
+
`)}try{let f=oT([e],r,c,u,d);l.push(...f)}catch(f){t_&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
|
|
533
|
+
`)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var t_,aT=x(()=>{"use strict";sT();t_=process.env.DEBUG?.includes("context-mode")});import*as Nt from"node:fs";import*as n_ from"node:path";function r_(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function mU(t){if(!Nt.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Nt.readdirSync(t.projectsRoot)){let o=n_.join(t.projectsRoot,n),s;try{s=Nt.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Nt.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=n_.join(o,a);try{let u=Nt.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=Nt.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Nt.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
|
|
534
|
+
`).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{Nt.closeSync(n)}}catch{}}function cT(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a}=t,c=a?[...lp(a),...dU]:pU;for(let u of c){let d=e[u];if(d&&!r_(d))return d}if(o){let u=mU({projectsRoot:o,maxAgeMs:s,nowMs:i});if(u&&!r_(u))return u}return n&&!r_(n)?n:r}var dU,pU,uT=x(()=>{"use strict";yn();dU=["CONTEXT_MODE_PROJECT_DIR"],pU=["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 fU}from"node:child_process";import{existsSync as tn,readdirSync as Bs,statSync as hU}from"node:fs";import{homedir as $l}from"node:os";import{join as Lt,sep as gU}from"node:path";function yT(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function _U(t){let e=t?.home??$l();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Lt(e,...o,"context-mode");return{name:n,sessionsDir:Lt(s,"sessions"),contentDir:Lt(s,"content")}})}function vU(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Ra(t){let e=qe(),r=t?.sessionsDir??Lt(e,"context-mode","sessions"),n=t?.memoryRoot??Lt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(tn(r)){let f=[];try{f=Bs(r).filter(p=>p.endsWith(".db"))}catch{}if(f.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Xe()}catch{}if(p)for(let h of f){let g=Lt(r,h);try{let y=new p(g,{readonly:!0});try{let v=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=v?.cnt??0,s+=_?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let S of b)S.category&&(u[S.category]=(u[S.category]??0)+(S.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let S=b.t.endsWith("Z")?b.t:b.t+"Z",P=Date.parse(S);Number.isFinite(P)&&P<a&&(a=P)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let S of b)S.p&&c.add(S.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(tn(n)){let f=[];try{f=Bs(n).filter(p=>{try{return hU(Lt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of f){let h=Lt(n,p,"memory");if(!tn(h))continue;let g=[];try{g=Bs(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let v=vU(y);m[v]=(m[v]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function _T(t){let e=t.sessionsDir??Lt($l(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!tn(e))return n;let o=[];try{o=Bs(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():Xe()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,f=0,p=new Map,h=_=>Math.floor(_/864e5)*864e5;for(let _ of o){let b=Lt(e,_),S=!1;try{let P=new s(b,{readonly:!0});try{let $=P.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let A of $)A.category&&(i[A.category]=(i[A.category]??0)+(A.cnt??0),a+=A.cnt??0,S=!0);let R=P.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(R?.mn){let A=Date.parse(R.mn+(R.mn.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A<l&&(l=A)}if(R?.mx){let A=Date.parse(R.mx+(R.mx.endsWith("Z")?"":"Z"));Number.isFinite(A)&&A>m&&(m=A)}try{let A=P.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let z of A){if(!z.sec)continue;let w=parseInt(z.sec,10)*1e3;if(!Number.isFinite(w))continue;let H=h(w),F=p.get(H)??{count:0,rescueBytes:0};F.count+=z.cnt??0,p.set(H,F)}}catch{}try{let A=P.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(A?.bytes&&(u+=A.bytes),A?.n&&(d+=A.n),A?.lastSec){let z=parseInt(A.lastSec,10)*1e3;if(Number.isFinite(z)&&z>f&&(f=z),Number.isFinite(z)&&(A?.bytes??0)>0){let w=h(z),H=p.get(w)??{count:0,rescueBytes:0};H.rescueBytes=Math.max(H.rescueBytes,A.bytes),p.set(w,H)}}}catch{}}finally{P.close()}}catch{}S&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,b])=>({category:_,count:b,label:kl[_]||_})).sort((_,b)=>b.count-_.count),v=[...p.entries()].sort((_,b)=>_[0]-b[0]).map(([_,b])=>({ms:_,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:y,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:f>0?f:void 0,byDay:v}}function bU(t,e,r){if(!t||!e||!tn(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():Xe()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
535
|
+
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function vT(t,e){if(!t||!tn(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():Xe()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
|
|
536
|
+
FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Ca(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Lt($l(),".claude","context-mode","sessions");if(!tn(r))return e;let n=[];try{n=Bs(r).filter(l=>!(!l.endsWith(".db")||t.worktreeHash&&!l.startsWith(t.worktreeHash)))}catch{return e}if(n.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 l of n){let m=Lt(r,l);fv(m,o);try{let f=new o(m,{readonly:!0});try{if(t.sessionId){let p=f.prepare(`SELECT
|
|
535
537
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
536
538
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
537
539
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
538
|
-
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(
|
|
540
|
+
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}}else if(t.projectDir){let p=f.prepare(`SELECT
|
|
539
541
|
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
540
542
|
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
541
543
|
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
542
|
-
FROM session_events`).get();p&&(o+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{f.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=N2(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let d=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:d}}function M2(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!Xr(t.sessionsDir))return n;let s=[];try{s=No(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(s.length===0)return n;let o=null;try{o=e()}catch{return n}if(!o)return n;let i=new Set,a=new Set;for(let d of s){let l=jt(t.sessionsDir,d);try{let m=new o(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function yl(t){let e=I2({home:t?.home}),r=t?.loadDatabase??st,n={...D2,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!Xr(c.sessionsDir))continue;let u=M2(c,r,n);s.push(u),o+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:o,totalSessions:i,totalBytes:a,perAdapter:s}}function fl(t){return j2[t]??t}function ot(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function z2(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function pl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function L2(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!pl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=P2("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!pl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!pl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return pl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function F$(t){let e=gl();return e?t===e?"~":t.startsWith(e+C2)?"~"+t.slice(e.length):t:t}function F2(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${ot(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function U2(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*q$,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*q$,v=Math.round((r?.rescueBytes??0)/4),_=y+v,b=s?.lifetime?.totalSavedTokens??0,S=Math.max(_,b),T=s?.lifetime?.bytesReturned??0,$=s?.lifetime?.bytesAvoided??0,R=T+$>0?Math.max(1,Math.floor(T/4)):Math.max(1,Math.round(S*.02)),N=n?.totalBytes&&n.totalBytes>0?n.totalBytes:S*4,P=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,C=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`,L=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,X=L>0?Math.max(1,Math.round((c-L)/864e5)):0,fe=n?.totalSessions??r?.totalSessions??1,ct=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,mt;if(n&&ct>=2)mt=`across ${ct} AI tools`;else if(n&&ct===1){let Ze=n.perAdapter.find(or=>or.isReal);mt=`in ${Ze?fl(Ze.name):"Claude Code"}`}else mt="in Claude Code";X>0?l.push(` Across ${X} days you ran ${vr(fe)} conversations ${mt}.`):l.push(` You ran ${vr(fe)} conversations ${mt}.`);let sr=X>0?N/X:0;l.push(` context-mode kept ${ot(N)} out of your context window \u2014 about ${ot(sr)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Dn=e.firstEventMs&&e.firstEventMs>0?U$(e.firstEventMs,i,a):"";if(Dn?l.push(` This conversation started ${Dn} in ${F$(o)}.`):l.push(` This conversation lives in ${F$(o)}.`),l.push(` ${C}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?U$(e.lastRescueMs,i,a):"",or=Math.round(e.snapshotBytes/1024);Ze?l.push(` On ${Ze}, /compact fired \u2014 ${or} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${or} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let Uo=s?.conversation,Ca=Uo?.bytesAvoided??0,Ml=Uo?.bytesReturned??0,jl=Uo?.eventDataBytes??0;if(Ca+Ml+jl>0){let Ze=Ca+Ml+jl,or=Math.max(1,Ml+jl),ir=Math.max(1,Math.floor(Ze/4)),Mr=Math.max(1,Math.floor(or/4)),zl=In(ir,ir,32),qT=In(Mr,ir,32),VT=(1-Mr/ir)*100,WT=Math.max(1,Math.round(ir/Mr));l.push(` Without context-mode ${ot(Ze).padStart(8)} ${zl} ${vr(ir).padStart(7)} tokens`),l.push(` With context-mode ${ot(or).padStart(8)} ${qT} ${vr(Mr).padStart(7)} tokens`),l.push(` ${VT.toFixed(0)}% kept out of context \xB7 your AI ran ${WT}\xD7 longer before /compact fired`),l.push("")}if(e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${ot(P)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),l.push(""),l.push(...Z2(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let UT=e.byCategory.reduce((Ze,or)=>Ze+or.count,0).toLocaleString(i);l.push(` ${UT} things \u2014 files, errors, decisions, agent runs:`),l.push("");let HT=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)l.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${In(Ze.count,HT,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let d_=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",p_=L>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(L)):"",m_=r?.distinctProjects??0,ZT=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${ot(P)} kept out \xB7 ${e.events.toLocaleString(i)} captures${d_?` \xB7 started ${d_}`:""}.`),l.push(` All your work: ${ot(N)} kept out \xB7 ${ZT.toLocaleString(i)} captures across ${m_} project${m_===1?"":"s"}${p_?` \xB7 since ${p_}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...F2(N,S,X)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Ze=Object.entries(r.autoMemoryByPrefix).sort((ir,Mr)=>Mr[1]-ir[1]),or=Ze.length>0?Ze[0][1]:1;for(let[ir,Mr]of Ze){let zl=J$[ir]??ir;l.push(` ${zl.padEnd(26)} ${String(Mr).padStart(2)} ${In(Mr,or,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let BT=u?`v${u}`:"context-mode";return l.push(` ${BT}`),u&&d&&d!=="unknown"&&W$(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),H2(l)}function H2(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function Z2(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let f=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function U$(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let s=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),o=l=>s.find(m=>m.type===l)?.value??"",i=o("day"),a=o("month"),c=o("year"),u=o("hour"),d=o("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function vr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function hl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*_l).toFixed(2)}`}function In(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function H$(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${vr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${vr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${vr(h)} sessions`,y=a*256+r;s.push(` ${vr(a)} events \xB7 ${g} \xB7 ~${hl(y)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:ml[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${In(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function Z$(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((s,o)=>o[1]-s[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[s,o]of r){let i=J$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${In(o,n,20)}`)}return e}function B$(t,e){let r=[],n=hl(t),s=(e?.totalEvents??0)*256+t,o=hl(s);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${o} lifetime`),r.push("\u2500".repeat(65)),r}function V$(t){if(!t)return[];let e=t.perAdapter.filter(s=>s.isReal),r=t.perAdapter.filter(s=>!s.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let s=16,o=10,i=10,a=16;n.push(` ${"Tool".padEnd(s)}${"Captures".padStart(o)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?vr(u.eventCount):"\u2014",m=ot(u.dataBytes),f=ot(d);n.push(` ${fl(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>fl(o.name)).join(", ");n.push(` Skipped (${r.length}): ${s}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function vl(t,e,r,n){let s=[],o=z2(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(T=>T.isReal).length??0;if(d&&l>0){let T=d.totalSessions||i?.totalSessions||0,$=i?.firstEventMs??0,R=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,N=R>0?`Across ${R} day${R===1?"":"s"} `:"",P=T>0?`you ran ${vr(T)} conversation${T===1?"":"s"} `:"you ran ",C;if(l>=2)C=`across ${l} AI tools`;else{let L=d.perAdapter.find(X=>X.isReal);C=`in ${L?fl(L.name):"Claude Code"}`}s.push(`${N}${P}${C}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let T=L2(),$=n?.cwd??process.cwd(),R=n?.now??Date.now(),N=n?.locale??T.locale,P=n?.tz??T.tz;return s.push(...U2({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:$,locale:N,tz:P,now:R,version:e,latestVersion:r})),s.join(`
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
`)
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
`)}function bT(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
|
|
544
|
+
FROM session_events
|
|
545
|
+
WHERE session_id IN (
|
|
546
|
+
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
547
|
+
)`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
|
|
548
|
+
FROM session_resume
|
|
549
|
+
WHERE session_id IN (
|
|
550
|
+
SELECT session_id FROM session_meta WHERE project_dir = ?
|
|
551
|
+
)`).get(t.projectDir);h?.bytes&&(c+=Number(h.bytes))}catch{}}else{let p=f.prepare(`SELECT
|
|
552
|
+
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
|
|
553
|
+
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
|
|
554
|
+
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
|
|
555
|
+
FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=f.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{f.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=bU(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let d=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:d}}function SU(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!tn(t.sessionsDir))return n;let o=[];try{o=Bs(t.sessionsDir).filter(d=>d.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let d of o){let l=Lt(t.sessionsDir,d);try{let m=new s(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Tl(t){let e=_U({home:t?.home}),r=t?.loadDatabase??Xe,n={...xU,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!tn(c.sessionsDir))continue;let u=SU(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}function wl(t){return kU[t]??t}function at(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function wU(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Sl(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function EU(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Sl(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=fU("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Sl(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Sl(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Sl(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function lT(t){let e=$l();return e?t===e?"~":t.startsWith(e+gU)?"~"+t.slice(e.length):t:t}function $U(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,o=(h,g=2)=>h.toFixed(g),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${at(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function TU(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*hT,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*hT,v=Math.round((r?.rescueBytes??0)/4),_=y+v,b=o?.lifetime?.totalSavedTokens??0,S=Math.max(_,b),P=o?.lifetime?.bytesReturned??0,$=o?.lifetime?.bytesAvoided??0,R=P+$>0?Math.max(1,Math.floor(P/4)):Math.max(1,Math.round(S*.02)),A=n?.totalBytes&&n.totalBytes>0?n.totalBytes:S*4,z=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,w=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`,H=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=H>0?Math.max(1,Math.round((c-H)/864e5)):0,ae=n?.totalSessions??r?.totalSessions??1,Ze=n?.perAdapter.filter(Be=>Be.isReal).length??0,mt;if(n&&Ze>=2)mt=`across ${Ze} AI tools`;else if(n&&Ze===1){let Be=n.perAdapter.find(sr=>sr.isReal);mt=`in ${Be?wl(Be.name):"Claude Code"}`}else mt="in Claude Code";F>0?l.push(` Across ${F} days you ran ${br(ae)} conversations ${mt}.`):l.push(` You ran ${br(ae)} conversations ${mt}.`);let or=F>0?A/F:0;l.push(` context-mode kept ${at(A)} out of your context window \u2014 about ${at(or)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Un=e.firstEventMs&&e.firstEventMs>0?dT(e.firstEventMs,i,a):"";if(Un?l.push(` This conversation started ${Un} in ${lT(s)}.`):l.push(` This conversation lives in ${lT(s)}.`),l.push(` ${w}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Be=e.lastRescueMs&&e.lastRescueMs>0?dT(e.lastRescueMs,i,a):"",sr=Math.round(e.snapshotBytes/1024);Be?l.push(` On ${Be}, /compact fired \u2014 ${sr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${sr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let La=o?.conversation,Fa=La?.bytesAvoided??0,Gl=La?.bytesReturned??0;if(Fa+Gl===0)l.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),l.push("");else{let Be=Fa+Gl,sr=Math.max(1,Gl),ir=Math.max(1,Math.floor(Be/4)),Fr=Math.max(1,Math.floor(sr/4)),Kl=zn(ir,ir,32),_P=zn(Fr,ir,32),vP=(1-Fr/ir)*100,bP=Math.max(1,Math.round(ir/Fr));l.push(` Without context-mode ${at(Be).padStart(8)} ${Kl} ${br(ir).padStart(7)} tokens`),l.push(` With context-mode ${at(sr).padStart(8)} ${_P} ${br(Fr).padStart(7)} tokens`),l.push(` ${vP.toFixed(0)}% kept out of context \xB7 your AI ran ${bP}\xD7 longer before /compact fired`),l.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;l.push(` How that ${at(z)} built up \u2014 ${Be} days, ${e.byDay.length} active:`),l.push(""),l.push(...RU(e.byDay,i,a))}l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),l.push("");let fP=e.byCategory.reduce((Be,sr)=>Be+sr.count,0).toLocaleString(i);l.push(` ${fP} things \u2014 files, errors, decisions, agent runs:`),l.push("");let hP=e.byCategory[0]?.count??1;for(let Be of e.byCategory)l.push(` ${Be.label.padEnd(26)} ${String(Be.count).padStart(5)} ${zn(Be.count,hP,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let b_=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",x_=H>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(H)):"",S_=r?.distinctProjects??0,gP=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${at(z)} kept out \xB7 ${e.events.toLocaleString(i)} captures${b_?` \xB7 started ${b_}`:""}.`),l.push(` All your work: ${at(A)} kept out \xB7 ${gP.toLocaleString(i)} captures across ${S_} project${S_===1?"":"s"}${x_?` \xB7 since ${x_}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...$U(A,S,F)),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),l.push(""),r&&r.autoMemoryCount>0){l.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let Be=Object.entries(r.autoMemoryByPrefix).sort((ir,Fr)=>Fr[1]-ir[1]),sr=Be.length>0?Be[0][1]:1;for(let[ir,Fr]of Be){let Kl=bT[ir]??ir;l.push(` ${Kl.padEnd(26)} ${String(Fr).padStart(2)} ${zn(Fr,sr,20)}`)}}else l.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");l.push(""),l.push(""),l.push(" Your AI talks less, remembers more, costs less."),l.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),l.push("");let yP=u?`v${u}`:"context-mode";return l.push(` ${yP}`),u&&d&&d!=="unknown"&&yT(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),PU(l)}function PU(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function RU(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let f=Math.round((m.ms-o.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(o.ms)} ${u.join("")} ${d(s.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function dT(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=l=>o.find(m=>m.type===l)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),d=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${d} (${r})`}function br(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function El(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Pl).toFixed(2)}`}function zn(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function pT(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(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 ${br(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${br(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${br(h)} sessions`,y=a*256+r;o.push(` ${br(a)} events \xB7 ${g} \xB7 ~${El(y)} saved lifetime`)}o.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:kl[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${zn(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function mT(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=bT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${zn(s,n,20)}`)}return e}function fT(t,e){let r=[],n=El(t),o=(e?.totalEvents??0)*256+t,s=El(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function gT(t){if(!t)return[];let e=t.perAdapter.filter(o=>o.isReal),r=t.perAdapter.filter(o=>!o.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,d)=>d.dataBytes+d.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let d=u.dataBytes+u.rescueBytes,l=u.eventCount>0?br(u.eventCount):"\u2014",m=at(u.dataBytes),f=at(d);n.push(` ${wl(u.name).padEnd(o)}${l.padStart(s)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>wl(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function Rl(t,e,r,n){let o=[],s=wU(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(P=>P.isReal).length??0;if(d&&l>0){let P=d.totalSessions||i?.totalSessions||0,$=i?.firstEventMs??0,R=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,A=R>0?`Across ${R} day${R===1?"":"s"} `:"",z=P>0?`you ran ${br(P)} conversation${P===1?"":"s"} `:"you ran ",w;if(l>=2)w=`across ${l} AI tools`;else{let H=d.perAdapter.find(F=>F.isReal);w=`in ${H?wl(H.name):"Claude Code"}`}o.push(`${A}${z}${w}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let P=EU(),$=n?.cwd??process.cwd(),R=n?.now??Date.now(),A=n?.locale??P.locale,z=n?.tz??P.tz;return o.push(...TU({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:$,locale:A,tz:z,now:R,version:e,latestVersion:r})),o.join(`
|
|
556
|
+
`)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,p=t.savings.total_calls,h=m+f,g=h>0?m/h*100:0,y=Math.round(m/4),v=f>0?Math.max(1,Math.round(h/Math.max(f,1))):0;if(m===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${at(f)} entered context | 0 tokens saved`),o.push(...pT(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),o.push(...gT(d)),o.push(...mT(i)),o.push(...fT(0,i)),o.push("");let P=e?`v${e}`:"context-mode";return o.push(P),e&&r&&r!=="unknown"&&yT(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
|
|
557
|
+
`)}o.push(`${br(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${El(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${zn(h,h)}| ${at(h)}`),o.push(`With context-mode |${zn(f,h)}| ${at(f)}`),o.push(""),v>=2?o.push(`${at(m)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):o.push(`${at(m)} kept out of your conversation. Never entered context.`),o.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${at(t.cache.bytes_saved)})`),o.push(_.join(" \xB7 "));let b=t.savings.by_tool.filter(P=>P.calls>0);if(b.length>=2){o.push("");let P=b.map($=>{let R=$.context_kb*1024,A=g<100?R/(1-g/100):R,z=Math.max(0,A-R);return{...$,returnedBytes:R,estimatedSaved:z}}).sort(($,R)=>R.estimatedSaved-$.estimatedSaved);for(let $ of P){let R=$.tool.length>22?$.tool.slice(0,19)+"...":$.tool;o.push(` ${R.padEnd(22)} ${String($.calls).padStart(4)} calls ${at($.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let P=a.filter($=>$.median_concurrency!=null&&($.max_concurrency??1)>1);if(P.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 $ of P){let R=$.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${R.padEnd(22)} ${$.calls} batches \xB7 ${$.median_concurrency} typical, ${$.max_concurrency} peak`)}}}o.push(...pT(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:y})),o.push(...gT(d)),o.push(...mT(i)),o.push(...fT(y,i)),o.push("");let S=e?`v${e}`:"context-mode";return o.push(S),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
|
|
558
|
+
`)}var kl,yU,qs,xU,bT,kU,Pl,hT,xT=x(()=>{"use strict";ln();Tr();hn();kl={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"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"},yU={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"},qs=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){let c=[...s.concurrencies].sort((d,l)=>d-l),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((w,H)=>w+H,0),s=Object.values(e.calls).reduce((w,H)=>w+H,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,d=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),l=Array.from(d).sort().map(w=>({tool:w,calls:e.calls[w]||0,context_kb:Math.round((e.bytesReturned[w]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[w]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let w=a+e.cacheBytesSaved,H=w/Math.max(o,1),F=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:F,total_with_cache:w,total_savings_ratio:H}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),b=_?!_.consumed:!1,S=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),P=new Map;for(let w of S){P.has(w.category)||P.set(w.category,new Set);let H=P.get(w.category);if(H.size<5){let F=w.data;w.category==="file"?F=w.data.split("/").pop()||w.data:(w.category==="prompt"||w.category==="user-prompt")&&(F=F.length>50?F.slice(0,47)+"...":F),F.length>40&&(F=F.slice(0,37)+"..."),H.add(F)}}let $=g.map(w=>({category:w.category,count:w.cnt,label:kl[w.category]||w.category,preview:P.get(w.category)?Array.from(P.get(w.category)).join(", "):"",why:yU[w.category]||"Survives context resets"})),R=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),z=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(w=>w.cnt>0).map(w=>({category:w.category,count:w.cnt,label:kl[w.category]||w.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:l,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:$,compact_count:v,resume_ready:b},projectMemory:{total_events:R.cnt,session_count:R.sessions,by_category:z}}}};xU={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};bT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},kU={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};Pl=15/1e6;hT=256});var XT={};Le(XT,{REGISTERED_CTX_TOOLS:()=>MT,__resetSuppressionDiagnosticForTests:()=>qU,browserOpenArgv:()=>YT,buildBatchNodeOptionsPrefix:()=>WT,buildFetchCode:()=>JT,classifyIp:()=>Na,currentAttribution:()=>Do,emitSuppressionDiagnostic:()=>LT,extractSnippet:()=>f_,formatBatchQueryResults:()=>VT,killProcessOnPort:()=>g_,openBrowserSync:()=>u_,positionsFromHighlight:()=>qT,registerEmptyToolsListHandler:()=>FT,resolveSessionIdFromSessionDB:()=>UT,runBatchCommands:()=>GT,server:()=>ze,shouldSuppressMcpToolsForNativePluginHost:()=>jT,withProjectDirOverride:()=>GU});import{createRequire as AT}from"node:module";import{existsSync as Ce,unlinkSync as Gs,readdirSync as CU,readFileSync as Ll,writeFileSync as l_,renameSync as OU,rmSync as Nl,mkdirSync as NT,cpSync as IU,statSync as ST,symlinkSync as AU,lstatSync as NU}from"node:fs";import{execSync as kT,spawnSync as DT}from"node:child_process";import{join as je,dirname as Sr,resolve as Ge,sep as DU,isAbsolute as MU}from"node:path";import{fileURLToPath as jU}from"node:url";import{homedir as Ia,tmpdir as d_,cpus as zU}from"node:os";import{request as LU}from"node:https";import{AsyncLocalStorage as FU}from"node:async_hooks";function jT(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??wt().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??HU(r);return ZU(n)&&BU(n)}function UU(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
|
|
559
|
+
`;)s++;s<t.length&&(e+=`
|
|
560
|
+
`);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function HU(t){let e=t==="kilo"?"kilo":"opencode",r=[Ge(`${e}.json`),Ge(`${e}.jsonc`),Ge(`.${e}`,`${e}.json`),Ge(`.${e}`,`${e}.jsonc`),je(Ia(),".config",e,`${e}.json`),je(Ia(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!Ce(n))continue;return JSON.parse(UU(Ll(n,"utf8")))}catch{}return null}function ZU(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function BU(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}function LT(t={}){if(a_)return;a_=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
|
|
561
|
+
`)}function qU(){a_=!1}function FT(t=ze){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(xs,async()=>({tools:[]}))}function WU(t,e){return async r=>{try{return await e(r)}catch(n){let o=QU(n);if(o)try{return G(t,o)}catch(s){if(s instanceof ar)return o;throw s}throw n}}}async function GU(t,e){let r=typeof t=="string"?{projectDir:t}:t;return p_.run(r,e)}function Do(){let t=p_.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??UT();if(e)return{sessionId:e}}function UT(t){let e=Date.now();if(!t?.bypassCache&&Cl&&e-Cl.checkedAt<2e3)return Cl.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??Ye(),o=ui({projectDir:r,sessionsDir:n});if(!Ce(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&&(Cl={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function KU(t){try{let e=Ye();if(!Ce(e))return;let r=CU(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=je(e,n);try{t.index({path:o,source:"session-events",attribution:Do()}),Gs(o)}catch{}}}catch{}}async function JU(){if(Ln)return Ln;try{let{getAdapter:t}=await Promise.resolve().then(()=>(yn(),vc)),e=wt();return await t(e.platform)}catch{return null}}function Vs(){if(Ln)return Ln.getSessionDir();try{let t=wt(),e=hi(t.platform);if(e)return _d({configDir:je(...e),configDirEnv:YU(e)})}catch{}return _d({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function YU(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Ye(){return mn(pn(Vs))}function wr(){let t=p_.getStore();if(t)return t.projectDir;let e,r;try{let n=wt().platform;r=n,n==="claude-code"&&(e=je(Ia(),".claude","projects"))}catch{}return cT({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r})}function XU(t){return MU(t)?t:Ge(wr(),t)}function Aa(){return ui({projectDir:wr(),sessionsDir:Ye()})}function Dl(){let t=mn(qo(Vs));return pv({projectDir:wr(),contentDir:t})}function Mo(){if(!xr){let t=Dl();xr=new bl(t),xr.setDenyChecker(e=>{try{let r=wr(),n=Wy("Read",r);return Ky(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=Sr(Dl());Zy(e,14),xr.cleanupStaleSources(14);let r=je(Ia(),".context-mode","content");Ce(r)&&Zy(r,0)}catch{}Hy()}return KU(xr),xr}function QU(t){return t instanceof ar?{content:[{type:"text",text:ai(t)}],isError:!0}:null}async function ET(){return new Promise(t=>{let e=LU("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function rH(){let t=Ln?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function nH(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function oH(){return!on||on==="unknown"?!1:nH(on,nn)}function sH(){if(!oH())return!1;let t=Date.now();if(Ol>=eH){if(t-wT<tH)return!1;Ol=0}return Ol===0&&(wT=t),Ol++,!0}function iH(){if(!$T){$T=!0;try{let t=qe(),e=Ge(t,"plugins","installed_plugins.json");if(!Ce(e))return;let r=JSON.parse(Ll(e,"utf-8")),n=Ge(t,"plugins","cache"),o=Ce(Ge(Ft,"package.json"))?Ft:Sr(Ft);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||Ce(c)||!Ge(c).startsWith(n+DU))continue;try{NU(c).isSymbolicLink()&&Gs(c)}catch{}let u=Sr(c);Ce(u)||NT(u,{recursive:!0}),Ce(o)&&AU(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function G(t,e){if(iH(),sH()&&e.content.length>0){let n=rH();e.content[0].text=`\u26A0\uFE0F context-mode v${nn} outdated \u2192 v${on} available. Upgrade: ${n}
|
|
562
|
+
|
|
563
|
+
`+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return se.calls[t]=(se.calls[t]||0)+1,se.bytesReturned[t]=(se.bytesReturned[t]||0)+r,Ml(),setImmediate(()=>Q$(Aa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>G$({sessionDbPath:Aa(),toolName:t,bytesReturned:r})),e}function kr(t,e="unknown"){se.bytesIndexed+=t,Ml(),t>0&&setImmediate(()=>K$({sessionDbPath:Aa(),source:e,bytesAvoided:t}))}function HT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=mn(ii(Vs));return je(e,`stats-${t}.json`)}function Ml(){let t=Date.now();if(!(t-c_<aH)){c_=t;try{let e=Object.values(se.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(se.calls).reduce((l,m)=>l+m,0),n=se.bytesIndexed+se.bytesSandboxed+se.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=Il?.tokens??0;if(!Il||t-Il.computedAt>uH)try{a=(Ra({sessionsDir:Ye()})?.totalEvents??0)*lH,Il={tokens:a,computedAt:t}}catch{}let c={schemaVersion:cH,version:nn,updated_at:t,session_start:se.sessionStart,uptime_ms:t-se.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:se.bytesIndexed,bytes_sandboxed:se.bytesSandboxed,cache_hits:se.cacheHits,cache_bytes_saved:se.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*Pl).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Pl).toFixed(2),by_tool:Object.fromEntries(Object.keys({...se.calls,...se.bytesReturned}).map(l=>[l,{calls:se.calls[l]||0,bytes:se.bytesReturned[l]||0}]))},u=HT(),d=`${u}.tmp`;l_(d,JSON.stringify(c)),OU(d,u)}catch{}}}function m_(t,e){try{let r=Vy(process.env.CLAUDE_PROJECT_DIR),n=Gy(t,r);if(n.decision==="deny")return G(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function ZT(t,e,r){try{let n=L$(t,e);if(n.length===0)return null;let o=Vy(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=Gy(s,o);if(i.decision==="deny")return G(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function BT(t,e){try{let r=wr(),n=Wy("Read",r),o=Ky(t,n,process.platform==="win32",r);if(o.denied)return G(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function qT(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===mH){for(e.push(r),n++;n<t.length&&t[n]!==fH;)r++,n++;n<t.length&&n++}else r++,n++;return e}function f_(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of qT(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),d=t.toLowerCase();for(let l of u){let m=d.indexOf(l);for(;m!==-1;)o.push(m),m=d.indexOf(l,m+1)}}if(o.length===0)return t.slice(0,r)+`
|
|
564
|
+
\u2026`;o.sort((u,d)=>u-d);let s=300,i=[];for(let u of o){let d=Math.max(0,u-s),l=Math.min(t.length,u+s);i.length>0&&d<=i[i.length-1][1]?i[i.length-1][1]=l:i.push([d,l])}let a=[],c=0;for(let[u,d]of i){if(c>=r)break;let l=t.slice(u,Math.min(d,u+(r-c)));a.push((u>0?"\u2026":"")+l+(d<t.length?"\u2026":"")),c+=l.length}return a.join(`
|
|
565
|
+
|
|
566
|
+
`)}function VT(t,e,r,n=80*1024){let o=[],s=0;for(let i of e){if(s>n){o.push(`## ${i}
|
|
554
567
|
(output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
|
|
555
|
-
`);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(
|
|
568
|
+
`);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(o.push(`## ${i}`),o.push(""),a.length>0){for(let c of a){let u=f_(c.content,i,3e3,c.highlighted);o.push(`### ${c.title}`),o.push(u),o.push(""),s+=u.length+c.title.length}continue}o.push("No matching sections found."),o.push("")}return o.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),o}function hH(t){return`'${t.replace(/'/g,"'\\''")}'`}function gH(t){return`'${t.replace(/'/g,"''")}'`}function WT(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${gH(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${hH(r)} `}function TT(t,e,r){let n=e||"(no output)",o=n.matchAll(/__CM_FS__:(\d+)/g),s=0;for(let i of o)s+=parseInt(i[1]);return s>0&&(r?.(s),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
|
|
556
569
|
|
|
557
570
|
${n}
|
|
558
|
-
`}
|
|
571
|
+
`}function PT(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
|
|
572
|
+
`)?"":`
|
|
573
|
+
`}${r}`:r:e}async function GT(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let l=[],m=Date.now(),f=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let v=Date.now()-m,_=n-v;if(_<=0){l.push(`# ${h.label}
|
|
559
574
|
|
|
560
575
|
(skipped \u2014 batch timeout exceeded)
|
|
561
|
-
`),f=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${
|
|
576
|
+
`),f=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${s}${h.command}`,timeout:g});if(l.push(TT(h.label,PT(y),i)),y.timedOut){f=!0;for(let v=p+1;v<t.length;v++)l.push(`# ${t[v].label}
|
|
562
577
|
|
|
563
578
|
(skipped \u2014 batch timeout exceeded)
|
|
564
|
-
`);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${
|
|
579
|
+
`);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${s}${l.command}`,timeout:n}),f=TT(l.label,PT(m),i);return{output:m.timedOut?f.replace(/\n$/,"")+`
|
|
565
580
|
(timed out after ${n??"?"}ms)
|
|
566
|
-
`:f,timedOut:!!m.timedOut}}})),{settled:c}=await
|
|
581
|
+
`:f,timedOut:!!m.timedOut}}})),{settled:c}=await zy(a,{concurrency:o}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let m=c[l];if(m.status==="fulfilled")u[l]=m.value.output,m.value.timedOut&&(d=!0);else{let f=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
|
|
567
582
|
|
|
568
583
|
(executor error: ${f})
|
|
569
|
-
`}}return{outputs:u,timedOut:d}}function
|
|
570
|
-
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function
|
|
571
|
-
`).length,
|
|
572
|
-
`)}let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${
|
|
584
|
+
`}}return{outputs:u,timedOut:d}}function KT(t,e){let r=Mo();kr(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:Do()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
|
|
585
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function Ws(t,e,r,n=5){let o=t.split(`
|
|
586
|
+
`).length,s=Buffer.byteLength(t),i=Mo(),a=i.indexPlainText(t,r,void 0,Do()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
|
|
587
|
+
`)}let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let l of c){let m=l.content.split(`
|
|
573
588
|
`)[0].slice(0,120);d.push(` - ${l.title}: ${m}`)}return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),d.join(`
|
|
574
|
-
`)}function
|
|
589
|
+
`)}function Ul(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function h_(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function _H(t){let e=Ul(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function vH(){return s_||(s_=AT(import.meta.url).resolve("turndown")),s_}function bH(){return i_||(i_=AT(import.meta.url).resolve("turndown-plugin-gfm")),i_}function JT(t,e){let r=JSON.stringify(vH()),n=JSON.stringify(bH()),o=JSON.stringify(e),s=Na.toString(),i=Na.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
|
|
575
590
|
var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
|
|
576
591
|
const TurndownService = require(${r});
|
|
577
592
|
const { gfm } = require(${n});
|
|
@@ -579,7 +594,7 @@ const fs = require('fs');
|
|
|
579
594
|
const dns = require('no' + 'de:dns');
|
|
580
595
|
const dnsPromises = require('no' + 'de:dns/promises');
|
|
581
596
|
const url = ${JSON.stringify(t)};
|
|
582
|
-
const outputPath = ${
|
|
597
|
+
const outputPath = ${o};
|
|
583
598
|
|
|
584
599
|
// Strip proxy env vars from this subprocess only. A configured outbound
|
|
585
600
|
// proxy (HTTP_PROXY / HTTPS_PROXY / ALL_PROXY) would route fetch through
|
|
@@ -797,20 +812,47 @@ async function main() {
|
|
|
797
812
|
emit('text', text);
|
|
798
813
|
}
|
|
799
814
|
main();
|
|
800
|
-
`}async function
|
|
815
|
+
`}function SH(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function kH(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=Na(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function Na(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?Na(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function wH(t,e,r,n){let o=await kH(t);if(o)return o;if(!r&&n!==0){let i=Mo(),a=By(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),d=Date.now()-u.getTime(),l=n??xH;if(d<l){let m=Math.floor(d/36e5),f=Math.floor(d/(60*1e3)),p=m>0?`${m}h ago`:f>0?`${f}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:p,ttlStr:SH(l)}}}}let s=je(d_(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=JT(t,s),a=await Ma.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let d=a.stderr||a.stdout||"unknown error",m=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(d)?" \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:`${d}${m}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{u=Ll(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{Nl(s)}catch{}}}function EH(t){let e=Mo(),r=By(t.source,t.url),n=Do(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),kr(Buffer.byteLength(t.markdown));let s=t.markdown.length>OT?B$(t.markdown,OT)+`
|
|
801
816
|
|
|
802
|
-
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:
|
|
803
|
-
${
|
|
804
|
-
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var
|
|
817
|
+
\u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function IT(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function YT(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function u_(t,e=process.platform,r=DT){let n=YT(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:Oa});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 g_(t,e=process.platform,r=DT){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Oa});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let d=u[0],l=u[1],m=u[2],f=u[u.length-1];d==="TCP"&&l.endsWith(s)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Oa});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Oa});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Oa});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}async function $H(){let t=Hy();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?d_():"/tmp",r=je(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{Ma.cleanupBackgrounded(),xr&&xr.close();try{Gs(Fl)}catch{}try{Gs(r)}catch{}if(rn&&rn.pid&&!rn.killed)try{rn.kill("SIGTERM")}catch{}},o=async()=>{try{c_=0,Ml()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),H$({onShutdown:()=>o()});let s=new yl;await ze.connect(s);try{l_(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(yn(),vc)),c=ze.server.getClientVersion(),u=i(c??void 0);Ln=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=eT(Aa());if(i){for(let[a,c]of Object.entries(i.calls))se.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))se.bytesReturned[a]=c;i.sessionStart>0&&(se.sessionStart=i.sessionStart)}}catch{}ET().then(i=>{i!=="unknown"&&(on=i)}),setInterval(()=>{ET().then(i=>{i!=="unknown"&&(on=i)})},3600*1e3).unref(),setInterval(()=>Ml(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${nn} running on stdio`),console.error(`Detected runtimes:
|
|
818
|
+
${Ja(Da)}`),Hn()||(console.error(`
|
|
819
|
+
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Ft,nn,Da,Al,ze,MT,zT,a_,VU,p_,Ma,Fl,xr,Cl,Ln,rn,se,on,Ol,wT,eH,tH,$T,aH,cH,uH,lH,c_,Il,dH,pH,mH,fH,jl,zl,No,o_,yH,RT,CT,s_,i_,xH,OT,Oa,QT=x(()=>{"use strict";u$();m$();Ny();jy();w$();N$();D$();F$();Xa();U$();Z$();q$();Tr();W$();Y$();tT();aT();cn();yn();pd();hn();uT();ln();xT();ko();Ft=Sr(jU(import.meta.url)),nn=(()=>{for(let t of["../package.json","./package.json"]){let e=Ge(Ft,t);if(Ce(e))try{return JSON.parse(Ll(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}
|
|
805
820
|
`)}),process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
|
|
806
|
-
`)}))
|
|
807
|
-
`);process.on("exit",()=>{try{
|
|
821
|
+
`)}));Da=Lo(),Al=Ya(Da),ze=new hl({name:"context-mode",version:nn}),MT=[];zT=jT(),a_=!1;VU=ze.registerTool.bind(ze);ze.registerTool=(...t)=>{let[e,r,n]=t;if(zT){LT();return}let o=WU(e,n);return MT.push({name:e,config:r,handler:o}),t[2]=o,VU(...t)};zT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&FT(ze);p_=new FU;ze.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});ze.server.setRequestHandler(bs,async()=>({prompts:[]}));ze.server.setRequestHandler(_s,async()=>({resources:[]}));ze.server.setRequestHandler(vs,async()=>({resourceTemplates:[]}));Ma=new Us({runtimes:Da,projectRoot:()=>wr()}),Fl=je(d_(),`cm-fs-preload-${process.pid}.js`);l_(Fl,`(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){}})();
|
|
822
|
+
`);process.on("exit",()=>{try{Gs(Fl)}catch{}});xr=null;Ln=null,rn=null;se={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()};on=null,Ol=0,wT=0,eH=3,tH=3600*1e3;$T=!1;aH=500,cH=2,uH=3e4,lH=256,c_=0;dH=Al.join(", "),pH=Hn()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",mH="",fH="";ze.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${pH} Languages: ${dH}.
|
|
823
|
+
|
|
824
|
+
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.
|
|
825
|
+
|
|
826
|
+
Concrete shape \u2014 analyze 47 source files without reading any of them:
|
|
827
|
+
ctx_execute(language: "javascript", code: \`
|
|
828
|
+
const fs = require('fs');
|
|
829
|
+
const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
|
|
830
|
+
files.forEach(f => {
|
|
831
|
+
const lines = fs.readFileSync('src/'+f,'utf8').split('\\\\n').length;
|
|
832
|
+
console.log(f + ': ' + lines + ' lines');
|
|
833
|
+
});
|
|
834
|
+
\`)
|
|
835
|
+
// 47 files analyzed, 15,314 LoC summarized \u2014 output ~3.6 KB instead of 47 Read() calls = ~700 KB.
|
|
808
836
|
|
|
809
|
-
|
|
837
|
+
WHEN:
|
|
838
|
+
- You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) \u2014 do the derivation in code and print only the answer
|
|
839
|
+
- Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)
|
|
840
|
+
- You would otherwise read raw output and then mentally compute \u2014 that compute belongs here, in code, where its inputs stay out of your conversation
|
|
841
|
+
- You need to keep a long-running process alive (dev server, watcher, daemon) \u2014 pass \`background: true\` to detach on timeout instead of killing the process
|
|
842
|
+
- The output may legitimately be large but you only want recall-by-topic later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search
|
|
810
843
|
|
|
811
|
-
|
|
844
|
+
WHEN NOT:
|
|
845
|
+
- Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) \u2014 Bash is simpler
|
|
846
|
+
- File mutations (Edit/Write) or navigation (cd/ls) \u2014 Bash is the right surface
|
|
847
|
+
- You already know the output is one short fixed line and you want to read it as-is
|
|
812
848
|
|
|
813
|
-
|
|
849
|
+
RETURNS:
|
|
850
|
+
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.
|
|
851
|
+
|
|
852
|
+
EXAMPLE: ctx_execute(language: "shell", code: "npm test 2>&1 | grep -E '(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))' | head -60")
|
|
853
|
+
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:L.object({language:L.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:L.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:L.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:L.preprocess(h_,L.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:L.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'.
|
|
854
|
+
|
|
855
|
+
TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=m_(e,"execute");if(s)return s}else{let s=ZT(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
|
|
814
856
|
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
|
|
815
857
|
let __cm_fs=0;
|
|
816
858
|
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
|
|
@@ -869,48 +911,65 @@ ${e}
|
|
|
869
911
|
}
|
|
870
912
|
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
|
|
871
913
|
setInterval(()=>{},2147483647);`:""}
|
|
872
|
-
})(typeof require!=='undefined'?require:null);`);let i=await
|
|
914
|
+
})(typeof require!=='undefined'?require:null);`);let i=await Ma.execute({language:t,code:s,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(se.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(se.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?G("ctx_execute",{content:[{type:"text",text:`${d}
|
|
873
915
|
|
|
874
|
-
_(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?
|
|
916
|
+
_(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?G("ctx_execute",{content:[{type:"text",text:`${d}
|
|
875
917
|
|
|
876
|
-
_(timed out after ${r}ms \u2014 partial output shown above)_`}]}):
|
|
918
|
+
_(timed out after ${r}ms \u2014 partial output shown above)_`}]}):G("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
|
|
877
919
|
|
|
878
920
|
stderr:
|
|
879
|
-
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=
|
|
921
|
+
${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=Jy({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(l)>jl?(kr(Buffer.byteLength(l)),G("ctx_execute",{content:[{type:"text",text:Ws(l,o,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>zl?(kr(Buffer.byteLength(l)),G("ctx_execute",{content:[{type:"text",text:Ws(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):G("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(u)>jl?(kr(Buffer.byteLength(u)),G("ctx_execute",{content:[{type:"text",text:Ws(u,o,`execute:${t}`)}]})):Buffer.byteLength(u)>zl?G("ctx_execute",KT(u,`execute:${t}`)):G("ctx_execute",{content:[{type:"text",text:u}]})}catch(s){let i=s instanceof Error?s.message:String(s);return G("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});jl=5e3,zl=102400;ze.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
|
|
922
|
+
|
|
923
|
+
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.
|
|
924
|
+
|
|
925
|
+
WHEN:
|
|
926
|
+
- You want to KNOW SOMETHING ABOUT a file (line count, matches of a pattern, parsed structure, statistical aggregate) without needing to SEE all of it
|
|
927
|
+
- The file is structured (CSV, JSON, log, code) and a code-level derivation is cheaper than reading verbatim
|
|
928
|
+
- The file is large enough that reading the full content would burn meaningful conversation memory you need for the actual work
|
|
929
|
+
- The derivation may itself produce a large output you want recall-by-topic on later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed and only matching sections come back, retrievable via ctx_search
|
|
880
930
|
|
|
881
|
-
|
|
931
|
+
WHEN NOT:
|
|
932
|
+
- You intend to EDIT the file \u2014 use Read so the subsequent Edit can match the exact text
|
|
933
|
+
- You only need one specific line and you know its offset \u2014 Read with offset/limit is the simplest path
|
|
934
|
+
- The file is small AND you will consume all of it for understanding/editing \u2014 Read directly
|
|
882
935
|
|
|
883
|
-
|
|
936
|
+
RETURNS:
|
|
937
|
+
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.
|
|
884
938
|
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
- API references (endpoint details, parameter specs, response schemas)
|
|
888
|
-
- MCP tools/list output (exact tool signatures and descriptions)
|
|
889
|
-
- Skill prompts and instructions that are too large for context
|
|
890
|
-
- README files, migration guides, changelog entries
|
|
891
|
-
- Any content with code examples you may need to reference precisely
|
|
939
|
+
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'))")
|
|
940
|
+
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:L.object({path:L.string().describe("Absolute file path or relative to project root"),language:L.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:L.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:L.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:L.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=BT(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=m_(r,"execute_file");if(i)return i}else{let i=ZT(r,e,"execute_file");if(i)return i}try{let i=await Ma.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return G("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=Jy({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(u)>jl?(kr(Buffer.byteLength(u)),G("ctx_execute_file",{content:[{type:"text",text:Ws(u,o,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>zl?(kr(Buffer.byteLength(u)),G("ctx_execute_file",{content:[{type:"text",text:Ws(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):G("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(a)>jl?(kr(Buffer.byteLength(a)),G("ctx_execute_file",{content:[{type:"text",text:Ws(a,o,`file:${t}`)}]})):Buffer.byteLength(a)>zl?G("ctx_execute_file",KT(a,`file:${t}`)):G("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return G("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});ze.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
|
|
892
941
|
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
942
|
+
WHEN:
|
|
943
|
+
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
|
|
944
|
+
- API references (endpoint details, parameter specs, response schemas)
|
|
945
|
+
- MCP tools/list output (exact tool signatures and descriptions)
|
|
946
|
+
- Skill prompts and instructions that are too large to keep verbatim in conversation
|
|
947
|
+
- README files, migration guides, changelog entries
|
|
948
|
+
- Any content with code examples you may need to reference precisely later
|
|
897
949
|
|
|
898
|
-
|
|
950
|
+
WHEN NOT:
|
|
951
|
+
- Log files, test output, CSV, or build output \u2014 use ctx_execute_file, which processes in-sandbox without persisting bytes
|
|
952
|
+
- Single-use ephemeral content you will not query later \u2014 keep it inline if it fits, or ctx_execute_file it
|
|
899
953
|
|
|
900
|
-
|
|
954
|
+
RETURNS:
|
|
955
|
+
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.
|
|
956
|
+
|
|
957
|
+
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
|
|
958
|
+
EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:L.object({content:L.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:L.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:L.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return G("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=BT(e,"ctx_index");if(n)return n}try{let n=e?XU(e):void 0;if(t)kr(Buffer.byteLength(t));else if(n)try{let i=await import("fs");kr(i.readFileSync(n).byteLength)}catch{}let s=Mo().index({content:t,path:n,source:r??n,attribution:Do()});return G("ctx_index",{content:[{type:"text",text:`Indexed ${s.totalChunks} sections (${s.codeChunks} with code) from: ${s.label}
|
|
959
|
+
Use ctx_search(queries: ["..."]) to query this content. Use source: "${s.label}" to scope results.`}]})}catch(n){let o=n instanceof Error?n.message:String(n);return G("ctx_index",{content:[{type:"text",text:`Index error: ${o}`}],isError:!0})}});No=0,o_=Date.now(),yH=6e4,RT=3,CT=8;ze.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts.\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:L.object({queries:L.preprocess(Ul,L.array(L.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:L.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:L.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:L.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:L.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.")})},async t=>{try{let e=Mo(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return G("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
|
|
901
960
|
|
|
902
961
|
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
|
|
903
962
|
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
|
|
904
963
|
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
|
|
905
964
|
\u2022 ctx_index(content, source) \u2014 manually index text content
|
|
906
965
|
|
|
907
|
-
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,
|
|
966
|
+
After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return G("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a}=t,c=Date.now();if(c-o_>yH&&(No=0,o_=c),No++,No>CT)return G("ctx_search",{content:[{type:"text",text:`BLOCKED: ${No} search calls in ${Math.round((c-o_)/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 u=No>RT?1:Math.min(s,2),d=40*1024,l=0,m=[],f=null;if(r==="timeline")try{let g=Ye(),y=wr(),v=ui({projectDir:y,sessionsDir:g});Ce(v)&&(f=new cr({dbPath:v}))}catch{}let p=Ln?.getConfigDir()??qe();try{for(let g of o){if(l>d){m.push(`## ${g}
|
|
908
967
|
(output cap reached)
|
|
909
|
-
`);continue}let y;if(r==="timeline"?y=
|
|
910
|
-
No results found.`);continue}let v=y.map((_,b)=>{let S=_.origin||"current-session",
|
|
968
|
+
`);continue}let y;if(r==="timeline"?y=iT({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:wr(),configDir:p,adapter:Ln??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){m.push(`## ${g}
|
|
969
|
+
No results found.`);continue}let v=y.map((_,b)=>{let S=_.origin||"current-session",P=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",$=`--- [${S}${P?" | "+P:""} | ${_.source}] ---`,R=`### ${_.title}`,A=f_(_.content,g,1500,_.highlighted);return`${$}
|
|
911
970
|
${R}
|
|
912
971
|
|
|
913
|
-
${
|
|
972
|
+
${A}`}).join(`
|
|
914
973
|
|
|
915
974
|
`);m.push(`## ${g}
|
|
916
975
|
|
|
@@ -920,144 +979,170 @@ ${v}`),l+=v.length}}finally{try{f?.close()}catch{}}let h=m.join(`
|
|
|
920
979
|
|
|
921
980
|
`);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
|
|
922
981
|
|
|
923
|
-
`+h)
|
|
982
|
+
`+h),No>=RT&&(h+=`
|
|
924
983
|
|
|
925
|
-
\u26A0 search call #${
|
|
926
|
-
Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return
|
|
984
|
+
\u26A0 search call #${No}/${CT} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
|
|
985
|
+
Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return G("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return G("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return G("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});s_=null,i_=null;xH=1440*60*1e3,OT=3072;ze.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
|
|
927
986
|
|
|
928
|
-
|
|
987
|
+
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.
|
|
929
988
|
|
|
930
|
-
|
|
989
|
+
WHEN:
|
|
990
|
+
- You need web content (docs, changelogs, API references, spec pages) and the raw page bytes should NOT enter your conversation
|
|
991
|
+
- Multi-URL research (library evaluation, migration scans, doc comparisons): pass the \`requests\` array and a \`concurrency\` value 2-8 for parallel I/O
|
|
992
|
+
- You want repeat lookups against the same URL to be cheap (TTL cache hits return only a hint, no re-fetch)
|
|
993
|
+
- You want a long-lived cache window (override \`ttl\` upward for stable specs) or a guaranteed-fresh fetch (\`ttl: 0\` or \`force: true\`)
|
|
931
994
|
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
Example: requests: [{url: 'https://react.dev/...', source: 'react'}, {url: 'https://vuejs.org/...', source: 'vue'}], concurrency: 5.
|
|
936
|
-
Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:F.object({url:F.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:F.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:F.array(F.object({url:F.string().describe("URL to fetch"),source:F.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:F.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:F.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return W("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(P=>({run:()=>NU(P.url,P.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await ky(c,{concurrency:a,capByCpuCount:!i&&a>1}),m=[];for(let P=0;P<u.length;P++){let C=u[P];if(C.status==="rejected"){let X=C.reason instanceof Error?C.reason.message:String(C.reason);m.push({kind:"job_error",url:o[P].url,error:X});continue}let L=C.value;if(L.kind==="cached"){oe.cacheHits++,oe.cacheBytesSaved+=L.estimatedBytes;let X=L.estimatedBytes,fe=L.label;setImmediate(()=>$$({sessionDbPath:wa(),source:fe,bytesAvoided:X})),m.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr})}else L.kind==="fetch_error"?m.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):m.push({kind:"fetched",indexed:DU(L)})}if(i){let P=m[0];if(P.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${P.label}** \u2014 ${P.chunkCount} sections, indexed ${P.ageStr} (fresh, TTL: 24h).
|
|
937
|
-
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
995
|
+
WHEN NOT:
|
|
996
|
+
- You already have the content locally \u2014 store it via the inline index tool
|
|
997
|
+
- The page is SPA-rendered (JavaScript-required to materialize content) \u2014 this is a plain HTTP fetch, no headless browser
|
|
938
998
|
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:L}]})}if(P.kind==="fetch_error"){let C=P.reason==="empty"?`Fetched ${P.url} but got empty content`:P.reason==="read"?`Fetched ${P.url} but could not read subprocess output`:P.reason==="exit"?`Failed to fetch ${P.url}: ${P.error}`:`Fetch error: ${P.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let f=384,p=[],h=0,g=0,y=0,v=0,_=0,b=[];for(let P of m)if(P.kind==="cached")y++,p.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr})`);else if(P.kind==="fetched"){v++,h+=P.indexed.totalChunks,g+=P.indexed.totalBytes;let C=(P.indexed.totalBytes/1024).toFixed(1);p.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${C}KB)`);let L=P.indexed.preview.length>f?P.indexed.preview.slice(0,f).trimEnd()+"\u2026":P.indexed.preview;b.push(`### ${P.indexed.label}
|
|
999
|
+
RETURNS:
|
|
1000
|
+
Per-source preview windows extracted around indexable headings plus indexing metadata (chunk counts, source labels, cache state). Raw content is NOT echoed back \u2014 retrieve any section on-demand via ctx_search(source: "<label>"). Concurrency parallelizes the fetch phase up to your chosen value (capped by the host's logical CPU count); the FTS5 write phase always runs serially because SQLite is a single-writer store. Net latency = max(fetch latency across the pool) + sum(per-source index write time). Cache hits skip both phases and return a small freshness hint instead of re-fetching. Use 4-8 for stable I/O-bound batches; lower the value when the target host enforces a per-IP rate limit you cannot raise.
|
|
942
1001
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
One ctx_batch_execute call replaces 30+ ctx_execute calls + 10+ ctx_search calls.
|
|
949
|
-
Provide all commands to run and all queries to search \u2014 everything happens in one round trip.
|
|
950
|
-
|
|
951
|
-
PARALLELIZE I/O: For I/O-bound batches (network calls, slow API queries, multi-URL fetches), ALWAYS pass concurrency: 4-8 \u2014 speeds up by 3-5x on real workloads.
|
|
952
|
-
\u2705 Use concurrency: 4-8 for: gh API calls, curl/web fetches, multi-region cloud queries, multi-repo git reads, dig/DNS, docker inspect.
|
|
953
|
-
\u274C Keep concurrency: 1 for: npm test, build, lint, image processing (CPU-bound), or commands sharing state (ports, lock files, same-repo writes).
|
|
954
|
-
Example: [gh issue view 1, gh issue view 2, gh issue view 3] \u2192 concurrency: 3.
|
|
955
|
-
Speedup depends on workload \u2014 applies to I/O wait, not CPU work.
|
|
1002
|
+
EXAMPLE: ctx_fetch_and_index(
|
|
1003
|
+
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
|
|
1004
|
+
concurrency: 5
|
|
1005
|
+
)`,inputSchema:L.object({url:L.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:L.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:L.preprocess(Ul,L.array(L.object({url:L.string().describe("URL to fetch"),source:L.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:L.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:L.preprocess(h_,L.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:L.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return G("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(w=>({run:()=>wH(w.url,w.source,o,s)})),{settled:d,effectiveConcurrency:l,capped:m}=await zy(u,{concurrency:c,capByCpuCount:!a&&c>1}),f=[];for(let w=0;w<d.length;w++){let H=d[w];if(H.status==="rejected"){let ae=H.reason instanceof Error?H.reason.message:String(H.reason);f.push({kind:"job_error",url:i[w].url,error:ae});continue}let F=H.value;if(F.kind==="cached"){se.cacheHits++,se.cacheBytesSaved+=F.estimatedBytes;let ae=F.estimatedBytes,Ze=F.label;setImmediate(()=>J$({sessionDbPath:Aa(),source:Ze,bytesAvoided:ae})),f.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?f.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):f.push({kind:"fetched",indexed:EH(F)})}if(a){let w=f[0];if(w.kind==="cached")return G("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${w.label}** \u2014 ${w.chunkCount} sections, indexed ${w.ageStr} (fresh, TTL: ${w.ttlStr}).
|
|
1006
|
+
To refresh: call ctx_fetch_and_index again with \`force: true\`.
|
|
956
1007
|
|
|
957
|
-
|
|
1008
|
+
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
|
|
1009
|
+
Use: ctx_search(queries: [...], source: "${w.label}")`}]});if(w.kind==="fetched"){let H=(w.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${w.indexed.totalChunks} sections** (${H}KB) from: ${w.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${w.indexed.label}") for specific lookups.`,"","---","",w.indexed.preview].join(`
|
|
1010
|
+
`);return G("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(w.kind==="fetch_error"){let H=w.reason==="empty"?`Fetched ${w.url} but got empty content`:w.reason==="read"?`Fetched ${w.url} but could not read subprocess output`:w.reason==="exit"?`Failed to fetch ${w.url}: ${w.error}`:`Fetch error: ${w.error}`;return G("ctx_fetch_and_index",{content:[{type:"text",text:H}],isError:!0})}return G("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${w.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,v=0,_=0,b=0,S=[];for(let w of f)if(w.kind==="cached")v++,h.push(`- [cache] ${w.label} \u2014 ${w.chunkCount} sections (${w.ageStr}, TTL: ${w.ttlStr})`);else if(w.kind==="fetched"){_++,g+=w.indexed.totalChunks,y+=w.indexed.totalBytes;let H=(w.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${w.indexed.label} \u2014 ${w.indexed.totalChunks} sections (${H}KB)`);let F=w.indexed.preview.length>p?w.indexed.preview.slice(0,p).trimEnd()+"\u2026":w.indexed.preview;S.push(`### ${w.indexed.label}
|
|
1011
|
+
|
|
1012
|
+
${F}`)}else b++,h.push(`- [err] ${w.url}: ${w.error}`);let P=(y/1024).toFixed(1),$=m?` cap=${l}/${zU().length}cpu`:"",R=(w,H,F)=>`${w} ${w===1?H:F}`,z=[`fetched ${i.length} c=${l}${$}. ok=${_} cache=${v} err=${b}. ${R(g,"section","sections")} ${P}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...S.length>0?["","---","",...S]:[]].join(`
|
|
1013
|
+
`);return G("ctx_fetch_and_index",{content:[{type:"text",text:z}],isError:b===i.length})});ze.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
|
|
1014
|
+
|
|
1015
|
+
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).
|
|
1016
|
+
|
|
1017
|
+
WHEN:
|
|
1018
|
+
- You have 3+ related commands you would otherwise run sequentially (multi-issue lookups, git log + git diff + git blame, multi-file reads, multi-region cloud queries)
|
|
1019
|
+
- You want to gather AND query in one round trip \u2014 pass \`queries\` so the matching sections come back inline
|
|
1020
|
+
- You want to parallelize I/O-bound work \u2014 pass \`concurrency\` 2-8 (network calls, gh CLI, cloud APIs, multi-repo git reads)
|
|
1021
|
+
- The combined output is large enough that piping it through ctx_search later would itself be expensive \u2014 let auto-index + inline queries do both in one shot
|
|
1022
|
+
|
|
1023
|
+
WHEN NOT:
|
|
1024
|
+
- Single command with no follow-up query \u2014 run it in the sandbox tool directly
|
|
1025
|
+
- CPU-bound or stateful commands \u2014 keep concurrency at 1 (npm test, build, lint, port-binding servers, lock-file holders, anything that races on the same resource)
|
|
1026
|
+
|
|
1027
|
+
RETURNS:
|
|
1028
|
+
Auto-indexed section list per command label, plus top matches per query (when \`queries\` is passed). Raw output is NOT echoed in full \u2014 only the matched windows. Concurrency>1 switches each command to its own per-command timeout (no shared budget); concurrency=1 preserves the legacy shared-budget cascading-skip-on-timeout path. Use 4-8 for I/O-bound batches; keep at 1 for CPU work or shared-state commands; lower the value when target hosts enforce per-IP rate limits.
|
|
1029
|
+
|
|
1030
|
+
EXAMPLE: ctx_batch_execute(
|
|
1031
|
+
commands: [
|
|
1032
|
+
{label: "issue 1", command: "gh issue view 1"},
|
|
1033
|
+
{label: "issue 2", command: "gh issue view 2"},
|
|
1034
|
+
{label: "summarize", command: "echo done"}
|
|
1035
|
+
],
|
|
1036
|
+
queries: ["root cause", "proposed fix"],
|
|
1037
|
+
concurrency: 2
|
|
1038
|
+
)`,inputSchema:L.object({commands:L.preprocess(_H,L.array(L.object({label:L.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:L.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:L.preprocess(Ul,L.array(L.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:L.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:L.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.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let o of t){let s=m_(o.command,"batch_execute");if(s)return s}try{let o=WT(Da.shell,Fl),{outputs:s,timedOut:i}=await GT(t,{timeout:r,concurrency:n,nodeOptsPrefix:o,onFsBytes:_=>{se.bytesSandboxed+=_}},Ma),a=s.join(`
|
|
958
1039
|
`),c=Buffer.byteLength(a),u=a.split(`
|
|
959
|
-
`).length;if(i&&
|
|
1040
|
+
`).length;if(i&&s.length===0)return G("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});kr(c);let d=Mo(),l=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l,attribution:Do()}),f=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],h=[];for(let _ of f){let b=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(b/1024).toFixed(1)}KB)`),h.push(_.title)}let g=VT(d,e,l),y=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
|
|
960
1041
|
Searchable terms for follow-up: ${y.join(", ")}`:""].join(`
|
|
961
|
-
`);return
|
|
962
|
-
`)}]})});ze.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:
|
|
963
|
-
`),c=
|
|
964
|
-
`);return
|
|
1042
|
+
`);return G("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(o){let s=o instanceof Error?o.message:String(o);return G("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${s}`}],isError:!0})}});ze.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:L.object({})},async()=>{let t;try{let e=wr(),r=ht(e),n=ui({projectDir:e,sessionsDir:Ye()});if(Ce(n)){let o=Xe(),s=new o(n,{readonly:!0});try{let i=new qs(s),a=i.queryAll(se),c=i.getMcpToolUsage(),u=Ra({sessionsDir:Ye()}),d;try{d=Tl()}catch{}let l,m;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){l=_T({sessionId:f,sessionsDir:Ye(),worktreeHash:r});let p=Dl(),h;try{let _=Xe(),b=(await import("node:fs")).readdirSync(Ye()).filter(P=>P.endsWith(".db")&&(!r||P.startsWith(r))),S;for(let P of b)try{let $=new _((await import("node:path")).join(Ye(),P),{readonly:!0});try{let R=$.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(f);if(R?.project_dir){S=R.project_dir;break}}finally{$.close()}}catch{}h=S?Ca({projectDir:S,sessionsDir:Ye(),worktreeHash:r,contentDbPath:p}):Ca({sessionId:f,sessionsDir:Ye(),worktreeHash:r,contentDbPath:p})}catch{h=Ca({sessionId:f,sessionsDir:Ye(),worktreeHash:r,contentDbPath:p})}let g=Ca({sessionsDir:Ye()}),y=vT(p),v={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};m={conversation:h,lifetime:v}}}catch{}t=Rl(a,nn,on,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m,cwd:e})}finally{s.close()}}else{let s=new qs(IT()).queryAll(se),i=Ra({sessionsDir:Ye()}),a;try{a=Tl()}catch{}t=Rl(s,nn,on,{lifetime:i,multiAdapter:a})}}catch{let r=new qs(IT()).queryAll(se),n;try{n=Ra({sessionsDir:Ye()})}catch{}let o;try{o=Tl()}catch{}t=Rl(r,nn,on,n||o?{lifetime:n,multiAdapter:o}:void 0)}return G("ctx_stats",{content:[{type:"text",text:t}]})});ze.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:L.object({})},async()=>{let t=["context-mode doctor",""],e=Ce(Ge(Ft,"package.json"))?Ft:Sr(Ft),r=11,n=(Al.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Al.length}/${r} (${n}%) \u2014 ${Al.join(", ")}`),Hn()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=pn(Vs),s=qo(Vs),i=ii(Vs);t.push(`[OK] Storage sessions: ${o.path} (${ac(o)})`),t.push(`[OK] Storage content: ${s.path} (${ac(s)})`),t.push(`[OK] Storage stats: ${i.path} (${ac(i)})`);{let c=new Us({runtimes:Da});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${d}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=Xe();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=c.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(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await JU();if(a){for(let u of a.validateHooks(e)){let d=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",l=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${d} ${u.check}: ${u.message}${l}`)}let c=ec(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let d=Ge(e,u);Ce(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${nn}`),G("ctx_doctor",{content:[{type:"text",text:t.join(`
|
|
1043
|
+
`)}]})});ze.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:L.object({})},async()=>{let t=Ce(Ge(Ft,"package.json"))?Ft:Sr(Ft),e=Ge(t,"cli.bundle.mjs"),r=Ge(t,"build","cli.js");try{let i=Ye(),a=je(Sr(i),"insight-cache");Ce(a)&&(g_(4747),Nl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(yn(),vc)),a=ze.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let o;if(Ce(e))o=`${Fe(e)} upgrade${n}`;else if(Ce(r))o=`${Fe(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'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(`
|
|
1044
|
+
`),c=Ge(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),o=Fe(c)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",o,"```","","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(`
|
|
1045
|
+
`);return G("ctx_upgrade",{content:[{type:"text",text:s}]})});ze.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
|
|
1046
|
+
|
|
1047
|
+
WHEN:
|
|
1048
|
+
- User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
|
|
1049
|
+
- User explicitly asks to reset the whole project ('reset everything', 'wipe the knowledge base')
|
|
965
1050
|
|
|
966
|
-
|
|
1051
|
+
WHEN NOT:
|
|
1052
|
+
- User says 'reset', 'clear', or 'wipe' without naming a scope -> ask which scope before calling
|
|
1053
|
+
- User wants to free memory or improve performance -> recommend ctx_stats first, do not purge
|
|
967
1054
|
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1055
|
+
SCOPES (pass exactly one):
|
|
1056
|
+
- Per-session: ctx_purge(confirm: true, sessionId: "<uuid>") deletes that session's events (auto-captured decisions, errors, plans, user prompts, rejected approaches, etc.) and per-session FTS5 chunks; sibling sessions and stats file are preserved.
|
|
1057
|
+
- Per-project: ctx_purge(confirm: true, scope: "project") wipes FTS5 knowledge base, every session DB row, events markdown, and resets the stats file. Use ctx_stats first to preview category counts before purging.
|
|
971
1058
|
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
1059
|
+
CONTRACT:
|
|
1060
|
+
- confirm:true is required; confirm:false returns 'purge cancelled'.
|
|
1061
|
+
- sessionId and scope:'project' together return 'ambiguous - pick one'.
|
|
1062
|
+
- scope:'session' without sessionId throws (sessionId required).
|
|
1063
|
+
- Bare {confirm:true} is deprecated: maps to scope:'project' with a stderr warning; will hard-error in a future major.
|
|
975
1064
|
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
\u2022 Both sessionId AND scope:'project' provided \u2192 'ambiguous \u2014 pick one'
|
|
979
|
-
\u2022 scope:'session' without sessionId \u2192 throws (sessionId required)
|
|
980
|
-
\u2022 Neither sessionId NOR scope provided \u2192 DEPRECATED: maps to
|
|
981
|
-
scope:'project' with a deprecation warning to stderr. Will be a hard
|
|
982
|
-
error in a future major.
|
|
1065
|
+
RETURNS:
|
|
1066
|
+
A summary of removed rows + the resolved scope.
|
|
983
1067
|
|
|
984
|
-
|
|
985
|
-
Use scope:'project'
|
|
986
|
-
NEVER call with bare {confirm:true} \u2014 always specify the scope.`,inputSchema:F.object({confirm:F.preprocess(wT,F.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:F.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:F.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return W("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let s;try{s=El()}catch{}if(br){try{br.cleanup()}catch{}br=null}let o=s?rr(s):void 0,{deleted:i}=S$({projectDir:Sr(),sessionsDir:it(),storePath:s,contentDir:o,legacyContentDir:Se(zo(),".context-mode","content"),contentHash:Jr(Sr()),scope:n,sessionId:e});if(n==="project"){oe.calls={},oe.bytesReturned={},oe.bytesIndexed=0,oe.bytesSandboxed=0,oe.cacheHits=0,oe.cacheBytesSaved=0,oe.sessionStart=Date.now(),i.push("session stats");try{let c=gT();Oe(c)&&jo(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return W("ctx_purge",{content:[{type:"text",text:a}]})});Sa=5e3;ze.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly.",inputSchema:F.object({port:F.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:F.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:F.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:F.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:F.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:s})=>{let o=t||4747,i=e||n,a=r||s,c=Oe(We(zt,"package.json"))?zt:rr(zt),u=We(c,"insight"),d=i?We(i):it(),l=a?We(a):Se(rr(d),"content"),m=Se(rr(d),"insight-cache");if(!Oe(Se(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],p=!1;ka(m,{recursive:!0});let h=X$(Se(u,"server.mjs")).mtimeMs,g=Oe(Se(m,"server.mjs"))?X$(Se(m,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),V2(u,m,{recursive:!0,force:!0}),f.push("Source files copied."),p=!0),!Oe(Se(m,"node_modules"))||p){f.push("Installing dependencies (first run, ~30s)...");try{Q$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{wl(Se(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Oe(Se(m,"node_modules","vite"))||!Oe(Se(m,"node_modules","better-sqlite3")))throw wl(Se(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),Q$("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let v=!1;try{let{request:R}=await import("node:http");await new Promise((N,P)=>{let C=R(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},L=>{L.resume(),N()});C.on("error",()=>P()),C.on("timeout",()=>{C.destroy(),P()}),C.end()}),v=!0}catch{}if(v&&p){f.push("Killing stale dashboard server (source updated)...");let R=a_(o);if(R.attemptedPids.length>0&&R.killedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${R.attemptedPids.join(", ")}: ${R.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(R.errors.length>0&&R.attemptedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${R.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(N=>setTimeout(N,500)),f.push(`Stale server killed (${R.killedPids.length} pid${R.killedPids.length===1?"":"s"}).`)}else if(v){f.push("Dashboard already running.");let R=`http://localhost:${o}`,N=e_(R),P=N.ok?"":` (auto-open failed: ${N.reason}; navigate manually)`;return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${R}${P}`}]})}if(Qr&&Qr.pid&&!Qr.killed)try{Qr.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),b=_("node",[Se(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});b.on("error",()=>{}),b.unref(),Qr=b,await new Promise(R=>setTimeout(R,1500));try{let{request:R}=await import("node:http");await new Promise((N,P)=>{let C=R(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},L=>{N(),L.resume()});C.on("error",P),C.on("timeout",()=>{C.destroy(),P(new Error("timeout"))}),C.end()})}catch{return W("ctx_insight",{content:[{type:"text",text:`Port ${o} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
|
|
1068
|
+
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
|
|
1069
|
+
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:L.object({confirm:L.preprocess(h_,L.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:L.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:L.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return G("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 G("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=Dl()}catch{}if(xr){try{xr.cleanup()}catch{}xr=null}let s=o?Sr(o):void 0,{deleted:i}=V$({projectDir:wr(),sessionsDir:Ye(),storePath:o,contentDir:s,legacyContentDir:je(Ia(),".context-mode","content"),contentHash:Ur(wr()),scope:n,sessionId:e});if(n==="project"){se.calls={},se.bytesReturned={},se.bytesIndexed=0,se.bytesSandboxed=0,se.cacheHits=0,se.cacheBytesSaved=0,se.sessionStart=Date.now(),i.push("session stats");try{let c=HT();Ce(c)&&Gs(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return G("ctx_purge",{content:[{type:"text",text:a}]})});Oa=5e3;ze.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:L.object({port:L.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:L.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:L.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:L.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:L.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=Ce(Ge(Ft,"package.json"))?Ft:Sr(Ft),u=Ge(c,"insight"),d=i?Ge(i):Ye(),l=a?Ge(a):je(Sr(d),"content"),m=je(Sr(d),"insight-cache");if(!Ce(je(u,"server.mjs")))return G("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],p=!1;NT(m,{recursive:!0});let h=ST(je(u,"server.mjs")).mtimeMs,g=Ce(je(m,"server.mjs"))?ST(je(m,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),IU(u,m,{recursive:!0,force:!0}),f.push("Source files copied."),p=!0),!Ce(je(m,"node_modules"))||p){f.push("Installing dependencies (first run, ~30s)...");try{kT(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{Nl(je(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Ce(je(m,"node_modules","vite"))||!Ce(je(m,"node_modules","better-sqlite3")))throw Nl(je(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),kT("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let v=!1;try{let{request:R}=await import("node:http");await new Promise((A,z)=>{let w=R(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},H=>{H.resume(),A()});w.on("error",()=>z()),w.on("timeout",()=>{w.destroy(),z()}),w.end()}),v=!0}catch{}if(v&&p){f.push("Killing stale dashboard server (source updated)...");let R=g_(s);if(R.attemptedPids.length>0&&R.killedPids.length===0)return G("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${R.attemptedPids.join(", ")}: ${R.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(R.errors.length>0&&R.attemptedPids.length===0)return G("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${R.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(A=>setTimeout(A,500)),f.push(`Stale server killed (${R.killedPids.length} pid${R.killedPids.length===1?"":"s"}).`)}else if(v){f.push("Dashboard already running.");let R=`http://localhost:${s}`,A=u_(R),z=A.ok?"":` (auto-open failed: ${A.reason}; navigate manually)`;return G("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${R}${z}`}]})}if(rn&&rn.pid&&!rn.killed)try{rn.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),b=_("node",[je(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});b.on("error",()=>{}),b.unref(),rn=b,await new Promise(R=>setTimeout(R,1500));try{let{request:R}=await import("node:http");await new Promise((A,z)=>{let w=R(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},H=>{A(),H.resume()});w.on("error",z),w.on("timeout",()=>{w.destroy(),z(new Error("timeout"))}),w.end()})}catch{return G("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
|
|
987
1070
|
|
|
988
1071
|
To fix:
|
|
989
|
-
- Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${
|
|
990
|
-
- Or use a different port: ctx_insight({ port: ${
|
|
1072
|
+
- Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${s}`:`lsof -ti:${s} | xargs kill`}
|
|
1073
|
+
- Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let S=`http://localhost:${s}`,P=u_(S),$=P.ok?"":` (auto-open failed: ${P.reason}; navigate manually)`;return f.push(`Dashboard running at ${S}${$}`),G("ctx_insight",{content:[{type:"text",text:f.map(R=>`- ${R}`).join(`
|
|
991
1074
|
`)+`
|
|
992
1075
|
|
|
993
1076
|
Open: ${S}
|
|
994
|
-
PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&MU().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var DT={};Le(DT,{needsHookNormalization:()=>Ra,normalizeHooksJson:()=>AT,normalizeHooksOnStartup:()=>jU,normalizePluginJson:()=>NT});import{existsSync as RT,readFileSync as CT,writeFileSync as OT}from"node:fs";import{resolve as IT}from"node:path";function Nn(t){return String(t).replace(/\\/g,"/")}function c_(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Nn(t));return e?e[1]:null}function u_(t,e){if(!e||!t||typeof t!="string")return!1;let r=Nn(t);Ol.lastIndex=0;let n;for(;(n=Ol.exec(r))!==null;)if(n[1]!==e)return!0;return!1}function Ra(t,e){return!t||typeof t!="string"?!1:t.includes(Pa)?!0:u_(t,c_(e))}function AT(t,e,r){if(!Ra(t,r))return t;let n=Nn(e),s=Nn(r),o=c_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(Array.isArray(d))for(let l of d){let m=l?.hooks;if(Array.isArray(m))for(let f of m){if(typeof f?.command!="string")continue;let p=f.command.includes(Pa),h=u_(f.command,o);if(!p&&!h)continue;let g=f.command;p&&(g=g.replaceAll(Pa,s),g=g.replace(/^\s*node\s+/,`"${n}" `)),h&&(g=Nn(g).replace(Ol,`context-mode/context-mode/${o}`)),f.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function NT(t,e,r){if(!Ra(t,r))return t;let n=Nn(e),s=Nn(r),o=c_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(!(!d||typeof d!="object")){if(Array.isArray(d.args)){let l=d.args,m=l.map(f=>{if(typeof f!="string")return f;let p=f;return p.includes(Pa)&&(p=p.replaceAll(Pa,s)),u_(p,o)&&(p=Nn(p).replace(Ol,`context-mode/context-mode/${o}`)),p});m.some((f,p)=>f!==l[p])&&(d.args=m,c=!0)}d.command==="node"&&c&&(d.command=n)}}return c?JSON.stringify(i,null,2):t}function jU({pluginRoot:t,nodePath:e,platform:r}){if(!(r!=="win32"&&r!=="linux")&&!(!t||!e)){try{let n=IT(t,"hooks","hooks.json");if(RT(n)){let s=CT(n,"utf-8");if(Ra(s,t)){let o=AT(s,e,t);o!==s&&OT(n,o,"utf-8")}}}catch{}try{let n=IT(t,".claude-plugin","plugin.json");if(RT(n)){let s=CT(n,"utf-8");if(Ra(s,t)){let o=NT(s,e,t);o!==s&&OT(n,o,"utf-8")}}}catch{}}}var Pa,Ol,MT=x(()=>{"use strict";Pa="${CLAUDE_PLUGIN_ROOT}",Ol=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});import{stdout as dP,stdin as pP}from"node:process";import*as rn from"node:readline";var f_=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,h_=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,g_=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var Fl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Oa=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ia=/\t{1,1000}/y,Ul=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"),Aa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,eP=new RegExp("\\p{M}+","gu"),tP={limit:1/0,ellipsis:""},y_=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?y_(s,tP,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,f=r.wideWidth??2,p=0,h=0,g=t.length,y=0,v=!1,_=g,b=Math.max(0,n-o),S=0,T=0,$=0,R=0;e:for(;;){if(T>S||h>=g&&h>p){let N=t.slice(S,T)||t.slice(p,h);y=0;for(let P of N.replaceAll(eP,"")){let C=P.codePointAt(0)||0;if(h_(C)?R=l:g_(C)?R=f:u!==m&&f_(C)?R=u:R=m,$+R>b&&(_=Math.min(_,Math.max(S,p)+y)),$+R>n){v=!0;break e}y+=P.length,$+=R}S=T=0}if(h>=g)break;if(Aa.lastIndex=h,Aa.test(t)){if(y=Aa.lastIndex-h,R=y*m,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/m))),$+R>n){v=!0;break}$+=R,S=p,T=h,h=p=Aa.lastIndex;continue}if(Fl.lastIndex=h,Fl.test(t)){if($+i>b&&(_=Math.min(_,h)),$+i>n){v=!0;break}$+=i,S=p,T=h,h=p=Fl.lastIndex;continue}if(Oa.lastIndex=h,Oa.test(t)){if(y=Oa.lastIndex-h,R=y*a,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/a))),$+R>n){v=!0;break}$+=R,S=p,T=h,h=p=Oa.lastIndex;continue}if(Ia.lastIndex=h,Ia.test(t)){if(y=Ia.lastIndex-h,R=y*c,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/c))),$+R>n){v=!0;break}$+=R,S=p,T=h,h=p=Ia.lastIndex;continue}if(Ul.lastIndex=h,Ul.test(t)){if($+d>b&&(_=Math.min(_,h)),$+d>n){v=!0;break}$+=d,S=p,T=h,h=p=Ul.lastIndex;continue}h+=1}return{width:v?b:$,index:v?_:g,truncated:v,ellipsed:v&&n>=o}},__=y_;var rP={limit:1/0,ellipsis:"",ellipsisWidth:0},nP=(t,e={})=>__(t,rP,e).width,ft=nP;var Na="\x1B",k_="\x9B",sP=39,Zl="\x07",w_="[",oP="]",E_="m",Bl=`${oP}8;;`,v_=new RegExp(`(?:\\${w_}(?<code>\\d+)m|\\${Bl}(?<uri>.*)${Zl})`,"y"),b_=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},x_=t=>`${Na}${w_}${t}${E_}`,S_=t=>`${Na}${Bl}${t}${Zl}`,Hl=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:ft(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=ft(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===Na||l===k_)&&(s=!0,o=e.startsWith(Bl,d+1)),s?o?l===Zl&&(s=!1,o=!1):l===E_&&(s=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},iP=t=>{let e=t.split(" "),r=e.length;for(;r&&!ft(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},aP=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",s,o,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=ft(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=ft(m);if(r.hard&&f>e){let p=e-c,h=1+Math.floor((f-p-1)/e);Math.floor((f-1)/e)<h&&a.push(""),Hl(a,m,e),c=ft(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){Hl(a,m,e),c=ft(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){Hl(a,m,e),c=ft(a.at(-1)??"");continue}a[a.length-1]+=m,c+=f}r.trim!==!1&&(a=a.map(l=>iP(l)));let u=a.join(`
|
|
995
|
-
`),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===
|
|
996
|
-
`){
|
|
997
|
-
`&&(
|
|
998
|
-
`)}var
|
|
1077
|
+
PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return G("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&$H().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var iP={};Le(iP,{needsHookNormalization:()=>za,normalizeHooksJson:()=>oP,normalizeHooksOnStartup:()=>TH,normalizePluginJson:()=>sP});import{existsSync as eP,readFileSync as tP,writeFileSync as rP}from"node:fs";import{resolve as nP}from"node:path";function Fn(t){return String(t).replace(/\\/g,"/")}function y_(t){if(!t)return null;let e=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?:\/|$)/.exec(Fn(t));return e?e[1]:null}function __(t,e){if(!e||!t||typeof t!="string")return!1;let r=Fn(t);Hl.lastIndex=0;let n;for(;(n=Hl.exec(r))!==null;)if(n[1]!==e)return!0;return!1}function za(t,e){return!t||typeof t!="string"?!1:t.includes(ja)?!0:__(t,y_(e))}function oP(t,e,r){if(!za(t,r))return t;let n=Fn(e),o=Fn(r),s=y_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.hooks;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(Array.isArray(d))for(let l of d){let m=l?.hooks;if(Array.isArray(m))for(let f of m){if(typeof f?.command!="string")continue;let p=f.command.includes(ja),h=__(f.command,s);if(!p&&!h)continue;let g=f.command;p&&(g=g.replaceAll(ja,o),g=g.replace(/^\s*node\s+/,`"${n}" `)),h&&(g=Fn(g).replace(Hl,`context-mode/context-mode/${s}`)),f.command=g,c=!0}}}return c?JSON.stringify(i,null,2):t}function sP(t,e,r){if(!za(t,r))return t;let n=Fn(e),o=Fn(r),s=y_(r),i;try{i=JSON.parse(t)}catch{return t}let a=i?.mcpServers;if(!a||typeof a!="object")return t;let c=!1;for(let u of Object.keys(a)){let d=a[u];if(!(!d||typeof d!="object")){if(Array.isArray(d.args)){let l=d.args,m=l.map(f=>{if(typeof f!="string")return f;let p=f;return p.includes(ja)&&(p=p.replaceAll(ja,o)),__(p,s)&&(p=Fn(p).replace(Hl,`context-mode/context-mode/${s}`)),p});m.some((f,p)=>f!==l[p])&&(d.args=m,c=!0)}d.command==="node"&&c&&(d.command=n)}}return c?JSON.stringify(i,null,2):t}function TH({pluginRoot:t,nodePath:e,platform:r}){if(!(r!=="win32"&&r!=="linux")&&!(!t||!e)){try{let n=nP(t,"hooks","hooks.json");if(eP(n)){let o=tP(n,"utf-8");if(za(o,t)){let s=oP(o,e,t);s!==o&&rP(n,s,"utf-8")}}}catch{}try{let n=nP(t,".claude-plugin","plugin.json");if(eP(n)){let o=tP(n,"utf-8");if(za(o,t)){let s=sP(o,e,t);s!==o&&rP(n,s,"utf-8")}}}catch{}}}var ja,Hl,aP=x(()=>{"use strict";ja="${CLAUDE_PLUGIN_ROOT}",Hl=/context-mode\/context-mode\/([0-9]+\.[0-9]+\.[0-9]+)(?=\/)/g});import{stdout as zP,stdin as LP}from"node:process";import*as sn from"node:readline";var k_=t=>t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109,w_=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,E_=t=>t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101632&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129672||t>=129680&&t<=129725||t>=129727&&t<=129733||t>=129742&&t<=129755||t>=129760&&t<=129768||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141;var Yl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ua=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ha=/\t{1,1000}/y,Xl=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"),Za=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,TP=new RegExp("\\p{M}+","gu"),PP={limit:1/0,ellipsis:""},$_=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?$_(o,PP,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,f=r.wideWidth??2,p=0,h=0,g=t.length,y=0,v=!1,_=g,b=Math.max(0,n-s),S=0,P=0,$=0,R=0;e:for(;;){if(P>S||h>=g&&h>p){let A=t.slice(S,P)||t.slice(p,h);y=0;for(let z of A.replaceAll(TP,"")){let w=z.codePointAt(0)||0;if(w_(w)?R=l:E_(w)?R=f:u!==m&&k_(w)?R=u:R=m,$+R>b&&(_=Math.min(_,Math.max(S,p)+y)),$+R>n){v=!0;break e}y+=z.length,$+=R}S=P=0}if(h>=g)break;if(Za.lastIndex=h,Za.test(t)){if(y=Za.lastIndex-h,R=y*m,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/m))),$+R>n){v=!0;break}$+=R,S=p,P=h,h=p=Za.lastIndex;continue}if(Yl.lastIndex=h,Yl.test(t)){if($+i>b&&(_=Math.min(_,h)),$+i>n){v=!0;break}$+=i,S=p,P=h,h=p=Yl.lastIndex;continue}if(Ua.lastIndex=h,Ua.test(t)){if(y=Ua.lastIndex-h,R=y*a,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/a))),$+R>n){v=!0;break}$+=R,S=p,P=h,h=p=Ua.lastIndex;continue}if(Ha.lastIndex=h,Ha.test(t)){if(y=Ha.lastIndex-h,R=y*c,$+R>b&&(_=Math.min(_,h+Math.floor((b-$)/c))),$+R>n){v=!0;break}$+=R,S=p,P=h,h=p=Ha.lastIndex;continue}if(Xl.lastIndex=h,Xl.test(t)){if($+d>b&&(_=Math.min(_,h)),$+d>n){v=!0;break}$+=d,S=p,P=h,h=p=Xl.lastIndex;continue}h+=1}return{width:v?b:$,index:v?_:g,truncated:v,ellipsed:v&&n>=s}},T_=$_;var RP={limit:1/0,ellipsis:"",ellipsisWidth:0},CP=(t,e={})=>T_(t,RP,e).width,ft=CP;var Ba="\x1B",I_="\x9B",OP=39,ed="\x07",A_="[",IP="]",N_="m",td=`${IP}8;;`,P_=new RegExp(`(?:\\${A_}(?<code>\\d+)m|\\${td}(?<uri>.*)${ed})`,"y"),R_=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},C_=t=>`${Ba}${A_}${t}${N_}`,O_=t=>`${Ba}${td}${t}${ed}`,Ql=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:ft(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=ft(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===Ba||l===I_)&&(o=!0,s=e.startsWith(td,d+1)),o?s?l===ed&&(o=!1,s=!1):l===N_&&(o=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},AP=t=>{let e=t.split(" "),r=e.length;for(;r&&!ft(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},NP=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let l=0;l<i.length;l++){let m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=ft(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=ft(m);if(r.hard&&f>e){let p=e-c,h=1+Math.floor((f-p-1)/e);Math.floor((f-1)/e)<h&&a.push(""),Ql(a,m,e),c=ft(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){Ql(a,m,e),c=ft(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){Ql(a,m,e),c=ft(a.at(-1)??"");continue}a[a.length-1]+=m,c+=f}r.trim!==!1&&(a=a.map(l=>AP(l)));let u=a.join(`
|
|
1078
|
+
`),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===Ba||m===I_){P_.lastIndex=l+1;let p=P_.exec(u)?.groups;if(p?.code!==void 0){let h=Number.parseFloat(p.code);o=h===OP?void 0:h}else p?.uri!==void 0&&(s=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
|
|
1079
|
+
`){s&&(n+=O_(""));let f=o?R_(o):void 0;o&&f&&(n+=C_(f))}else m===`
|
|
1080
|
+
`&&(o&&R_(o)&&(n+=C_(o)),s&&(n+=O_(s)))}return n},DP=/\r?\n/;function zo(t,e,r){return String(t).normalize().split(DP).map(n=>NP(n,e,r)).join(`
|
|
1081
|
+
`)}var Xs=Ys(nd(),1);import{ReadStream as M_}from"node:tty";var FP=["up","down","left","right","space","enter","cancel"],UP=["January","February","March","April","May","June","July","August","September","October","November","December"],Er={actions:new Set(FP),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:[...UP],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 j_(t,e){if(typeof t=="string")return Er.aliases.get(t)===e;for(let r of t)if(r!==void 0&&j_(r,e))return!0;return!1}var HP=globalThis.process.platform.startsWith("win");function z_({input:t=LP,output:e=zP,overwrite:r=!0,hideCursor:n=!0}={}){let o=sn.createInterface({input:t,output:e,prompt:"",tabSize:1});sn.emitKeypressEvents(t,o),t instanceof M_&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(j_([u,a,c],"cancel")){n&&e.write(Xs.cursor.show),process.exit(0);return}if(!r)return;sn.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{sn.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(Xs.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(Xs.cursor.show),t instanceof M_&&t.isTTY&&!HP&&t.setRawMode(!1),o.terminal=!1,o.close()}}var od=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ie,stripVTControlCharacters as $Z}from"node:util";import Ut from"node:process";var Qs=Ys(nd(),1);function BP(){return Ut.platform!=="win32"?Ut.env.TERM!=="linux":!!Ut.env.CI||!!Ut.env.WT_SESSION||!!Ut.env.TERMINUS_SUBLIME||Ut.env.ConEmuTask==="{cmd::Cmder}"||Ut.env.TERM_PROGRAM==="Terminus-Sublime"||Ut.env.TERM_PROGRAM==="vscode"||Ut.env.TERM==="xterm-256color"||Ut.env.TERM==="alacritty"||Ut.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var sd=BP(),qP=()=>process.env.CI==="true";var ye=(t,e)=>sd?t:e,CZ=ye("\u25C6","*"),VP=ye("\u25A0","x"),WP=ye("\u25B2","x"),id=ye("\u25C7","o"),GP=ye("\u250C","T"),an=ye("\u2502","|"),KP=ye("\u2514","\u2014"),OZ=ye("\u2510","T"),IZ=ye("\u2518","\u2014"),AZ=ye("\u25CF",">"),NZ=ye("\u25CB"," "),DZ=ye("\u25FB","[\u2022]"),MZ=ye("\u25FC","[+]"),jZ=ye("\u25FB","[ ]"),zZ=ye("\u25AA","\u2022"),L_=ye("\u2500","-"),JP=ye("\u256E","+"),YP=ye("\u251C","+"),XP=ye("\u256F","+"),QP=ye("\u2570","+"),LZ=ye("\u256D","+"),eR=ye("\u25CF","\u2022"),tR=ye("\u25C6","*"),rR=ye("\u25B2","!"),nR=ye("\u25A0","x");var C={message:(t=[],{symbol:e=Ie("gray",an),secondarySymbol:r=Ie("gray",an),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Er.withGuide,c=a?r:"",u=a?`${e} `:"",d=a?`${r} `:"";for(let m=0;m<o;m++)i.push(c);let l=Array.isArray(t)?t:t.split(`
|
|
999
1082
|
`);if(l.length>0){let[m,...f]=l;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of f)p.length>0?i.push(`${d}${p}`):i.push(a?r:"")}n.write(`${i.join(`
|
|
1000
1083
|
`)}
|
|
1001
|
-
`)},info:(t,e)=>{
|
|
1002
|
-
`)},
|
|
1003
|
-
${
|
|
1004
|
-
|
|
1005
|
-
`)};var
|
|
1006
|
-
`),o
|
|
1007
|
-
`).map(
|
|
1008
|
-
`),d=
|
|
1009
|
-
`:"",l=
|
|
1084
|
+
`)},info:(t,e)=>{C.message(t,{...e,symbol:Ie("blue",eR)})},success:(t,e)=>{C.message(t,{...e,symbol:Ie("green",tR)})},step:(t,e)=>{C.message(t,{...e,symbol:Ie("green",id)})},warn:(t,e)=>{C.message(t,{...e,symbol:Ie("yellow",rR)})},warning:(t,e)=>{C.warn(t,e)},error:(t,e)=>{C.message(t,{...e,symbol:Ie("red",nR)})}};var ad=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Er.withGuide?`${Ie("gray",GP)} `:"";r.write(`${n}${t}
|
|
1085
|
+
`)},qa=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??Er.withGuide?`${Ie("gray",an)}
|
|
1086
|
+
${Ie("gray",KP)} `:"";r.write(`${n}${t}
|
|
1087
|
+
|
|
1088
|
+
`)};var oR=t=>Ie("dim",t),sR=(t,e,r)=>{let n={hard:!0,trim:!1},o=zo(t,e,n).split(`
|
|
1089
|
+
`),s=o.reduce((c,u)=>Math.max(ft(u),c),0),i=o.map(r).reduce((c,u)=>Math.max(ft(u),c),0),a=e-(i-s);return zo(t,a,n)},Va=(t="",e="",r)=>{let n=r?.output??Ut.stdout,o=r?.withGuide??Er.withGuide,s=r?.format??oR,i=["",...sR(t,od(n)-6,s).split(`
|
|
1090
|
+
`).map(s),""],a=ft(e),c=Math.max(i.reduce((m,f)=>{let p=ft(f);return p>m?p:m},0),a)+2,u=i.map(m=>`${Ie("gray",an)} ${m}${" ".repeat(c-ft(m))}${Ie("gray",an)}`).join(`
|
|
1091
|
+
`),d=o?`${Ie("gray",an)}
|
|
1092
|
+
`:"",l=o?YP:QP;n.write(`${d}${Ie("green",id)} ${Ie("reset",e)} ${Ie("gray",L_.repeat(Math.max(c-a-1,1))+JP)}
|
|
1010
1093
|
${u}
|
|
1011
|
-
${
|
|
1012
|
-
`)};var
|
|
1013
|
-
`);let
|
|
1014
|
-
`);
|
|
1015
|
-
`);let
|
|
1016
|
-
`):r.write(`${
|
|
1017
|
-
`)),$(),d()};return{start:
|
|
1018
|
-
`)}catch{}return null}return i[1]}catch{return null}}
|
|
1019
|
-
|
|
1094
|
+
${Ie("gray",l+L_.repeat(c+2)+XP)}
|
|
1095
|
+
`)};var iR=t=>Ie("magenta",t),cd=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:o,frames:s=sd?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=sd?80:120,signal:a,...c}={})=>{let u=qP(),d,l,m=!1,f=!1,p="",h,g=performance.now(),y=od(r),v=c?.styleFrame??iR,_=ae=>{let Ze=ae>1?o??Er.messages.error:n??Er.messages.cancel;f=ae===1,m&&(F(Ze,ae),f&&typeof e=="function"&&e())},b=()=>_(2),S=()=>_(1),P=()=>{process.on("uncaughtExceptionMonitor",b),process.on("unhandledRejection",b),process.on("SIGINT",S),process.on("SIGTERM",S),process.on("exit",_),a&&a.addEventListener("abort",S)},$=()=>{process.removeListener("uncaughtExceptionMonitor",b),process.removeListener("unhandledRejection",b),process.removeListener("SIGINT",S),process.removeListener("SIGTERM",S),process.removeListener("exit",_),a&&a.removeEventListener("abort",S)},R=()=>{if(h===void 0)return;u&&r.write(`
|
|
1096
|
+
`);let ae=zo(h,y,{hard:!0,trim:!1}).split(`
|
|
1097
|
+
`);ae.length>1&&r.write(Qs.cursor.up(ae.length-1)),r.write(Qs.cursor.to(0)),r.write(Qs.erase.down())},A=ae=>ae.replace(/\.+$/,""),z=ae=>{let Ze=(performance.now()-ae)/1e3,mt=Math.floor(Ze/60),or=Math.floor(Ze%60);return mt>0?`[${mt}m ${or}s]`:`[${or}s]`},w=c.withGuide??Er.withGuide,H=(ae="")=>{m=!0,d=z_({output:r}),p=A(ae),g=performance.now(),w&&r.write(`${Ie("gray",an)}
|
|
1098
|
+
`);let Ze=0,mt=0;P(),l=setInterval(()=>{if(u&&p===h)return;R(),h=p;let or=v(s[Ze]),Un;if(u)Un=`${or} ${p}...`;else if(t==="timer")Un=`${or} ${p} ${z(g)}`;else{let Fa=".".repeat(Math.floor(mt)).slice(0,3);Un=`${or} ${p}${Fa}`}let La=zo(Un,y,{hard:!0,trim:!1});r.write(La),Ze=Ze+1<s.length?Ze+1:0,mt=mt<4?mt+.125:0},i)},F=(ae="",Ze=0,mt=!1)=>{if(!m)return;m=!1,clearInterval(l),R();let or=Ze===0?Ie("green",id):Ze===1?Ie("red",VP):Ie("red",WP);p=ae??p,mt||(t==="timer"?r.write(`${or} ${p} ${z(g)}
|
|
1099
|
+
`):r.write(`${or} ${p}
|
|
1100
|
+
`)),$(),d()};return{start:H,stop:(ae="")=>F(ae,0),message:(ae="")=>{p=A(ae??p)},cancel:(ae="")=>F(ae,1),error:(ae="")=>F(ae,2),clear:()=>F("",0,!0),get isCancelled(){return f}}},FZ={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var UZ=`${Ie("gray",an)} `;var k=Ys(H_(),1);Xa();pd();hn();Tr();import{execFileSync as Ks,execSync as PH,execFile as RH}from"node:child_process";import{readFileSync as Lr,cpSync as cP,accessSync as uP,existsSync as Oe,readdirSync as CH,rmSync as Js,closeSync as OH,openSync as IH,chmodSync as AH,constants as lP}from"node:fs";import{request as NH}from"node:https";import{resolve as ie,dirname as dP,join as pt}from"node:path";import{tmpdir as DH,devNull as MH,homedir as ql}from"node:os";import{fileURLToPath as jH,pathToFileURL as Vl}from"node:url";import{execFileSync as gO}from"node:child_process";var yO="node.*plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs",_O=`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs' } | Select-Object -ExpandProperty ProcessId`,vO=(t,e)=>gO(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),bO=t=>{try{return process.kill(t,0),!0}catch{return!1}},xO=(t,e)=>{process.kill(t,e)};function SO(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let o=Number.parseInt(n,10);Number.isFinite(o)&&o>0&&e.add(o)}return[...e]}function Db(t){let e=t.platform??process.platform,r=t.runCommand??vO,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",_O]):n=r("pgrep",["-f",yO])}catch{return[]}return SO(n).filter(o=>o!==t.ownPid&&o!==t.ownPpid)}function kO(t){return new Promise(e=>{setTimeout(e,t)})}async function Mb(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??bO,o=t.sendSignal??xO,s={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return s;let i=new Set,a=new Set;for(let l of t.pids){n(l)&&(i.add(l),a.add(l));try{o(l,"SIGTERM")}catch(m){m?.code!=="ESRCH"&&a.delete(l)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await kO(r);for(let l of[...a])n(l)||(a.delete(l),u++)}let d=0;for(let l of a){try{o(l,"SIGKILL")}catch(m){if(m?.code==="ESRCH"){u++;continue}continue}i.has(l)&&d++}return{terminatedBySigterm:u,terminatedBySigkill:d,totalKilled:u+d}}fp();import{existsSync as OO}from"node:fs";import{execSync as IO,execFileSync as j4,spawnSync as z4}from"node:child_process";function Lb({platform:t=process.platform,existsSync:e=OO,exec:r=IO,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let o="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(o))return null;let i=r(`"${o}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
|
|
1101
|
+
`)}catch{}return null}return i[1]}catch{return null}}yn();function zH(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 LH={"claude-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"},"gemini-cli":{beforeagent:"hooks/gemini-cli/beforeagent.mjs",beforetool:"hooks/gemini-cli/beforetool.mjs",aftertool:"hooks/gemini-cli/aftertool.mjs",precompress:"hooks/gemini-cli/precompress.mjs",sessionstart:"hooks/gemini-cli/sessionstart.mjs"},"vscode-copilot":{pretooluse:"hooks/vscode-copilot/pretooluse.mjs",posttooluse:"hooks/vscode-copilot/posttooluse.mjs",precompact:"hooks/vscode-copilot/precompact.mjs",sessionstart:"hooks/vscode-copilot/sessionstart.mjs"},cursor:{pretooluse:"hooks/cursor/pretooluse.mjs",posttooluse:"hooks/cursor/posttooluse.mjs",sessionstart:"hooks/cursor/sessionstart.mjs",stop:"hooks/cursor/stop.mjs",afteragentresponse:"hooks/cursor/afteragentresponse.mjs"},codex:{pretooluse:"hooks/codex/pretooluse.mjs",posttooluse:"hooks/codex/posttooluse.mjs",precompact:"hooks/codex/precompact.mjs",sessionstart:"hooks/codex/sessionstart.mjs",userpromptsubmit:"hooks/codex/userpromptsubmit.mjs",stop:"hooks/codex/stop.mjs"},kiro:{pretooluse:"hooks/kiro/pretooluse.mjs",posttooluse:"hooks/kiro/posttooluse.mjs"},"jetbrains-copilot":{pretooluse:"hooks/jetbrains-copilot/pretooluse.mjs",posttooluse:"hooks/jetbrains-copilot/posttooluse.mjs",precompact:"hooks/jetbrains-copilot/precompact.mjs",sessionstart:"hooks/jetbrains-copilot/sessionstart.mjs"},"qwen-code":{pretooluse:"hooks/pretooluse.mjs",posttooluse:"hooks/posttooluse.mjs",precompact:"hooks/precompact.mjs",sessionstart:"hooks/sessionstart.mjs",userpromptsubmit:"hooks/userpromptsubmit.mjs"}};async function FH(t,e){try{OH(2),IH(MH,"w")}catch{process.stderr.write=(()=>!0)}let r=LH[t]?.[e];r||process.exit(1);let n=jo();await import(Vl(pt(n,r)).href)}var UH=new Set(["opencode","kilo"]),pP=t=>t?UH.has(t):!1,St=process.argv.slice(2);function HH(){console.log(["Usage:"," context-mode Start MCP server (stdio)"," 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","","Environment:"," CONTEXT_MODE_DIR=/absolute/path Override sessions/content storage root; empty is ignored, non-empty must be absolute"].join(`
|
|
1102
|
+
`))}if(St[0]==="--help"||St[0]==="-h"||St[0]==="help")HH();else if(St[0]==="doctor")GH().then(t=>process.exit(t));else if(St[0]==="upgrade"){let t=St.indexOf("--platform"),e=t>=0&&St[t+1]?St[t+1]:void 0;JH(e?{platform:e}:void 0).catch(r=>{let n=r instanceof Error?r.message:String(r);C.error(k.default.red(n)),process.exit(1)})}else St[0]==="hook"?FH(St[1],St[2]):St[0]==="insight"?KH(St[1]?Number(St[1]):4747):St[0]==="statusline"?YH():Promise.resolve().then(()=>(QT(),XT));function DJ(t){return t.replace(/\\/g,"/")}var Wl=process.platform==="win32";function Zl(t,e={}){Ks(Wl?"npm.cmd":"npm",t,{...e,...Wl?{shell:!0}:{}})}function ZH(t,e={}){let r={...e,...Wl?{shell:!0}:{}};PH(Wl?t.replace(/^npm /,"npm.cmd "):t,r)}function BH(t,e=process.platform,r=RH){let n={stdio:"ignore"},o=()=>console.error(`
|
|
1103
|
+
Could not auto-open browser. Open manually: ${t}`),s=zH(t,e),i=!1;for(let{cmd:a,args:c}of s)try{r(a,c,n),i=!0;break}catch{}i||o()}function qH(){let t=jH(import.meta.url),e=dP(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ie(e,".."):e}function VH(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ie(r,t,...e):ie(ql(),"AppData","Local",t,...e)}return ie(ql(),".cache",t,...e)}function jo(){let t=wt().platform;return pP(t)?VH(t):qH()}function mP(){try{return JSON.parse(Lr(ie(jo(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function WH(){return new Promise(t=>{let e=NH("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Bl(t){return t.envVar?t.envVar:"adapter default"}function v_(t){try{return mn(t),C.success(k.default.green(`Storage ${t.kind}: PASS`)+k.default.dim(` \u2014 ${t.path} (${Bl(t)})`)),0}catch(e){if(e instanceof ar)return C.error(k.default.red(`Storage ${t.kind}: FAIL`)+k.default.dim(` \u2014 ${ai(e)}`)),1;throw e}}async function GH(){process.stdout.isTTY&&console.clear();let t=wt(),e=await gi(t.platform);ad(k.default.bgMagenta(k.default.white(" context-mode doctor "))),C.info(`Platform: ${k.default.cyan(e.name)}`+k.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0;try{let y=pn(()=>e.getSessionDir()),v=qo(()=>y.path),_=ii(()=>y.path);Va([`sessions: ${y.path} (${Bl(y)})`,`content: ${v.path} (${Bl(v)})`,`stats: ${_.path} (${Bl(_)})`].join(`
|
|
1104
|
+
`),"Storage paths"),r+=v_(y),r+=v_(v),r+=v_(_)}catch(y){if(y instanceof ar)r++,C.error(k.default.red(`Storage ${y.kind}: FAIL`)+k.default.dim(` \u2014 ${ai(y)}`));else throw y}let n=cd();n.start("Running diagnostics");let o,s;try{o=Lo(),s=Ya(o)}catch{return n.stop("Diagnostics partial"),C.warn(k.default.yellow("Could not detect runtimes")+k.default.dim(" \u2014 module may be missing, restart session after upgrade")),qa(k.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Va(Ja(o),"Runtimes");{let{hasModernSqlite:y}=await Promise.resolve().then(()=>(ln(),hd));process.platform==="linux"&&!y()&&!Hn()&&(r++,C.error(k.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+k.default.dim(`
|
|
1020
1105
|
context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
|
|
1021
1106
|
V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
|
|
1022
1107
|
Refs: https://github.com/nodejs/node/issues/62515
|
|
1023
1108
|
https://github.com/mksglu/context-mode/issues/564
|
|
1024
1109
|
Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
|
|
1025
|
-
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}
|
|
1026
|
-
Run: ${y.fix}`):"")):
|
|
1027
|
-
Run: ${y.fix}`):""));
|
|
1110
|
+
Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}Hn()?C.success(k.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):C.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?(r++,C.error(k.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+k.default.dim(` \u2014 ${s.join(", ")||"none"}`))):C.info(`Language coverage: ${s.length}/${i} (${a}%)`+k.default.dim(` \u2014 ${s.join(", ")}`)),C.step("Testing server initialization...");try{let{PolyglotExecutor:y}=await Promise.resolve().then(()=>(jy(),k$)),_=await new y({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(_.exitCode===0&&_.stdout.trim()==="ok")C.success(k.default.green("Server test: PASS"));else{r++;let b=_.stderr?.trim()?` (${_.stderr.trim().slice(0,200)})`:"";C.error(k.default.red("Server test: FAIL")+` \u2014 exit ${_.exitCode}${b}`)}}catch(y){let v=y instanceof Error?y.message:String(y);v.includes("Cannot find module")||v.includes("MODULE_NOT_FOUND")?C.warn(k.default.yellow("Server test: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,C.error(k.default.red("Server test: FAIL")+` \u2014 ${v}`))}C.step(`Checking ${e.name} hooks configuration...`);let c=jo(),u=e.validateHooks(c);for(let y of u)y.status==="pass"?C.success(k.default.green(`${y.check}: PASS`)+` \u2014 ${y.message}`):y.status==="warn"?C.warn(k.default.yellow(`${y.check}: WARN`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1111
|
+
Run: ${y.fix}`):"")):C.error(k.default.red(`${y.check}: FAIL`)+` \u2014 ${y.message}`+(y.fix?k.default.dim(`
|
|
1112
|
+
Run: ${y.fix}`):""));C.step("Checking hook scripts...");let d=e.getHealthChecks?.(c)??[];if(d.length>0)for(let y of d){let v=y.check();v.status==="OK"?C.success(k.default.green(`${y.name}: PASS`)+(v.detail?k.default.dim(` \u2014 ${v.detail}`):"")):C.error(k.default.red(`${y.name}: FAIL`)+(v.detail?k.default.dim(` \u2014 ${v.detail}`):""))}else{let y=ec(e,c);if(y.length===0)C.success(k.default.green("Hook scripts: PASS")+k.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let v of y){let _=ie(c,v);try{uP(_,lP.R_OK),C.success(k.default.green("Hook script exists: PASS")+k.default.dim(` \u2014 ${_}`))}catch{C.error(k.default.red("Hook script exists: FAIL")+k.default.dim(` \u2014 not found at ${_}`))}}}C.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?C.success(k.default.green("Plugin enabled: PASS")+k.default.dim(` \u2014 ${l.message}`)):C.warn(k.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),C.step("Checking team-shared hook configs in your workspace...");{let S=function($){return!!($.startsWith("/")||/^[A-Za-z]:[/\\]/.test($)||$.includes("\\\\")||$.includes("fnm_multishells")||$.includes("process.execPath"))},P=function($,R){if(typeof $=="string")R($);else if(Array.isArray($))for(let A of $)P(A,R);else if($&&typeof $=="object")for(let A of Object.values($))P(A,R)};var h=S,g=P;let y=process.cwd(),v=[".github/hooks/context-mode.json",".cursor/hooks.json",".jetbrains/copilot/hooks.json"],_=0,b=0;for(let $ of v){let R=ie(y,$);if(Oe(R)){b++;try{let A=JSON.parse(Lr(R,"utf-8")),z=[];if(P(A,w=>{S(w)&&z.push(w)}),z.length>0){r++,_++;let w=z[0].length>100?z[0].slice(0,97)+"...":z[0];C.error(k.default.red("Hook config: FAIL")+` \u2014 ${$} has your machine's local paths baked in`+k.default.dim(`
|
|
1028
1113
|
This file is committed to git, so teammates and CI will get your path and the hooks will break for them.
|
|
1029
|
-
Found ${
|
|
1114
|
+
Found ${z.length} hard-coded path(s), e.g.: ${w}
|
|
1030
1115
|
Fix: run /context-mode:ctx-upgrade \u2014 it rewrites the file to a portable form that works on every machine.
|
|
1031
|
-
Details: https://github.com/mksglu/context-mode/issues/613`))}else
|
|
1116
|
+
Details: https://github.com/mksglu/context-mode/issues/613`))}else C.success(k.default.green("Hook config: PASS")+k.default.dim(` \u2014 ${$} is portable (no hard-coded paths)`))}catch(A){let z=A instanceof Error?A.message:String(A);C.warn(k.default.yellow("Hook config: WARN")+` \u2014 ${$} is not valid JSON`+k.default.dim(`
|
|
1032
1117
|
Doctor cannot scan it for portability issues until the file parses.
|
|
1033
1118
|
Fix: open the file and check it in a JSON validator, or delete it and run /context-mode:ctx-upgrade to regenerate.
|
|
1034
|
-
Parser said: ${
|
|
1119
|
+
Parser said: ${z.slice(0,160)}`))}}}b===0&&C.info(k.default.dim("Hook config: SKIP \u2014 no team-shared hook configs found in this workspace"))}C.step("Checking for leftover .mcp.json files from older versions...");{let y=pt(ql(),".claude","plugins","cache","context-mode","context-mode");if(!Oe(y))C.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 v=0,_=[];try{let b=CH(y);for(let S of b){let P=pt(y,S,".mcp.json");Oe(P)&&(v++,_.length<5&&_.push(S))}}catch(b){let S=b instanceof Error?b.message:String(b);C.warn(k.default.yellow("Leftover .mcp.json check: WARN")+" \u2014 could not read the plugin cache directory"+k.default.dim(`
|
|
1035
1120
|
Path: ${y}
|
|
1036
1121
|
Reason: ${S.slice(0,160)}
|
|
1037
|
-
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),v=0}v===0?
|
|
1122
|
+
Fix: check that the directory is readable, then re-run doctor. If the issue persists, run /context-mode:ctx-upgrade.`)),v=0}v===0?C.success(k.default.green("Leftover .mcp.json check: PASS")+k.default.dim(" \u2014 no old .mcp.json files in the plugin cache")):C.warn(k.default.yellow("Leftover .mcp.json check: WARN")+` \u2014 found ${v} old .mcp.json file(s) left over from previous context-mode versions`+k.default.dim(`
|
|
1038
1123
|
These are harmless but should be cleaned up so they cannot confuse Claude Code after an auto-update.
|
|
1039
1124
|
Versions affected: ${_.join(", ")}${v>_.length?", ...":""}
|
|
1040
1125
|
Fix: run /context-mode:ctx-upgrade \u2014 it sweeps these files automatically on the next run.
|
|
1041
|
-
Details: https://github.com/mksglu/context-mode/issues/609`))}}
|
|
1126
|
+
Details: https://github.com/mksglu/context-mode/issues/609`))}}C.step("Checking FTS5 / SQLite...");try{let y=(await Promise.resolve().then(()=>(ln(),hd))).loadDatabase(),v=new y(":memory:");v.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),v.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let _=v.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();v.close(),_&&_.content==="hello world"?C.success(k.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,C.error(k.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(y){let v=y instanceof Error?y.message:String(y),_=jo(),b=ie(_,"node_modules","better-sqlite3");!Oe(b)?(r++,C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+k.default.dim(" \u2014 package-missing")+k.default.dim(`
|
|
1042
1127
|
Path: ${b}
|
|
1043
1128
|
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).
|
|
1044
1129
|
Try (primary): cd "${_}" && npm install better-sqlite3 --no-optional
|
|
1045
|
-
Try (fallback): /context-mode:ctx-upgrade`))):v.includes("Cannot find module")||v.includes("MODULE_NOT_FOUND")?
|
|
1130
|
+
Try (fallback): /context-mode:ctx-upgrade`))):v.includes("Cannot find module")||v.includes("MODULE_NOT_FOUND")?C.warn(k.default.yellow("FTS5 / better-sqlite3: SKIP")+k.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(v)||/bindings\.node/i.test(v)||/\bbindings\b/i.test(v))&&process.platform==="win32"?C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${v}`+k.default.dim(`
|
|
1046
1131
|
Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
|
|
1047
1132
|
Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
|
|
1048
|
-
Try (fallback): npm rebuild better-sqlite3`)):
|
|
1049
|
-
Try: npm rebuild better-sqlite3`)))}
|
|
1050
|
-
Run: /context-mode:ctx-upgrade`)),p==="not installed"?
|
|
1051
|
-
Run: /context-mode:ctx-upgrade`)):
|
|
1133
|
+
Try (fallback): npm rebuild better-sqlite3`)):C.error(k.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${v}`+k.default.dim(`
|
|
1134
|
+
Try: npm rebuild better-sqlite3`)))}C.step("Checking versions...");let m=mP(),f=await WH(),p=e.getInstalledVersion();return f==="unknown"?C.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===f?C.success(k.default.green("npm (MCP): PASS")+` \u2014 v${m}`):C.warn(k.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${f}`+k.default.dim(`
|
|
1135
|
+
Run: /context-mode:ctx-upgrade`)),p==="standalone"?C.info(k.default.dim(`${e.name}: standalone MCP mode`)+" \u2014 no platform plugin version to compare"):p==="not installed"?C.info(k.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&p===f?C.success(k.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):f!=="unknown"?C.warn(k.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${f}`+k.default.dim(`
|
|
1136
|
+
Run: /context-mode:ctx-upgrade`)):C.info(`${e.name}: v${p}`+k.default.dim(" \u2014 could not verify against npm registry")),r>0?(qa(k.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(qa(s.length>=4?k.default.green("Diagnostics complete!"):k.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function KH(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:o,cpSync:s}=await import("node:fs"),i=ie(jo(),"insight"),a=wt(),c=await gi(a.platform),u=mn(pn(()=>c.getSessionDir())),d=mn(qo(()=>u)),l=pt(dP(u),"insight-cache");Oe(pt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),o(l,{recursive:!0});let m=n(pt(i,"server.mjs")).mtimeMs,f=Oe(pt(l,"server.mjs"))?n(pt(l,"server.mjs")).mtimeMs:0;if(m>f&&(console.log("Copying Insight source..."),s(i,l,{recursive:!0,force:!0})),!Oe(pt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{ZH("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{Js(pt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!Oe(pt(l,"node_modules","vite"))||!Oe(pt(l,"node_modules","better-sqlite3")))throw Js(pt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
|
|
1052
1137
|
context-mode Insight
|
|
1053
1138
|
${p}
|
|
1054
|
-
`);let h=r("node",[
|
|
1139
|
+
`);let h=r("node",[pt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,v)=>{let _=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},b=>{y(),b.resume()});_.on("error",v),_.on("timeout",()=>{_.destroy(),v(new Error("timeout"))}),_.end()})}catch{console.error(`
|
|
1055
1140
|
Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
|
|
1056
|
-
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}
|
|
1057
|
-
Insight error: ${r}`),process.exit(1)}}async function
|
|
1058
|
-
Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let S=ie(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!
|
|
1059
|
-
Path: ${S}`)+
|
|
1060
|
-
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+
|
|
1061
|
-
Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+
|
|
1062
|
-
Try (fallback): /context-mode:ctx-doctor`)))
|
|
1063
|
-
`),"Changes Applied"):
|
|
1141
|
+
To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}BH(p),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
|
|
1142
|
+
Insight error: ${r}`),process.exit(1)}}async function JH(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:wt(),r=await gi(e.platform);ad(k.default.bgCyan(k.default.black(" context-mode upgrade "))),C.info(`Platform: ${k.default.cyan(r.name)}`+k.default.dim(` (${e.confidence} confidence)`));let n=jo(),o=[],s=cd(),i=ie(qe(),"plugins","marketplaces","context-mode");if(Oe(pt(i,".git"))){s.start("Syncing marketplace clone");try{Ks("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")),C.info(k.default.dim(` Run manually: git -C "${i}" stash && git pull --ff-only`))):(Ks("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),Ks("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(m){let f=m instanceof Error?m.message:String(m);s.stop(k.default.yellow("Marketplace sync skipped")),C.warn(k.default.yellow("git refresh on marketplace failed")+` \u2014 ${f}`),C.info(k.default.dim(" Continuing \u2014 cache dir update will still happen."))}}C.step("Pulling latest from GitHub...");let a=mP(),c=pt(DH(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{Ks("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let m=c,p=JSON.parse(Lr(ie(m,"package.json"),"utf-8")).version??"unknown";if(p===a)C.success(k.default.green("Already on latest")+` \u2014 v${a}`),Js(c,{recursive:!0,force:!0});else{C.info(`Update available: ${k.default.yellow("v"+a)} \u2192 ${k.default.green("v"+p)}`);try{let b=Db({ownPid:process.pid,ownPpid:process.ppid});if(b.length>0){let S=await Mb({pids:b});if(S.totalKilled>0){let P=S.totalKilled===1?"sibling MCP server":"sibling MCP servers";C.info(k.default.dim(`Stopped ${S.totalKilled} ${P} (SIGTERM: ${S.terminatedBySigterm}, SIGKILL: ${S.terminatedBySigkill})`))}}}catch{}s.start("Installing dependencies & building");let h=Lb();Zl(["install","--no-audit","--no-fund"],{cwd:m,stdio:"pipe",timeout:12e4,...h?{env:{...process.env,npm_config_msvs_version:h}}:{}}),Zl(["run","build"],{cwd:m,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let y=[...JSON.parse(Lr(ie(m,"package.json"),"utf-8")).files||[],"src","package.json"];for(let b of y)try{Js(ie(n,b),{recursive:!0,force:!0}),cP(ie(m,b),ie(n,b),{recursive:!0})}catch{}try{(await Promise.resolve().then(()=>(aP(),iP))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}s.stop(k.default.green(`Updated in-place to v${p}`));let v=ie(n,".claude-plugin","plugin.json"),_=null;try{let b=JSON.parse(Lr(v,"utf-8"));b&&typeof b.version=="string"&&(_=b.version)}catch{}if(_!==p)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${_??"<missing>"}" but newVersion is "${p}". Refusing to bump registry.`);r.updatePluginRegistry(n,p),C.info(k.default.dim(" Registry synced to "+n));try{let b=ie(qe(),"plugins","installed_plugins.json");if(Oe(b)){let P=JSON.parse(Lr(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let $ of P){let R=$?.installPath;if(typeof R!="string"||!R)continue;if(!Oe(R))throw new Error(`installPath does not exist on disk: ${R}`);let A=ie(R,".claude-plugin","plugin.json");if(!Oe(A))throw new Error(`missing plugin.json manifest at ${A}`);let z=JSON.parse(Lr(A,"utf-8"));if(z?.version!==$.version)throw new Error(`version mismatch \u2014 registry says "${$.version}" but ${A} says "${z?.version}"`)}}}catch(b){let S=b instanceof Error?b.message:String(b);throw new Error(`Registry consistency check failed: ${S}`)}try{let b=ie(qe(),"plugins","cache"),S="context-mode@context-mode",P=bc({pluginRoot:n,pluginCacheRoot:b,pluginKey:S});if(P&&P.error)throw new Error(P.error);let $=bc({pluginRoot:n,pluginCacheRoot:b,pluginKey:S});if($&&Array.isArray($.healed)&&$.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${$.healed.join(",")})`)}catch(b){let S=b instanceof Error?b.message:String(b);throw new Error(`plugin.json drift check failed: ${S}`)}try{let b=ie(qe(),"plugins","cache"),S="context-mode@context-mode",P=xc({pluginCacheRoot:b,pluginKey:S});P&&P.removed&&P.removed.length>0&&C.info(k.default.dim(` Swept ${P.removed.length} stale .mcp.json file(s) from cache`));let $=xc({pluginCacheRoot:b,pluginKey:S});if($&&Array.isArray($.removed)&&$.removed.length>0)throw new Error(`.mcp.json sweep drift: ${$.removed.length} file(s) still present after first pass`)}catch(b){let S=b instanceof Error?b.message:String(b);throw new Error(`.mcp.json sweep check failed: ${S}`)}try{let{healClaudeJsonMcpArgs:b}=await Promise.resolve().then(()=>(fp(),zb)),S=ie(ql(),".claude.json"),P=ie(qe(),"plugins","cache","context-mode","context-mode"),$=b({dotClaudeJsonPath:S,pluginCacheParent:P,newPluginRoot:n});$.healed&&$.healed.length>0&&C.info(k.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+p))}catch{}try{let b=ie(i,".claude-plugin","plugin.json");if(Oe(b)){let S=JSON.parse(Lr(b,"utf-8"));S?.version!==p&&(C.warn(k.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${S?.version}" but expected "${p}"`),C.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"),Zl(["install","--production","--no-audit","--no-fund"],{cwd:n,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),!pP(e.platform)){s.start("Verifying native addon ABI");let b=ie(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let P=ie(n,"hooks","ensure-deps.mjs");if(!Oe(P))throw new Error(`missing ${P}`);await import(`${Vl(P).href}?upgrade=${Date.now()}`),Oe(b)?(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")),C.warn(k.default.dim(` Try manually: cd "${n}" && npm rebuild better-sqlite3`)))}catch(P){let $=P instanceof Error?P.message:String(P);s.stop(k.default.yellow("Native addon ABI bootstrap unavailable")),C.warn(k.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${$}`+k.default.dim(`
|
|
1143
|
+
Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let S=ie(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!Oe(S))try{let P=ie(n,"scripts","heal-better-sqlite3.mjs");if(Oe(P)){let $=await import(`${Vl(P).href}?upgrade=${Date.now()}`);typeof $.healBetterSqlite3Binding=="function"&&$.healBetterSqlite3Binding(n)}}catch{}Oe(S)||(process.exitCode=1,C.error(k.default.red("better-sqlite3 native binding: MISSING")+k.default.dim(`
|
|
1144
|
+
Path: ${S}`)+k.default.dim(`
|
|
1145
|
+
Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+k.default.dim(`
|
|
1146
|
+
Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+k.default.dim(`
|
|
1147
|
+
Try (fallback): /context-mode:ctx-doctor`))),s.start("Updating npm global package");try{Zl(["install","-g",n,"--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")),C.info(k.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}}Js(c,{recursive:!0,force:!0});try{let b=ie(qe(),"plugins","installed_plugins.json");if(Oe(b)){let P=JSON.parse(Lr(b,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(P))for(let $ of P){let R=$.installPath;if(R&&R!==n&&Oe(R)){let A=ie(m,"skills");Oe(A)&&(cP(A,ie(R,"skills"),{recursive:!0}),o.push("Synced skills to active install path"))}}}}catch{}o.push(`Updated v${a} \u2192 v${p}`),C.success(k.default.green("Plugin reinstalled from GitHub!")+k.default.dim(` \u2014 v${p}`))}}catch(m){let f=m instanceof Error?m.message:String(m);s.stop(k.default.red("Update failed")),C.error(k.default.red("GitHub pull failed")+` \u2014 ${f}`),process.exitCode=1,C.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.")),C.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{Js(c,{recursive:!0,force:!0})}catch{}}C.step(`Backing up ${r.name} settings...`);let u=r.backupSettings();u?.endsWith(".bak")?(C.success(k.default.green("Backup created")+k.default.dim(" -> "+u)),o.push("Backed up settings")):u?C.success(k.default.green("Backup skipped")+k.default.dim(" \u2014 no changes needed")):C.warn(k.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),C.step(`Configuring ${r.name} hooks...`);try{let m=r.configureAllHooks(n);for(let f of m)C.info(k.default.dim(` ${f}`)),o.push(f);C.success(k.default.green("Hooks configured")+k.default.dim(` \u2014 ${r.name}`))}catch(m){let f=m instanceof Error?m.message:String(m);throw new Error(`Hook configuration failed: ${f}`)}C.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let m of["build/cli.js","cli.bundle.mjs"]){let f=ie(n,m);try{uP(f,lP.F_OK),AH(f,493),d.push(f)}catch{}}d.length>0?(C.success(k.default.green("Permissions set")+k.default.dim(` \u2014 ${d.length} hook script(s)`)),o.push(`Set ${d.length} hook scripts as executable`)):C.error(k.default.red("No hook scripts found")+k.default.dim(" \u2014 expected in "+ie(n,"hooks"))),o.length>0?Va(o.map(m=>k.default.green(" + ")+m).join(`
|
|
1148
|
+
`),"Changes Applied"):C.info(k.default.dim("No changes were needed."));let l=r.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";C.warn(k.default.yellow("Restart for new MCP tools to take effect.")+k.default.dim(` (${l})`)),C.step("Running doctor to verify..."),console.log();try{let m=ie(n,"cli.bundle.mjs"),f=ie(n,"build","cli.js"),p=Oe(m)?m:f;Ks("node",[p,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}catch{C.warn(k.default.yellow("Doctor had warnings")+k.default.dim(` \u2014 restart your ${r.name} session to pick up the new version`))}}function YH(){let t=qe(),e=[ie(jo(),"bin","statusline.mjs"),ie(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ie(t,"plugins","installed_plugins.json");if(Oe(n)){let s=JSON.parse(Lr(n,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(s))for(let i of s){let a=i?.installPath;typeof a=="string"&&a&&e.push(ie(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>Oe(n));r||process.exit(0),import(Vl(r).href).catch(()=>{process.exit(0)})}export{ZH as npmExec,Zl as npmExecFile,BH as openInBrowser,DJ as toUnixPath};
|