@gabrywu/knowledge-bank 0.1.2-alpha.227 → 0.1.2-alpha.252

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/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{Command as e}from"commander";import t,{dirname as n}from"path";import r from"os";import s,{readFileSync as a,existsSync as o,mkdirSync as i,writeFileSync as c}from"fs";import{exec as u}from"child_process";import{fileURLToPath as d}from"url";import l from"better-sqlite3";import p from"simple-git";import{cwd as h}from"process";import{ZodOptional as m,z as f}from"zod";import g from"node:process";import y from"express";import _ from"express-ejs-layouts";import v from"markdown-it";const w=["personal","project","organization"],b=["developer","architect","reviewer","ai"],k=["code_pattern","tool_usage","architecture","config","pitfall","api_usage","exploration"],$={DRAFT:"draft",SUGGESTED:"suggested",VERIFIED:"verified"},S={knowledge_item:`\n CREATE TABLE IF NOT EXISTS knowledge_item (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n\n -- Basic information\n title TEXT NOT NULL,\n summary TEXT NOT NULL,\n content TEXT NOT NULL,\n\n -- Classification dimensions\n scope TEXT NOT NULL CHECK(scope IN (${w.map(e=>`'${e}'`).join(", ")})),\n source_type TEXT NOT NULL CHECK(source_type IN (${b.map(e=>`'${e}'`).join(", ")})),\n knowledge_type TEXT NOT NULL ,\n status TEXT NOT NULL DEFAULT '${$.DRAFT}' CHECK(status IN (${Object.values($).map(e=>`'${e}'`).join(", ")})),\n\n -- Source tracking\n source_file TEXT,\n contributor TEXT,\n\n -- Timestamps\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n `,session:"\n CREATE TABLE IF NOT EXISTS session (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT UNIQUE NOT NULL,\n\n -- Session basic information\n cwd TEXT NOT NULL,\n cwd_updated_at INTEGER NOT NULL,\n git_url TEXT,\n git_branch TEXT,\n git_commit_id TEXT,\n user_name TEXT,\n\n -- Environment information (stored as JSON)\n env TEXT,\n\n -- Configuration information (stored as JSON)\n config TEXT,\n\n -- Session duration (seconds, calculated on session end)\n duration INTEGER,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n ",session_event:"\n CREATE TABLE IF NOT EXISTS session_event (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n\n -- Hook information\n name TEXT NOT NULL,\n input TEXT NOT NULL,\n output TEXT,\n exit_code INTEGER NOT NULL DEFAULT 0,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n ",knowledge_item_fts:"\n CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_item_fts USING fts5(\n title, summary, content,\n content='knowledge_item',\n content_rowid='id',\n tokenize='trigram'\n )\n "},E={knowledge_item_fts_insert:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_insert AFTER INSERT ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n ",knowledge_item_fts_delete:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_delete AFTER DELETE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n END\n ",knowledge_item_fts_update:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_update AFTER UPDATE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n "},T={idx_knowledge_scope:"CREATE INDEX IF NOT EXISTS idx_knowledge_scope ON knowledge_item(scope)",idx_knowledge_type:"CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_item(knowledge_type)",idx_knowledge_status:"CREATE INDEX IF NOT EXISTS idx_knowledge_status ON knowledge_item(status)",idx_knowledge_session:"CREATE INDEX IF NOT EXISTS idx_knowledge_session ON knowledge_item(session_id)",idx_session_id:"CREATE INDEX IF NOT EXISTS idx_session_id ON session(session_id)",idx_session_cwd:"CREATE INDEX IF NOT EXISTS idx_session_cwd ON session(cwd)",idx_session_event_session:"CREATE INDEX IF NOT EXISTS idx_session_event_session ON session_event(session_id)",idx_session_event_name:"CREATE INDEX IF NOT EXISTS idx_session_event_name ON session_event(name)"};function x(e){Object.values(S).forEach(t=>{e.prepare(t).run()}),Object.values(T).forEach(t=>{e.prepare(t).run()}),Object.values(E).forEach(t=>{e.prepare(t).run()})}const O={logging:{level:"DEBUG"},db:{file:t.join(r.homedir(),".knowledge-bank","knowledge.db"),configs:["journal_mode = WAL","foreign_keys = ON"]},tmp:t.join(r.homedir(),".knowledge-bank","tmp")};let N=null;function I(){if(null===N){const e=process.env.KNOWLEDGE_CONF_DIR||t.join(r.homedir(),".knowledge-bank"),n=t.join(e,"config.json");N={...O,...s.existsSync(n)?JSON.parse(s.readFileSync(n,"utf-8")):{}}}return N}const P=I(),R={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},C=Object.values(R);class j{constructor(e,n){this.loggerName=n;const a=P.logging.path||t.join(r.homedir(),".knowledge-bank","logs");s.mkdirSync(a,{recursive:!0}),this.loggerFile=t.join(a,`${e}.log`),this.logLevel=P.logging.level.toUpperCase()||R.INFO}formatMessage(e,t,n=null){const r=`${(new Date).toISOString().replace("T","-").split(".")[0]} ${this.loggerName} ${e}: ${t}`;return null===n?r:`${r} - ${JSON.stringify(n)}`}isLogLevelEnabled(e){const t=C.indexOf(this.logLevel);return C.indexOf(e)>=t}writeMessage(e,t,n){if(this.isLogLevelEnabled(e)){const r=this.formatMessage(e,t,n);s.appendFileSync(this.loggerFile,`${r}\n`,"utf8")}}logInfo(e,t=null){this.writeMessage(R.INFO,e,t)}logError(e,t=null){if(t instanceof Error){const n={message:t.message,stack:t.stack,name:t.name,...t.cause&&{cause:t.cause},...Object.getOwnPropertyNames(t).reduce((e,n)=>(["message","stack","name"].includes(n)||(e[n]=t[n]),e),{})};this.writeMessage(R.ERROR,e,n)}else this.writeMessage(R.ERROR,e,t)}logWarn(e,t=null){this.writeMessage(R.WARN,e,t)}logDebug(e,t=null){this.writeMessage(R.DEBUG,e,t)}}function z(e,t){return new j(e,t)}class A{constructor(e={}){this.isDev=void 0!==e.isDev?e.isDev:this.detectEnvironment(),this._rootDir=null,this._packageFile=null,this._marketplaceRepo=null}detectEnvironment(){const e=d(import.meta.url),n=t.dirname(e),r=s.existsSync(t.join(n,"..","..","src")),a=n.includes("dist"),o=t.join(n,"..","..","package.json"),i=t.join(n,"..","package.json");return r&&!a||!s.existsSync(i)&&s.existsSync(o)}getRootDir(){if(this._rootDir)return this._rootDir;const e=d(import.meta.url),n=t.dirname(e);if(this.isDev)this._rootDir=t.join(n,"..","..");else if(n.includes("dist")){const e=n.indexOf("dist");this._rootDir=n.substring(0,e-1)}else if(n.includes("src"))this._rootDir=t.join(n,"..","..");else{let e=n;for(;e!==t.dirname(e);){const n=t.join(e,"package.json");if(s.existsSync(n)){this._rootDir=e;break}e=t.dirname(e)}this._rootDir||(this._rootDir=t.dirname(n))}return this._rootDir}getPackageFile(){if(this._packageFile)return this._packageFile;const e=this.getRootDir();if(this._packageFile=t.join(e,"package.json"),!s.existsSync(this._packageFile)){const e=t.join(process.cwd(),"package.json");if(!s.existsSync(e))throw new Error(`package.json not found at ${this._packageFile} or ${e}`);this._packageFile=e}return this._packageFile}getMarketplaceRepo(){if(this._marketplaceRepo)return this._marketplaceRepo;const e=this.getRootDir();if(this.isDev){const n=t.join(e,"dist","claude-marketplace"),r=t.join(e,"src","claude-marketplace");if(s.existsSync(n))this._marketplaceRepo=n;else{if(!s.existsSync(r))throw new Error(`Marketplace directory not found at ${n} or ${r}`);this._marketplaceRepo=r}}else if(this._marketplaceRepo=t.join(e,"dist","claude-marketplace"),!s.existsSync(this._marketplaceRepo))throw new Error(`Marketplace directory not found at ${this._marketplaceRepo}`);return this._marketplaceRepo}getWebViewsPath(){const e=this.getRootDir();return this.isDev?t.join(e,"src","web","views"):t.join(e,"dist","web","views")}getWebPublicPath(){const e=this.getRootDir();return this.isDev?t.join(e,"src","web","public"):t.join(e,"dist","web","public")}}const M=new A,D=z("common","common"),Z=M.getPackageFile(),L=M.getMarketplaceRepo(),F=JSON.parse(a(Z,"utf8"));function q(e){return s.existsSync(e)?JSON.parse(s.readFileSync(e,"utf-8")):{}}const U=t.join(r.homedir(),".claude","settings.local.json");function V(){const e=function(){const e=process.env.CLAUDE_PROJECT_DIR||process.cwd(),n=t.join(e,".claude/settings.local.json"),r=t.join(e,".claude/settings.json"),s=q(n),a=q(r);return{...q(U),...a,...s}}(),n=!1!==(e?.knowledge||{}).enabled;return n||D.logWarn("Knowledge collection is disabled in settings."),{enabled:n}}function H(){return new Promise((e,t)=>{u("claude plugin marketplace list --json",(n,r,s)=>{if(n)t(n);else{s&&console.error(s);try{const t=r.trim()?JSON.parse(r):[];e(t)}catch(e){t(e)}}})})}const J=I(),K=new class{constructor(){this.dbFile=J.db.file,this.initialized=!1}initialize(){if(!this.initialized){const e=n(this.dbFile);o(e)||i(e,{recursive:!0})}return this.initialized=!0,this}_createConnection(){const e=new l(this.dbFile);return J.db.configs.forEach(t=>{e.pragma(t)}),e}withConnection(e){let t=null;try{return t=this.initialize()._createConnection(),e(t)}finally{t&&(t.close(),t=null)}}static install(){K.withConnection(e=>{x(e)})}},B=I();class W{constructor(){this.dbInstance=K}withConnection(e){return this.dbInstance.withConnection(e)}}class G extends W{create(e){return this.withConnection(t=>{const n=Date.now(),r=t.prepare("\n INSERT INTO knowledge_item (\n session_id,\n title, summary, content,\n scope, source_type, knowledge_type, status,\n source_file, contributor,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @title, @summary, @content,\n @scope, @source_type, @knowledge_type, @status,\n @source_file, @contributor,\n @created_at, @updated_at\n )\n ").run({...e,status:e.status||$.DRAFT,created_at:n,updated_at:n});return this._findById(t,r.lastInsertRowid)})}_findById(e,t){return e.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(t)}findById(e){return this.withConnection(t=>this._findById(t,e))}findByCwd(e,t=10){return this.withConnection(e=>e.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ?").all(t))}findByScope(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE scope = ? ORDER BY updated_at DESC").all(e))}findByStatus(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE status = ? ORDER BY updated_at DESC").all(e))}findByKnowledgeType(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE knowledge_type = ? ORDER BY updated_at DESC").all(e))}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE session_id = ? ORDER BY updated_at DESC").all(e))}update(e,t){return this.withConnection(n=>{const r=Date.now(),s=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return n.prepare(`\n UPDATE knowledge_item\n SET ${s},\n updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:r}),n.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(e)})}updateStatus(e,t){return this.update(e,{status:t})}delete(e){return this.withConnection(t=>t.prepare("DELETE FROM knowledge_item WHERE id = ?").run(e))}count(e={}){return this.withConnection(t=>{let n="SELECT COUNT(*) as count FROM knowledge_item";const r=[],s=[];return e.scope&&(r.push("scope = ?"),s.push(e.scope)),e.status&&(r.push("status = ?"),s.push(e.status)),e.knowledge_type&&(r.push("knowledge_type = ?"),s.push(e.knowledge_type)),e.session_id&&(r.push("session_id = ?"),s.push(e.session_id)),r.length>0&&(n+=` WHERE ${r.join(" AND ")}`),t.prepare(n).get(...s).count})}findAll(e=100,t=0){return this.withConnection(n=>n.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ? OFFSET ?").all(e,t))}search(e,t=10){return this.withConnection(n=>{const r=Array.isArray(e)?e.map(e=>`"${e}"`).join(" OR "):`"${e}"`;return n.prepare("\n SELECT ki.*\n FROM knowledge_item ki\n JOIN knowledge_item_fts fts ON fts.rowid = ki.id\n WHERE knowledge_item_fts MATCH ?\n ORDER BY rank\n LIMIT ?").all(r,t)})}}class X{constructor(){this.logger=z("knowledge-management","knowledge-management"),this.knowledgeRepo=new G}getSessionId(){return process.env.CLAUDE_SESSION_ID}buildUpdateData(e){const t={};return["title","summary","content","scope","source_type","knowledge_type","status","source_file","contributor"].forEach(n=>{void 0!==e[n]&&(t[n]=e[n])}),t}aggregateByStatus(e,t){e.forEach(e=>{t.by_status[e]=this.knowledgeRepo.count({status:e})})}aggregateByScope(e,t){e.forEach(e=>{t.by_scope[e]=this.knowledgeRepo.count({scope:e})})}aggregateByType(e,t){e.forEach(e=>{t.by_type[e]=this.knowledgeRepo.count({knowledge_type:e})})}async create(e){return this.logger.logInfo("Creating new knowledge item",{sessionId:e.session_id}),this.knowledgeRepo.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.source_type,knowledge_type:e.knowledge_type,status:e.status,source_file:e.source_file,contributor:e.contributor,session_id:e.session_id||this.getSessionId()})}async update(e,t){this.logger.logInfo(`Updating knowledge item ${e}...`);const n=this.buildUpdateData(t),r=this.knowledgeRepo.update(e,n);return this.logger.logInfo(`✓ Knowledge item ${e} updated`),r}async delete(e){this.logger.logInfo(`Deleting knowledge item ${e}...`),this.knowledgeRepo.delete(e),this.logger.logInfo(`✓ Knowledge item ${e} deleted`)}async get(e){return this.knowledgeRepo.findById(e)||(this.logger.logWarn(`Knowledge item ${e} not found`),null)}async list(e={}){if(e.scope)return this.knowledgeRepo.findByScope(e.scope);if(e.status)return this.knowledgeRepo.findByStatus(e.status);if(e.knowledge_type)return this.knowledgeRepo.findByKnowledgeType(e.knowledge_type);const t=e.limit||100,n=e.offset||0;return this.knowledgeRepo.findAll(t,n)}async search(e,t=10){return this.knowledgeRepo.search(e,t)}async updateStatus(e,t){this.logger.logInfo(`Updating status of knowledge item ${e} to ${t}...`);const n=this.knowledgeRepo.updateStatus(e,t);return this.logger.logInfo(`✓ Status updated to ${t}`),n}async getStats(){const e={total:0,by_status:{draft:0,suggested:0,verified:0},by_scope:{personal:0,project:0,organization:0},by_type:{code_pattern:0,architecture:0,config:0,pitfall:0,api_usage:0}};return e.total=this.knowledgeRepo.count({}),this.aggregateByStatus(["draft","suggested","verified"],e),this.aggregateByScope(["personal","project","organization"],e),this.aggregateByType(["code_pattern","architecture","config","pitfall","api_usage"],e),e}}class Y extends W{create(e){return this.withConnection(t=>{const n=Date.now(),r=t.prepare("\n INSERT INTO session_event (\n session_id,\n name, input, output, exit_code,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @name, @input, @output, @exit_code,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,name:e.name,input:"string"==typeof e.input?e.input:JSON.stringify(e.input),output:void 0===e.output||null===e.output?null:"string"==typeof e.output?e.output:JSON.stringify(e.output),exit_code:e.exit_code||0,created_at:n,updated_at:n}),s=t.prepare("SELECT * FROM session_event WHERE id = ?").get(r.lastInsertRowid);return s&&(s.input&&(s.input=JSON.parse(s.input)),s.output&&(s.output=JSON.parse(s.output))),s})}updateOutput(e,t,n=0){return this.withConnection(r=>{const s=Date.now(),a=r.prepare("\n UPDATE session_event\n SET output = ?, exit_code = ?, updated_at = ?\n WHERE id = ?\n "),o="string"==typeof t?t:JSON.stringify(t);return a.run(o,n,s,e),this._findById(r,e)})}_findById(e,t){const n=e.prepare("SELECT * FROM session_event WHERE id = ?").get(t);return n&&(n.input&&(n.input=JSON.parse(n.input)),n.output&&(n.output=JSON.parse(n.output))),n}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM session_event WHERE session_id = ? ORDER BY id ASC").all(e).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findBySessionAndName(e,t){return this.withConnection(n=>n.prepare("SELECT * FROM session_event WHERE session_id = ? AND name = ? ORDER BY created_at ASC").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findByName(e,t=100){return this.withConnection(n=>n.prepare("SELECT * FROM session_event WHERE name = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findLatestSessionStart(e){return this.withConnection(t=>{const n=t.prepare("\n SELECT * FROM session_event\n WHERE session_id = ? AND name = ?\n ORDER BY created_at DESC\n LIMIT 1\n ").get(e,"session_start");return n&&(n.input&&(n.input=JSON.parse(n.input)),n.output&&(n.output=JSON.parse(n.output))),n})}hasSessionEnded(e){return this.withConnection(t=>t.prepare("\n SELECT COUNT(*) as count FROM session_event\n WHERE session_id = ? AND name = ?\n limit 1\n ").get(e,"session_end").count>0)}delete(e){return this.withConnection(t=>t.prepare("DELETE FROM session_event WHERE id = ?").run(e))}count(e={}){return this.withConnection(t=>{let n="SELECT COUNT(*) as count FROM session_event";const r=[],s=[];return e.session_id&&(r.push("session_id = ?"),s.push(e.session_id)),e.name&&(r.push("name = ?"),s.push(e.name)),r.length>0&&(n+=` WHERE ${r.join(" AND ")}`),t.prepare(n).get(...s).count})}}class Q extends W{create(e){return this.withConnection(t=>{const n=t.prepare("SELECT * FROM session WHERE session_id = ?").get(e.session_id);if(n)return n;const r=Date.now(),s=e.config||I(),a=t.prepare("\n INSERT INTO session (\n session_id,\n cwd, cwd_updated_at, git_url, git_branch, git_commit_id, user_name,\n env, config, duration,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @cwd, @cwd_updated_at, @git_url, @git_branch, @git_commit_id, @user_name,\n @env, @config, @duration,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,cwd:e.cwd||e.working_directory,cwd_updated_at:r,git_url:e.git_url||null,git_branch:e.git_branch||e.branch||null,git_commit_id:e.git_commit_id||null,user_name:e.user_name||e.username||null,env:e.env?JSON.stringify(e.env):null,config:JSON.stringify(s),duration:null,created_at:r,updated_at:r});return this._findById(t,a.lastInsertRowid)})}_findById(e,t){return e.prepare("SELECT * FROM session WHERE id = ?").get(t)}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM session WHERE session_id = ?").get(e))}updateSessionDuration(e){return this.withConnection(t=>{const n=t.prepare("SELECT * FROM session WHERE session_id = ?").get(e);if(!n)throw new Error(`Session not found: ${e}`);const r=Date.now(),s=Math.floor((r-n.created_at)/1e3);return t.prepare("\n UPDATE session\n SET duration = ?, updated_at = ?\n WHERE id = ?\n ").run(s,r,n.id),t.prepare("SELECT * FROM session WHERE id = ?").get(n.id)})}findByCwd(e){return this.withConnection(t=>t.prepare("SELECT * FROM session WHERE cwd = ? ORDER BY updated_at DESC").all(e))}getSessionSummary(e){return this.withConnection(t=>{const n=(new Y).findBySessionId(e),r=t.prepare("SELECT * FROM session WHERE session_id = ?").get(e),s={session_id:e,total_events:n.length,hook_types:{},start_time:null,end_time:null,duration:null,cwd:r?.cwd||null,git_branch:r?.git_branch||null,config:r?.config||null,created_at:r?.created_at||null,updated_at:r?.updated_at||null};return n.forEach(e=>{s.hook_types[e.name]=(s.hook_types[e.name]||0)+1,"session_start"!==e.name||s.start_time||(s.start_time=e.created_at),"session_end"!==e.name||s.end_time||(s.end_time=e.created_at)}),s.start_time&&s.end_time&&(s.duration=s.end_time-s.start_time),s})}}class ee{constructor(e=null){this.repoPath=e||h(),this.git=p(this.repoPath)}getCurrentBranch(){return this.git.branchLocal().then(e=>e.current).catch(e=>{throw new Error(`Failed to get current branch: ${e.message}`)})}getRemoteUrl(e="origin"){return this.git.getRemotes(!0).then(t=>{const n=t.find(t=>t.name===e);if(!n)throw new Error(`Remote '${e}' not found`);return n.refs.fetch||n.refs.push}).catch(e=>{throw new Error(`Failed to get remote URL: ${e.message}`)})}getMainBranch(){return this.git.branchLocal().then(e=>{const t=e.all;return t.includes("main")?"main":t.includes("master")?"master":t[0]||"main"}).catch(()=>"main")}isOnMainBranch(){return this.getCurrentBranch().then(e=>this.getMainBranch().then(t=>e===t))}getCurrentCommitHash(){return this.git.revparse(["HEAD"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit hash: ${e.message}`)})}getCurrentCommit(){return this.getCurrentCommitHash()}isBranchMergedToMain(e){return this.getMainBranch().then(t=>this.git.branch(["--merged",t]).then(t=>t.all.map(e=>e.replace("*","").trim()).includes(e))).catch(e=>(console.error(`Failed to check merge status: ${e.message}`),!1))}getRepoRoot(){return this.git.revparse(["--show-toplevel"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get repo root: ${e.message}`)})}getUpstreamUrl(){return this.getCurrentBranch().then(e=>this.git.getConfig(`branch.${e}.remote`)).then(e=>{const t=e.value;if(!t)throw new Error("No upstream remote configured for current branch");return this.getRemoteUrl(t)}).catch(e=>{throw new Error(`Failed to get upstream URL: ${e.message}`)})}isGitRepository(){return this.git.checkIsRepo().then(e=>e).catch(()=>!1)}getUserInfo(){return Promise.all([this.git.getConfig("user.name").catch(()=>({value:null})),this.git.getConfig("user.email").catch(()=>({value:null}))]).then(([e,t])=>({name:e.value||"unknown",email:t.value||"unknown"}))}}class te extends j{constructor(e){super(e.session_id,e.hook_event_name),this.input=e,this.sessionId=e.session_id,this.transcriptPath=e.transcript_path,this.cwd=e.cwd,this.permissionMode=e.permission_mode,this.hookEventName=e.hook_event_name,this.sessionRecord=null,this.sessionEvent=null,this.gitUtils=new ee(this.cwd),this.sessionRepo=new Q,this.sessionEventRepo=new Y}async createSessionRecord(){const e=await this.gitUtils.isGitRepository(),t=e?await this.gitUtils.getCurrentBranch():null,n=e?await this.gitUtils.getUserInfo().name:null,r=e?await this.gitUtils.getRemoteUrl():null,s=e?await this.gitUtils.getCurrentCommit():null;return this.sessionRepo.create({session_id:this.sessionId,cwd:this.cwd,git_url:r,git_branch:t,git_commit_id:s,user_name:n,env:{...process.env}})}static async parseInput(){const e=await te.readStdin();return JSON.parse(e)}static async readStdin(){return new Promise((e,t)=>{let n="";const r=process.stdin;r.setEncoding("utf8"),r.on("data",e=>{n+=e}),r.on("end",()=>{e(n)}),r.on("error",e=>{t(e)}),r.resume()})}updateSessionOutput(e){this.sessionEvent&&this.sessionEventRepo.updateOutput(this.sessionEvent.id,e.message,e.exitCode)}async execute(){return this.createSessionRecord().then(e=>(this.sessionRecord=e,this.sessionEvent=this.sessionEventRepo.create({session_id:this.sessionId,name:this.hookEventName,input:this.input}),this.internalExecute(this.sessionRecord,this.sessionEvent))).then(e=>(this.updateSessionOutput(e),e)).catch(e=>this.createNonBlockingError(`Hook execution failed: ${e.message}`))}async internalExecute(e,t){throw new Error("internalExecute() must be implemented by subclass")}createSuccessOutput(e={}){return new ne({exitCode:0,message:e})}createBlockingError(e){return new ne({exitCode:2,message:e})}createNonBlockingError(e){return new ne({exitCode:1,message:e})}}class ne{constructor({exitCode:e,message:t}){this.exitCode=e,this.message=t,this.logger=z("ClaudeHookOutput","ClaudeHookOutput")}send(){0===this.exitCode?process.stdout.write("object"==typeof this.message?JSON.stringify(this.message,null,2):this.message):process.stderr.write(this.message),process.exit(this.exitCode)}}class re{constructor(){this.continue=!0,this.stopReason=null,this.suppressOutput=!1,this.systemMessage=null,this.hookSpecificOutput=null}setSuppressOutput(e){return this.suppressOutput=e,this}setSystemMessage(e){return this.systemMessage=e,this}toJSON(){const e={};return void 0!==this.continue&&(e.continue=this.continue),this.stopReason&&(e.stopReason=this.stopReason),this.suppressOutput&&(e.suppressOutput=this.suppressOutput),this.systemMessage&&(e.systemMessage=this.systemMessage),this.hookSpecificOutput&&(e.hookSpecificOutput=this.hookSpecificOutput),e}}class se extends re{constructor(){super(),this.permissionDecision=null,this.permissionDecisionReason=null,this.updatedInput=null,this.additionalContext=null}allow(e=null){return this.permissionDecision="allow",this.permissionDecisionReason=e,this}deny(e){return this.permissionDecision="deny",this.permissionDecisionReason=e,this}ask(e=null){return this.permissionDecision="ask",this.permissionDecisionReason=e,this}updateInput(e){return this.updatedInput=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON(),t=!!this.permissionDecision,n=!!this.updatedInput,r=!!this.additionalContext;if(t||n||r){const t={hookEventName:"PreToolUse"};this.permissionDecision&&(t.permissionDecision=this.permissionDecision),this.permissionDecisionReason&&(t.permissionDecisionReason=this.permissionDecisionReason),this.updatedInput&&(t.updatedInput=this.updatedInput),this.additionalContext&&(t.additionalContext=this.additionalContext),e.hookSpecificOutput=t}return e}}class ae extends re{constructor(){super(),this.hookSpecificOutput={hookEventName:"PermissionRequest",decision:null}}allow(e=null){return this.hookSpecificOutput.decision={behavior:"allow"},e&&(this.hookSpecificOutput.decision.updatedInput=e),this}deny(e=null,t=!1){return this.hookSpecificOutput.decision={behavior:"deny"},e&&(this.hookSpecificOutput.decision.message=e),t&&(this.hookSpecificOutput.decision.interrupt=t),this}toJSON(){const e=super.toJSON();return this.hookSpecificOutput.decision&&(e.hookSpecificOutput={hookEventName:"PermissionRequest",decision:this.hookSpecificOutput.decision}),e}}class oe extends re{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"PostToolUse",additionalContext:this.additionalContext}),e}}class ie extends re{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"UserPromptSubmit",additionalContext:this.additionalContext}),e}}class ce extends re{constructor(){super(),this.decision=null,this.reason=null}block(e){return this.decision="block",this.reason=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),e}}class ue extends re{constructor(){super(),this.additionalContext=null}setAdditionalContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.additionalContext&&(e.hookSpecificOutput={hookEventName:"SessionStart",additionalContext:this.additionalContext}),e}}class de extends ce{}class le extends re{}class pe extends re{}class he extends re{}const me=I();class fe extends te{async persistVariables(e={}){const t=process.env.CLAUDE_ENV_FILE;if(!t)return void this.logDebug("CLAUDE_ENV_FILE not set, skipping variable persistence");const n={CLAUDE_SESSION_ID:this.sessionId,CLAUDE_SESSION_TRANSCRIPT_PATH:this.transcriptPath,CLAUDE_SESSION_CWD:this.cwd,CLAUDE_SESSION_SOURCE:this.input.source,CLAUDE_SESSION_MODE:this.input.model};[...Object.entries(n).map(([e,t])=>[e,t]),...Object.entries(e).filter(([e,t])=>!["id","session_id"].includes(e)).map(([e,t])=>[`CLAUDE_SESSION_${e.toUpperCase()}`,t])].forEach(([e,n])=>{if(!process.env[e]){const r=String(n).replace(/'/g,"'\\''");s.appendFileSync(t,`export ${e}='${r}'\n`)}}),this.logDebug("Persisted input variables to CLAUDE_ENV_FILE",{envFile:t})}injectKnowledgePrompt(){return["KNOWLEDGE INTEGRATION WORKFLOW:","","**At the START of each new task** (when user submits their first prompt for a task):","1. FIRST: Proactively invoke the `knowledge.enhance` skill to search and inject relevant knowledge based on user input"," - This provides context from past sessions and related knowledge"," - Only call this ONCE at the beginning of the task","","**At the END of successful task completion** (when the task is fully resolved):","2. LAST: Proactively invoke the `knowledge.collect` skill in the background to collect and organize knowledge from this session"," - This captures learnings from the completed work"," - Only call this ONCE after all work is done","","**IMPORTANT - Conflict Prevention & Manual Override**:","- If you have already invoked ANY `knowledge.*` skill (e.g., `knowledge.add`, `knowledge.save`, `knowledge.init`, `knowledge.update`, `knowledge.import`) during this session, **do NOT invoke `knowledge.collect`** at the end. Manual knowledge operations take precedence over automatic collection.","- Do NOT invoke these skills during task interruptions (network issues, asking user for clarification, etc.)","- Do NOT invoke these skills when user is providing additional information for an ongoing task","- Do NOT invoke these skills repeatedly - only ONCE at start and ONCE at end","","**How to detect interruptions vs new tasks**:","- If the user prompt is answering your question or providing requested information, it is an interruption","- If the user prompt is a brand new request or task, invoke `knowledge.enhance` first"]}cleanTempFiles(){s.readdirSync(me.tmp,{withFileTypes:!0}).forEach(e=>{const n=t.join(me.tmp,e.name);if(e.isDirectory())s.rmSync(n,{recursive:!0,force:!0});else{const r=s.statSync(t.join(me.tmp,e.name)),a=new Date(r.birthtime),o=new Date,i=Math.abs(o-a);Math.ceil(i/864e5)>1&&s.rmSync(n,{force:!0})}})}async internalExecute(e,t){const n=V(),r=new ue;if(n.enabled){await this.persistVariables(e),this.cleanTempFiles();const t=[`Knowledge-Bank session started (${this.sessionId})`,`- Branch: ${e.git_branch}`,`- Knowledge auto-collection: enabled, version ${F.version}`];r.setSystemMessage(t.join("\n"));const n=this.injectKnowledgePrompt();r.setAdditionalContext(n.join("\n"))}return super.createSuccessOutput(r.toJSON())}}class ge extends te{async internalExecute(e,t){const n=new le;this.logDebug("Notification hook triggered",{input:this.input});const r=n.toJSON();return this.logDebug("Notification hook output generated",{output:r}),super.createSuccessOutput(r)}}I();class ye extends te{async internalExecute(e,t){const n=(new ae).toJSON();return this.logDebug("PermissionRequest hook output generated",{output:n}),super.createSuccessOutput(n)}}class _e extends te{async internalExecute(e,t){const n=new oe;return this.logDebug("PostToolUse hook completed",n),super.createSuccessOutput(n.toJSON())}}class ve extends te{async internalExecute(e,t){(new Y).findLatestSessionStart(this.sessionId);const n=new pe;return this.logDebug("PreCompact hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(n.toJSON())}generateSessionSummary(e){const t={};e.forEach(e=>{t[e.name]=(t[e.name]||0)+1});const n=[];return(t.tool_use||t.post_tool_use)&&n.push(`${(t.tool_use||0)+(t.post_tool_use||0)} tool operation(s)`),(t.user_prompt||t.user_prompt_submit)&&n.push(`${(t.user_prompt||0)+(t.user_prompt_submit||0)} user prompt(s)`),`Session with ${n.join(", ")}`}}const we=I();class be extends te{async internalExecute(e,t){const n=new se;this.shouldAutoApprove()&&n.allow(),this.logDebug("PreToolUse hook triggered",{input:this.input});const r=n.toJSON();return super.createSuccessOutput(r)}shouldAutoApprove(){let e=!1;this.logDebug("Evaluating permission request for auto-approval",this.input);const{tool_name:t,tool_input:n}=this.input;switch(t){case"mcp__plugin_core_knowledge-bank-management__knowledge_create":case"mcp__plugin_core_knowledge-bank-management__knowledge_get":case"mcp__plugin_core_knowledge-bank-management__knowledge_update":case"mcp__plugin_core_knowledge-bank-management__knowledge_delete":case"mcp__plugin_core_knowledge-bank-management__knowledge_list":case"mcp__plugin_core_knowledge-bank-management__knowledge_search":case"mcp__plugin_core_knowledge-bank-management__knowledge_update_status":case"mcp__plugin_core_knowledge-bank-management__knowledge_stats":e=!0;break;case"Read":case"Write":case"Edit":e=n.file_path.startsWith(we.tmp)||n.file_path.endsWith("/skills/KNOWLEDGE-DEFINITION.md");break;case"Bash":e=n.command.startsWith(`mkdir -p ${we.tmp}`);break;case"Skill":e=n.skill.startsWith("core:knowledge.")||n.skill.startsWith("knowledge.")}return e}}class ke extends te{async internalExecute(e,t){(new Q).updateSessionDuration(this.sessionId);const n=new he;return this.logDebug("SessionEnd hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(n.toJSON())}}class $e extends te{async internalExecute(e,t){const n=new ce;this.logDebug("Stop hook triggered",{input:this.input});const r=n.toJSON();return this.logDebug("Stop hook output generated",{output:r}),super.createSuccessOutput(r)}}class Se extends te{async internalExecute(e,t){const n=new de;this.logDebug("SubagentStop hook triggered",{input:this.input});const r=n.toJSON();return this.logDebug("SubagentStop hook output generated",{output:r}),super.createSuccessOutput(r)}}class Ee extends te{isKnowledgeSkillInvocation(){const e=this.input.prompt||"";return e.startsWith("/knowledge.")||e.startsWith("/core:knowledge.")}async internalExecute(e,t){const n=new ie;if(V().enabled&&!this.isKnowledgeSkillInvocation()){const e=["REMINDER: Knowledge Integration Workflow","- FIRST: Invoke `knowledge.enhance` skill to get relevant context","- LAST: After task completion, invoke `knowledge.collect` skill to capture learnings","","Note: This is a new task - remember to invoke knowledge.enhance first before proceeding."];n.addContext(e.join("\n")),this.logDebug("UserPromptSubmitHook: Added knowledge context for new task")}return super.createSuccessOutput(n.toJSON())}}var Te,xe;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Te||(Te={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(xe||(xe={}));const Oe=Te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ne=e=>{switch(typeof e){case"undefined":return Oe.undefined;case"string":return Oe.string;case"number":return Number.isNaN(e)?Oe.nan:Oe.number;case"boolean":return Oe.boolean;case"function":return Oe.function;case"bigint":return Oe.bigint;case"symbol":return Oe.symbol;case"object":return Array.isArray(e)?Oe.array:null===e?Oe.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Oe.promise:"undefined"!=typeof Map&&e instanceof Map?Oe.map:"undefined"!=typeof Set&&e instanceof Set?Oe.set:"undefined"!=typeof Date&&e instanceof Date?Oe.date:Oe.object;default:return Oe.unknown}},Ie=Te.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"]);class Pe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(r);else if("invalid_return_type"===s.code)r(s.returnTypeError);else if("invalid_arguments"===s.code)r(s.argumentsError);else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof Pe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Te.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Pe.create=e=>new Pe(e);const Re=(e,t)=>{let n;switch(e.code){case Ie.invalid_type:n=e.received===Oe.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Ie.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Te.jsonStringifyReplacer)}`;break;case Ie.unrecognized_keys:n=`Unrecognized key(s) in object: ${Te.joinValues(e.keys,", ")}`;break;case Ie.invalid_union:n="Invalid input";break;case Ie.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Te.joinValues(e.options)}`;break;case Ie.invalid_enum_value:n=`Invalid enum value. Expected ${Te.joinValues(e.options)}, received '${e.received}'`;break;case Ie.invalid_arguments:n="Invalid function arguments";break;case Ie.invalid_return_type:n="Invalid function return type";break;case Ie.invalid_date:n="Invalid date";break;case Ie.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Te.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Ie.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Ie.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Ie.custom:n="Invalid input";break;case Ie.invalid_intersection_types:n="Intersection results could not be merged";break;case Ie.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Ie.not_finite:n="Number must be finite";break;default:n=t.defaultError,Te.assertNever(e)}return{message:n}};let Ce=Re;function je(e,t){const n=Ce,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,a=[...n,...s.path||[]],o={...s,path:a};if(void 0!==s.message)return{...s,path:a,message:s.message};let i="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...s,path:a,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Re?void 0:Re].filter(e=>!!e)});e.common.issues.push(r)}class ze{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return Ae;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return ze.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:s}=r;if("aborted"===t.status)return Ae;if("aborted"===s.status)return Ae;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!r.alwaysSet||(n[t.value]=s.value)}return{status:e.value,value:n}}}const Ae=Object.freeze({status:"aborted"}),Me=e=>({status:"dirty",value:e}),De=e=>({status:"valid",value:e}),Ze=e=>"aborted"===e.status,Le=e=>"dirty"===e.status,Fe=e=>"valid"===e.status,qe=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Ue;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Ue||(Ue={}));class Ve{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}}const He=(e,t)=>{if(Fe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Pe(e.common.issues);return this._error=t,this._error}}};function Je(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??s.defaultError}:void 0===s.data?{message:a??r??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:a??n??s.defaultError}},description:s}}let Ke=class{get description(){return this._def.description}_getType(e){return Ne(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ze,ctx:{common:e.parent.common,data:e.data,parsedType:Ne(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(qe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},r=this._parseSync({data:e,path:n.path,parent:n});return He(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Fe(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Fe(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ne(e)},r=this._parse({data:e,path:n.path,parent:n}),s=await(qe(r)?r:Promise.resolve(r));return He(n,s)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const s=e(t),a=()=>r.addIssue({code:Ie.custom,...n(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Ht({schema:this,typeName:en.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:e=>this["~validate"](e)}}optional(){return Jt.create(this,this._def)}nullable(){return Kt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return It.create(this)}promise(){return Vt.create(this,this._def)}or(e){return Ct.create([this,e],this._def)}and(e){return zt.create(this,e,this._def)}transform(e){return new Ht({...Je(this._def),schema:this,typeName:en.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Bt({...Je(this._def),innerType:this,defaultValue:t,typeName:en.ZodDefault})}brand(){return new Xt({typeName:en.ZodBranded,type:this,...Je(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Wt({...Je(this._def),innerType:this,catchValue:t,typeName:en.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Yt.create(this,e)}readonly(){return Qt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Be=/^c[^\s-]{8,}$/i,We=/^[0-9a-z]+$/,Ge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Xe=/^[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,Ye=/^[a-z0-9_-]{21}$/i,Qe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,et=/^[-+]?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)?)??$/,tt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let nt;const rt=/^(?:(?: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])$/,st=/^(?:(?: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])$/,at=/^(([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]))$/,ot=/^(([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])$/,it=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ct=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ut="((\\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])))",dt=new RegExp(`^${ut}$`);function lt(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function pt(e){return new RegExp(`^${lt(e)}$`)}function ht(e){let t=`${ut}T${lt(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function mt(e,t){return!("v4"!==t&&t||!rt.test(e))||!("v6"!==t&&t||!at.test(e))}function ft(e,t){if(!Qe.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function gt(e,t){return!("v4"!==t&&t||!st.test(e))||!("v6"!==t&&t||!ot.test(e))}let yt=class e extends Ke{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Oe.string){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.string,received:t.parsedType}),Ae}const t=new ze;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,a=e.data.length<r.value;(s||a)&&(n=this._getOrReturnCtx(e,n),s?je(n,{code:Ie.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&je(n,{code:Ie.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)tt.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"email",code:Ie.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)nt||(nt=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nt.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"emoji",code:Ie.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)Xe.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"uuid",code:Ie.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"nanoid",code:Ie.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)Be.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"cuid",code:Ie.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)We.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"cuid2",code:Ie.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)Ge.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"ulid",code:Ie.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),je(n,{validation:"url",code:Ie.invalid_string,message:r.message}),t.dirty()}else"regex"===r.kind?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"regex",code:Ie.invalid_string,message:r.message}),t.dirty())):"trim"===r.kind?e.data=e.data.trim():"includes"===r.kind?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):"toLowerCase"===r.kind?e.data=e.data.toLowerCase():"toUpperCase"===r.kind?e.data=e.data.toUpperCase():"startsWith"===r.kind?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):"endsWith"===r.kind?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):"datetime"===r.kind?ht(r).test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:"datetime",message:r.message}),t.dirty()):"date"===r.kind?dt.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:"date",message:r.message}),t.dirty()):"time"===r.kind?pt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.invalid_string,validation:"time",message:r.message}),t.dirty()):"duration"===r.kind?et.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"duration",code:Ie.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?mt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"ip",code:Ie.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?ft(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"jwt",code:Ie.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?gt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"cidr",code:Ie.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?it.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"base64",code:Ie.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?ct.test(e.data)||(n=this._getOrReturnCtx(e,n),je(n,{validation:"base64url",code:Ie.invalid_string,message:r.message}),t.dirty()):Te.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Ie.invalid_string,...Ue.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...Ue.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ue.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ue.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ue.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ue.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ue.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ue.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ue.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ue.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ue.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ue.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ue.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ue.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ue.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Ue.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ue.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ue.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Ue.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ue.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ue.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ue.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ue.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ue.errToObj(t)})}nonempty(e){return this.min(1,Ue.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function _t(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}yt.create=e=>new yt({checks:[],typeName:en.ZodString,coerce:e?.coerce??!1,...Je(e)});let vt=class e extends Ke{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)!==Oe.number){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.number,received:t.parsedType}),Ae}let t;const n=new ze;for(const r of this._def.checks)"int"===r.kind?Te.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty()):"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):"multipleOf"===r.kind?0!==_t(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.not_finite,message:r.message}),n.dirty()):Te.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ue.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ue.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ue.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ue.toString(t))}setLimit(t,n,r,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ue.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:Ue.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ue.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ue.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ue.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ue.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ue.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ue.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ue.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ue.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Te.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};vt.create=e=>new vt({checks:[],typeName:en.ZodNumber,coerce:e?.coerce||!1,...Je(e)});class wt extends Ke{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)!==Oe.bigint)return this._getInvalidInput(e);let t;const n=new ze;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),je(t,{code:Ie.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):Te.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.bigint,received:t.parsedType}),Ae}gte(e,t){return this.setLimit("min",e,!0,Ue.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ue.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ue.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ue.toString(t))}setLimit(e,t,n,r){return new wt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Ue.toString(r)}]})}_addCheck(e){return new wt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ue.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ue.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ue.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ue.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ue.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}wt.create=e=>new wt({checks:[],typeName:en.ZodBigInt,coerce:e?.coerce??!1,...Je(e)});let bt=class extends Ke{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==Oe.boolean){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.boolean,received:t.parsedType}),Ae}return De(e.data)}};bt.create=e=>new bt({typeName:en.ZodBoolean,coerce:e?.coerce||!1,...Je(e)});class kt extends Ke{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Oe.date){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.date,received:t.parsedType}),Ae}if(Number.isNaN(e.data.getTime()))return je(this._getOrReturnCtx(e),{code:Ie.invalid_date}),Ae;const t=new ze;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),je(n,{code:Ie.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Te.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new kt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ue.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ue.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}kt.create=e=>new kt({checks:[],coerce:e?.coerce||!1,typeName:en.ZodDate,...Je(e)});class $t extends Ke{_parse(e){if(this._getType(e)!==Oe.symbol){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.symbol,received:t.parsedType}),Ae}return De(e.data)}}$t.create=e=>new $t({typeName:en.ZodSymbol,...Je(e)});class St extends Ke{_parse(e){if(this._getType(e)!==Oe.undefined){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.undefined,received:t.parsedType}),Ae}return De(e.data)}}St.create=e=>new St({typeName:en.ZodUndefined,...Je(e)});let Et=class extends Ke{_parse(e){if(this._getType(e)!==Oe.null){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.null,received:t.parsedType}),Ae}return De(e.data)}};Et.create=e=>new Et({typeName:en.ZodNull,...Je(e)});class Tt extends Ke{constructor(){super(...arguments),this._any=!0}_parse(e){return De(e.data)}}Tt.create=e=>new Tt({typeName:en.ZodAny,...Je(e)});let xt=class extends Ke{constructor(){super(...arguments),this._unknown=!0}_parse(e){return De(e.data)}};xt.create=e=>new xt({typeName:en.ZodUnknown,...Je(e)});let Ot=class extends Ke{_parse(e){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.never,received:t.parsedType}),Ae}};Ot.create=e=>new Ot({typeName:en.ZodNever,...Je(e)});class Nt extends Ke{_parse(e){if(this._getType(e)!==Oe.undefined){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.void,received:t.parsedType}),Ae}return De(e.data)}}Nt.create=e=>new Nt({typeName:en.ZodVoid,...Je(e)});let It=class e extends Ke{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==Oe.array)return je(t,{code:Ie.invalid_type,expected:Oe.array,received:t.parsedType}),Ae;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,s=t.data.length<r.exactLength.value;(e||s)&&(je(t,{code:e?Ie.too_big:Ie.too_small,minimum:s?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(je(t,{code:Ie.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(je(t,{code:Ie.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Ve(t,e,t.path,n)))).then(e=>ze.mergeArray(n,e));const s=[...t.data].map((e,n)=>r.type._parseSync(new Ve(t,e,t.path,n)));return ze.mergeArray(n,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Ue.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Ue.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Ue.toString(n)}})}nonempty(e){return this.min(1,e)}};function Pt(e){if(e instanceof Rt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Jt.create(Pt(r))}return new Rt({...e._def,shape:()=>t})}return e instanceof It?new It({...e._def,type:Pt(e.element)}):e instanceof Jt?Jt.create(Pt(e.unwrap())):e instanceof Kt?Kt.create(Pt(e.unwrap())):e instanceof At?At.create(e.items.map(e=>Pt(e))):e}It.create=(e,t)=>new It({type:e,minLength:null,maxLength:null,exactLength:null,typeName:en.ZodArray,...Je(t)});let Rt=class e extends Ke{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Te.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Oe.object){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.object,received:t.parsedType}),Ae}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ot&&"strip"===this._def.unknownKeys))for(const e in n.data)s.includes(e)||a.push(e);const o=[];for(const e of s){const t=r[e],s=n.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new Ve(n,s,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ot){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)o.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)a.length>0&&(je(n,{code:Ie.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new Ve(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ze.mergeObjectSync(t,e)):ze.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return Ue.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,n)=>{const r=this._def.errorMap?.(e,n).message??n.defaultError;return"unrecognized_keys"===e.code?{message:Ue.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:en.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const n={};for(const e of Te.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){const n={};for(const e of Te.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Pt(this)}partial(t){const n={};for(const e of Te.objectKeys(this.shape)){const r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){const n={};for(const e of Te.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Jt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ft(Te.objectKeys(this.shape))}};Rt.create=(e,t)=>new Rt({shape:()=>e,unknownKeys:"strip",catchall:Ot.create(),typeName:en.ZodObject,...Je(t)}),Rt.strictCreate=(e,t)=>new Rt({shape:()=>e,unknownKeys:"strict",catchall:Ot.create(),typeName:en.ZodObject,...Je(t)}),Rt.lazycreate=(e,t)=>new Rt({shape:e,unknownKeys:"strip",catchall:Ot.create(),typeName:en.ZodObject,...Je(t)});let Ct=class extends Ke{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new Pe(e.ctx.common.issues));return je(t,{code:Ie.invalid_union,unionErrors:n}),Ae});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=r.map(e=>new Pe(e));return je(t,{code:Ie.invalid_union,unionErrors:s}),Ae}}get options(){return this._def.options}};function jt(e,t){const n=Ne(e),r=Ne(t);if(e===t)return{valid:!0,data:e};if(n===Oe.object&&r===Oe.object){const n=Te.objectKeys(t),r=Te.objectKeys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=jt(e[n],t[n]);if(!r.valid)return{valid:!1};s[n]=r.data}return{valid:!0,data:s}}if(n===Oe.array&&r===Oe.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const s=jt(e[r],t[r]);if(!s.valid)return{valid:!1};n.push(s.data)}return{valid:!0,data:n}}return n===Oe.date&&r===Oe.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Ct.create=(e,t)=>new Ct({options:e,typeName:en.ZodUnion,...Je(t)});let zt=class extends Ke{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Ze(e)||Ze(r))return Ae;const s=jt(e.value,r.value);return s.valid?((Le(e)||Le(r))&&t.dirty(),{status:t.value,value:s.data}):(je(n,{code:Ie.invalid_intersection_types}),Ae)};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(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};zt.create=(e,t,n)=>new zt({left:e,right:t,typeName:en.ZodIntersection,...Je(n)});class At extends Ke{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Oe.array)return je(n,{code:Ie.invalid_type,expected:Oe.array,received:n.parsedType}),Ae;if(n.data.length<this._def.items.length)return je(n,{code:Ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ae;!this._def.rest&&n.data.length>this._def.items.length&&(je(n,{code:Ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new Ve(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ze.mergeArray(t,e)):ze.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new At({...this._def,rest:e})}}At.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new At({items:e,typeName:en.ZodTuple,rest:null,...Je(t)})};class Mt extends Ke{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Oe.map)return je(n,{code:Ie.invalid_type,expected:Oe.map,received:n.parsedType}),Ae;const r=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Ve(n,e,n.path,[a,"key"])),value:s._parse(new Ve(n,t,n.path,[a,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of a){const r=await n.key,s=await n.value;if("aborted"===r.status||"aborted"===s.status)return Ae;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of a){const r=n.key,s=n.value;if("aborted"===r.status||"aborted"===s.status)return Ae;"dirty"!==r.status&&"dirty"!==s.status||t.dirty(),e.set(r.value,s.value)}return{status:t.value,value:e}}}}Mt.create=(e,t,n)=>new Mt({valueType:t,keyType:e,typeName:en.ZodMap,...Je(n)});class Dt extends Ke{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Oe.set)return je(n,{code:Ie.invalid_type,expected:Oe.set,received:n.parsedType}),Ae;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(je(n,{code:Ie.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(je(n,{code:Ie.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const n=new Set;for(const r of e){if("aborted"===r.status)return Ae;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>s._parse(new Ve(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(e,t){return new Dt({...this._def,minSize:{value:e,message:Ue.toString(t)}})}max(e,t){return new Dt({...this._def,maxSize:{value:e,message:Ue.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Dt.create=(e,t)=>new Dt({valueType:e,minSize:null,maxSize:null,typeName:en.ZodSet,...Je(t)});class Zt extends Ke{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Zt.create=(e,t)=>new Zt({getter:e,typeName:en.ZodLazy,...Je(t)});let Lt=class extends Ke{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return je(t,{received:t.data,code:Ie.invalid_literal,expected:this._def.value}),Ae}return{status:"valid",value:e.data}}get value(){return this._def.value}};function Ft(e,t){return new qt({values:e,typeName:en.ZodEnum,...Je(t)})}Lt.create=(e,t)=>new Lt({value:e,typeName:en.ZodLiteral,...Je(t)});let qt=class e extends Ke{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return je(t,{expected:Te.joinValues(n),received:t.parsedType,code:Ie.invalid_type}),Ae}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return je(t,{received:t.data,code:Ie.invalid_enum_value,options:n}),Ae}return De(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};qt.create=Ft;class Ut extends Ke{_parse(e){const t=Te.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Oe.string&&n.parsedType!==Oe.number){const e=Te.objectValues(t);return je(n,{expected:Te.joinValues(e),received:n.parsedType,code:Ie.invalid_type}),Ae}if(this._cache||(this._cache=new Set(Te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Te.objectValues(t);return je(n,{received:n.data,code:Ie.invalid_enum_value,options:e}),Ae}return De(e.data)}get enum(){return this._def.values}}Ut.create=(e,t)=>new Ut({values:e,typeName:en.ZodNativeEnum,...Je(t)});class Vt extends Ke{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Oe.promise&&!1===t.common.async)return je(t,{code:Ie.invalid_type,expected:Oe.promise,received:t.parsedType}),Ae;const n=t.parsedType===Oe.promise?t.data:Promise.resolve(t.data);return De(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Vt.create=(e,t)=>new Vt({type:e,typeName:en.ZodPromise,...Je(t)});class Ht extends Ke{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===en.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:e=>{je(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===r.type){const e=r.transform(n.data,s);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Ae;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?Ae:"dirty"===r.status||"dirty"===t.value?Me(r.value):r});{if("aborted"===t.value)return Ae;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?Ae:"dirty"===r.status||"dirty"===t.value?Me(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,s);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?Ae:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Ae:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Fe(e))return Ae;const a=r.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Fe(e)?Promise.resolve(r.transform(e.value,s)).then(e=>({status:t.value,value:e})):Ae)}Te.assertNever(r)}}Ht.create=(e,t,n)=>new Ht({schema:e,typeName:en.ZodEffects,effect:t,...Je(n)}),Ht.createWithPreprocess=(e,t,n)=>new Ht({schema:t,effect:{type:"preprocess",transform:e},typeName:en.ZodEffects,...Je(n)});let Jt=class extends Ke{_parse(e){return this._getType(e)===Oe.undefined?De(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Jt.create=(e,t)=>new Jt({innerType:e,typeName:en.ZodOptional,...Je(t)});let Kt=class extends Ke{_parse(e){return this._getType(e)===Oe.null?De(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kt.create=(e,t)=>new Kt({innerType:e,typeName:en.ZodNullable,...Je(t)});let Bt=class extends Ke{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Bt.create=(e,t)=>new Bt({innerType:e,typeName:en.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Je(t)});let Wt=class extends Ke{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Pe(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new Pe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wt.create=(e,t)=>new Wt({innerType:e,typeName:en.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Je(t)});class Gt extends Ke{_parse(e){if(this._getType(e)!==Oe.nan){const t=this._getOrReturnCtx(e);return je(t,{code:Ie.invalid_type,expected:Oe.nan,received:t.parsedType}),Ae}return{status:"valid",value:e.data}}}Gt.create=e=>new Gt({typeName:en.ZodNaN,...Je(e)});class Xt extends Ke{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Yt extends Ke{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ae:"dirty"===e.status?(t.dirty(),Me(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ae:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new Yt({in:e,out:t,typeName:en.ZodPipeline})}}let Qt=class extends Ke{_parse(e){const t=this._def.innerType._parse(e),n=e=>(Fe(e)&&(e.value=Object.freeze(e.value)),e);return qe(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};var en;Qt.create=(e,t)=>new Qt({innerType:e,typeName:en.ZodReadonly,...Je(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(en||(en={})),Ot.create,It.create;const tn=Rt.create;function nn(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const s=o.prototype,a=Object.keys(s);for(let e=0;e<a.length;e++){const t=a[e];t in n||(n[t]=s[t].bind(n))}}const s=n?.Parent??Object;class a extends s{}function o(e){var t;const s=n?.Parent?new a:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const e of s._zod.deferred)e();return s}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}Ct.create,zt.create,At.create,qt.create,Vt.create,Jt.create,Kt.create;class rn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class sn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const an={};function on(e){return an}function cn(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function un(e,t){return"bigint"==typeof t?t.toString():t}function dn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ln(e){return null==e}function pn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const hn=Symbol("evaluating");function mn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==hn)return void 0===r&&(r=hn,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function fn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function gn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function yn(e){return JSON.stringify(e)}const _n="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function vn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const wn=dn(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function bn(e){if(!1===vn(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==vn(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function kn(e){return bn(e)?{...e}:Array.isArray(e)?[...e]:e}const $n=new Set(["string","number","symbol"]);function Sn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function En(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Tn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const xn={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]};function On(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Nn(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function In(e){return"string"==typeof e?e:e?.message}function Pn(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const s=In(e.inst?._zod.def?.error?.(e))??In(t?.error?.(e))??In(n.customError?.(e))??In(n.localeError?.(e))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Rn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Cn(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const jn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,un,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zn=nn("$ZodError",jn),An=nn("$ZodError",jn,{Parent:Error}),Mn=e=>(t,n,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new rn;if(o.issues.length){const t=new(s?.Err??e)(o.issues.map(e=>Pn(e,a,on())));throw _n(t,s?.callee),t}return o.value},Dn=Mn(An),Zn=e=>async(t,n,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(s?.Err??e)(o.issues.map(e=>Pn(e,a,on())));throw _n(t,s?.callee),t}return o.value},Ln=Zn(An),Fn=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new rn;return a.issues.length?{success:!1,error:new(e??zn)(a.issues.map(e=>Pn(e,s,on())))}:{success:!0,data:a.value}},qn=Fn(An),Un=e=>async(t,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Pn(e,s,on())))}:{success:!0,data:a.value}},Vn=Un(An),Hn=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Mn(e)(t,n,s)},Jn=e=>(t,n,r)=>Mn(e)(t,n,r),Kn=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Zn(e)(t,n,s)},Bn=e=>async(t,n,r)=>Zn(e)(t,n,r),Wn=e=>(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Fn(e)(t,n,s)},Gn=e=>(t,n,r)=>Fn(e)(t,n,r),Xn=e=>async(t,n,r)=>{const s=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Un(e)(t,n,s)},Yn=e=>async(t,n,r)=>Un(e)(t,n,r),Qn=/^[cC][^\s-]{8,}$/,er=/^[0-9a-z]+$/,tr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nr=/^[0-9a-vA-V]{20}$/,rr=/^[A-Za-z0-9]{27}$/,sr=/^[a-zA-Z0-9_-]{21}$/,ar=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,or=/^([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})$/,ir=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,cr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ur=/^(?:(?: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])$/,dr=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,lr=/^((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])$/,pr=/^(([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])$/,hr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mr=/^[A-Za-z0-9_-]*$/,fr=/^\+[1-9]\d{6,14}$/,gr="(?:(?:\\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])))",yr=new RegExp(`^${gr}$`);function _r(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const vr=/^-?\d+$/,wr=/^-?\d+(?:\.\d+)?$/,br=/^(?:true|false)$/i,kr=/^null$/i,$r=/^[^A-Z]*$/,Sr=/^[^a-z]*$/,Er=nn("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Tr={number:"number",bigint:"bigint",object:"date"},xr=nn("$ZodCheckLessThan",(e,t)=>{Er.init(e,t);const n=Tr[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Or=nn("$ZodCheckGreaterThan",(e,t)=>{Er.init(e,t);const n=Tr[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Nr=nn("$ZodCheckMultipleOf",(e,t)=>{Er.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let s=(r.split(".")[1]||"").length;if(0===s&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(s=Number.parseInt(e[1]))}const a=n>s?n:s;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ir=nn("$ZodCheckNumberFormat",(e,t)=>{Er.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,a]=xn[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=s,r.maximum=a,n&&(r.pattern=vr)}),e._zod.check=o=>{const i=o.value;if(n){if(!Number.isInteger(i))return void o.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?o.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}i<s&&o.issues.push({origin:"number",input:i,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),i>a&&o.issues.push({origin:"number",input:i,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Pr=nn("$ZodCheckMaxLength",(e,t)=>{var n;Er.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!ln(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=Rn(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Rr=nn("$ZodCheckMinLength",(e,t)=>{var n;Er.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!ln(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=Rn(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cr=nn("$ZodCheckLengthEquals",(e,t)=>{var n;Er.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!ln(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const a=Rn(r),o=s>t.length;n.issues.push({origin:a,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),jr=nn("$ZodCheckStringFormat",(e,t)=>{var n,r;Er.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),zr=nn("$ZodCheckRegex",(e,t)=>{jr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ar=nn("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=$r),jr.init(e,t)}),Mr=nn("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Sr),jr.init(e,t)}),Dr=nn("$ZodCheckIncludes",(e,t)=>{Er.init(e,t);const n=Sn(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Zr=nn("$ZodCheckStartsWith",(e,t)=>{Er.init(e,t);const n=new RegExp(`^${Sn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Lr=nn("$ZodCheckEndsWith",(e,t)=>{Er.init(e,t);const n=new RegExp(`.*${Sn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Fr=nn("$ZodCheckOverwrite",(e,t)=>{Er.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class qr{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Ur={major:4,minor:3,patch:6},Vr=nn("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ur;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=On(e);for(const a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&!1===n?.async)throw new rn;if(r||o instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(s||(s=On(e,t)))});else{if(e.issues.length===t)continue;s||(s=On(e,t))}}return r?r.then(()=>e):e},n=(n,s,a)=>{if(On(n))return n.aborted=!0,n;const o=t(s,r,a);if(o instanceof Promise){if(!1===a.async)throw new rn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if("backward"===a.direction){const t=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,s,a)):n(t,s,a)}const o=e._zod.parse(s,a);if(o instanceof Promise){if(!1===a.async)throw new rn;return o.then(e=>t(e,r,a))}return t(o,r,a)}}mn(e,"~standard",()=>({validate:t=>{try{const n=qn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Vn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Hr=nn("$ZodString",(e,t)=>{var n;Vr.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Jr=nn("$ZodStringFormat",(e,t)=>{jr.init(e,t),Hr.init(e,t)}),Kr=nn("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=or),Jr.init(e,t)}),Br=nn("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ir(e))}else t.pattern??(t.pattern=ir());Jr.init(e,t)}),Wr=nn("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=cr),Jr.init(e,t)}),Gr=nn("$ZodURL",(e,t)=>{Jr.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),s=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=s.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Xr=nn("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Jr.init(e,t)}),Yr=nn("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=sr),Jr.init(e,t)}),Qr=nn("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Qn),Jr.init(e,t)}),es=nn("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=er),Jr.init(e,t)}),ts=nn("$ZodULID",(e,t)=>{t.pattern??(t.pattern=tr),Jr.init(e,t)}),ns=nn("$ZodXID",(e,t)=>{t.pattern??(t.pattern=nr),Jr.init(e,t)}),rs=nn("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=rr),Jr.init(e,t)}),ss=nn("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=_r({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${gr}T(?:${r})$`)}(t)),Jr.init(e,t)}),as=nn("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=yr),Jr.init(e,t)}),os=nn("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${_r(t)}$`)),Jr.init(e,t)}),is=nn("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ar),Jr.init(e,t)}),cs=nn("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ur),Jr.init(e,t),e._zod.bag.format="ipv4"}),us=nn("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=dr),Jr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),ds=nn("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=lr),Jr.init(e,t)}),ls=nn("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pr),Jr.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ps(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const hs=nn("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=hr),Jr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ps(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),ms=nn("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mr),Jr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!mr.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ps(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),fs=nn("$ZodE164",(e,t)=>{t.pattern??(t.pattern=fr),Jr.init(e,t)}),gs=nn("$ZodJWT",(e,t)=>{Jr.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ys=nn("$ZodNumber",(e,t)=>{Vr.init(e,t),e._zod.pattern=e._zod.bag.pattern??wr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const s=n.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return n;const a="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...a?{received:a}:{}}),n}}),_s=nn("$ZodNumberFormat",(e,t)=>{Ir.init(e,t),ys.init(e,t)}),vs=nn("$ZodBoolean",(e,t)=>{Vr.init(e,t),e._zod.pattern=br,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const s=n.value;return"boolean"==typeof s||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),ws=nn("$ZodNull",(e,t)=>{Vr.init(e,t),e._zod.pattern=kr,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),bs=nn("$ZodUnknown",(e,t)=>{Vr.init(e,t),e._zod.parse=e=>e}),ks=nn("$ZodNever",(e,t)=>{Vr.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function $s(e,t,n){e.issues.length&&t.issues.push(...Nn(n,e.issues)),t.value[n]=e.value}const Ss=nn("$ZodArray",(e,t)=>{Vr.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const a=[];for(let e=0;e<s.length;e++){const o=s[e],i=t.element._zod.run({value:o,issues:[]},r);i instanceof Promise?a.push(i.then(t=>$s(t,n,e))):$s(i,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Es(e,t,n,r,s){if(e.issues.length){if(s&&!(n in r))return;t.issues.push(...Nn(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Ts(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function xs(e,t,n,r,s,a){const o=[],i=s.keySet,c=s.catchall._zod,u=c.def.type,d="optional"===c.optout;for(const s in t){if(i.has(s))continue;if("never"===u){o.push(s);continue}const a=c.run({value:t[s],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Es(e,n,s,t,d))):Es(a,n,s,t,d)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Os=nn("$ZodObject",(e,t)=>{Vr.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=dn(()=>Ts(t));mn(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const s=vn,a=t.catchall;let o;e._zod.parse=(t,n)=>{o??(o=r.value);const i=t.value;if(!s(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value={};const c=[],u=o.shape;for(const e of o.keys){const r=u[e],s="optional"===r._zod.optout,a=r._zod.run({value:i[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>Es(n,t,e,i,s))):Es(a,t,e,i,s)}return a?xs(c,i,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ns=nn("$ZodObjectJIT",(e,t)=>{Os.init(e,t);const n=e._zod.parse,r=dn(()=>Ts(t));let s;const a=vn,o=!an.jitless,i=o&&wn.value,c=t.catchall;let u;e._zod.parse=(d,l)=>{u??(u=r.value);const p=d.value;return a(p)?o&&i&&!1===l?.async&&!0!==l.jitless?(s||(s=(e=>{const t=new qr(["shape","payload","ctx"]),n=r.value,s=e=>{const t=yn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const a=Object.create(null);let o=0;for(const e of n.keys)a[e]="key_"+o++;t.write("const newResult = {};");for(const r of n.keys){const n=a[r],o=yn(r),i=e[r],c="optional"===i?._zod?.optout;t.write(`const ${n} = ${s(r)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${o} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n newResult[${o}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n newResult[${o}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,n)=>i(e,t,n)})(t.shape)),d=s(d,l),c?xs([],p,d,l,u,e):d):n(d,l):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function Is(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const s=e.filter(e=>!On(e));return 1===s.length?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Pn(e,r,on())))}),t)}const Ps=nn("$ZodUnion",(e,t)=>{Vr.init(e,t),mn(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),mn(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),mn(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),mn(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>pn(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(s,a)=>{if(n)return r(s,a);let o=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:s.value,issues:[]},a);if(t instanceof Promise)i.push(t),o=!0;else{if(0===t.issues.length)return t;i.push(t)}}return o?Promise.all(i).then(t=>Is(t,s,e,a)):Is(i,s,e,a)}}),Rs=nn("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ps.init(e,t);const n=e._zod.parse;mn(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=dn(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(s,a)=>{const o=s.value;if(!vn(o))return s.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),s;const i=r.value.get(o?.[t.discriminator]);return i?i._zod.run(s,a):t.unionFallback?n(s,a):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),s)}}),Cs=nn("$ZodIntersection",(e,t)=>{Vr.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,s=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([t,n])=>zs(e,t,n)):zs(e,s,a)}});function js(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(bn(e)&&bn(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const n of r){const r=js(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};s[n]=r.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const s=js(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function zs(e,t,n){const r=new Map;let s;for(const n of t.issues)if("unrecognized_keys"===n.code){s??(s=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&s&&e.issues.push({...s,keys:a}),On(e))return e;const o=js(t.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const As=nn("$ZodRecord",(e,t)=>{Vr.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!bn(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const a=[],o=t.keyType._zod.values;if(o){n.value={};const i=new Set;for(const e of o)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){i.add("number"==typeof e?e.toString():e);const o=t.valueType._zod.run({value:s[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Nn(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Nn(e,o.issues)),n.value[e]=o.value)}let c;for(const e in s)i.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c})}else{n.value={};for(const o of Reflect.ownKeys(s)){if("__proto__"===o)continue;let i=t.keyType._zod.run({value:o,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof o&&wr.test(o)&&i.issues.length){const e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(i=e)}if(i.issues.length){"loose"===t.mode?n.value[o]=s[o]:n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>Pn(e,r,on())),input:o,path:[o],inst:e});continue}const c=t.valueType._zod.run({value:s[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Nn(o,e.issues)),n.value[i.value]=e.value})):(c.issues.length&&n.issues.push(...Nn(o,c.issues)),n.value[i.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Ms=nn("$ZodEnum",(e,t)=>{Vr.init(e,t);const n=cn(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>$n.has(typeof e)).map(e=>"string"==typeof e?Sn(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const a=t.value;return r.has(a)||t.issues.push({code:"invalid_value",values:n,input:a,inst:e}),t}}),Ds=nn("$ZodLiteral",(e,t)=>{if(Vr.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Sn(e):e?Sn(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),r}}),Zs=nn("$ZodTransform",(e,t)=>{Vr.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new sn(e.constructor.name);const s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(n.value=e,n));if(s instanceof Promise)throw new rn;return n.value=s,n}});function Ls(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Fs=nn("$ZodOptional",(e,t)=>{Vr.init(e,t),e._zod.optin="optional",e._zod.optout="optional",mn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),mn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${pn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Ls(t,e.value)):Ls(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),qs=nn("$ZodExactOptional",(e,t)=>{Fs.init(e,t),mn(e._zod,"values",()=>t.innerType._zod.values),mn(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Us=nn("$ZodNullable",(e,t)=>{Vr.init(e,t),mn(e._zod,"optin",()=>t.innerType._zod.optin),mn(e._zod,"optout",()=>t.innerType._zod.optout),mn(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${pn(e.source)}|null)$`):void 0}),mn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Vs=nn("$ZodDefault",(e,t)=>{Vr.init(e,t),e._zod.optin="optional",mn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Hs(e,t)):Hs(r,t)}});function Hs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Js=nn("$ZodPrefault",(e,t)=>{Vr.init(e,t),e._zod.optin="optional",mn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ks=nn("$ZodNonOptional",(e,t)=>{Vr.init(e,t),mn(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(t=>Bs(t,e)):Bs(s,e)}});function Bs(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Ws=nn("$ZodCatch",(e,t)=>{Vr.init(e,t),mn(e._zod,"optin",()=>t.innerType._zod.optin),mn(e._zod,"optout",()=>t.innerType._zod.optout),mn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Pn(e,n,on()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Pn(e,n,on()))},input:e.value}),e.issues=[]),e)}}),Gs=nn("$ZodPipe",(e,t)=>{Vr.init(e,t),mn(e._zod,"values",()=>t.in._zod.values),mn(e._zod,"optin",()=>t.in._zod.optin),mn(e._zod,"optout",()=>t.out._zod.optout),mn(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Xs(e,t.in,n)):Xs(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Xs(e,t.out,n)):Xs(r,t.out,n)}});function Xs(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Ys=nn("$ZodReadonly",(e,t)=>{Vr.init(e,t),mn(e._zod,"propValues",()=>t.innerType._zod.propValues),mn(e._zod,"values",()=>t.innerType._zod.values),mn(e._zod,"optin",()=>t.innerType?._zod?.optin),mn(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Qs):Qs(r)}});function Qs(e){return e.value=Object.freeze(e.value),e}const ea=nn("$ZodCustom",(e,t)=>{Er.init(e,t),Vr.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(t=>ta(t,n,r,e));ta(s,n,r,e)}});function ta(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Cn(e))}}var na;(na=globalThis).__zod_globalRegistry??(na.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const ra=globalThis.__zod_globalRegistry;function sa(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Tn(t)})}function aa(e,t){return new xr({check:"less_than",...Tn(t),value:e,inclusive:!1})}function oa(e,t){return new xr({check:"less_than",...Tn(t),value:e,inclusive:!0})}function ia(e,t){return new Or({check:"greater_than",...Tn(t),value:e,inclusive:!1})}function ca(e,t){return new Or({check:"greater_than",...Tn(t),value:e,inclusive:!0})}function ua(e,t){return new Nr({check:"multiple_of",...Tn(t),value:e})}function da(e,t){return new Pr({check:"max_length",...Tn(t),maximum:e})}function la(e,t){return new Rr({check:"min_length",...Tn(t),minimum:e})}function pa(e,t){return new Cr({check:"length_equals",...Tn(t),length:e})}function ha(e){return new Fr({check:"overwrite",tx:e})}function ma(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ra,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function fa(e,t,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);const i=e._zod.toJSONSchema?.();if(i)o.schema=i;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{const n=o.schema,a=t.processors[s.type];if(!a)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);a(e,t,n,r)}const a=e._zod.parent;a&&(o.ref||(o.ref=a),fa(a,t,r),t.seen.get(a).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),"input"===t.io&&_a(e)&&(delete o.schema.examples,delete o.schema.default),"input"===t.io&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function ga(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const s=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:s,defId:a}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,s=e.external.uri??(e=>e);if(n)return{ref:s(n)};const a=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=a,{defId:a,ref:`${s("__shared")}#/${r}/${a}`}}if(t[1]===n)return{ref:"#"};const s=`#/${r}/`,a=t[1].schema.id??"__schema"+e.counter++;return{defId:a,ref:s+a}})(t);r.def={...r.schema},a&&(r.defId=a);const o=r.schema;for(const e in o)delete o[e];o.$ref=s};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){s(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){s(n);continue}}const a=e.metadataRegistry.get(n[0])?.id;(a||r.cycle||r.count>1&&"ref"===e.reused)&&s(n)}}function ya(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const s=n.def??n.schema,a={...s},o=n.ref;if(n.ref=null,o){r(o);const n=e.seen.get(o),i=n.schema;if(!i.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(s,i):(s.allOf=s.allOf??[],s.allOf.push(i)),Object.assign(s,a),t._zod.parent===o)for(const e in s)"$ref"!==e&&"allOf"!==e&&(e in a||delete s[e]);if(i.$ref&&n.def)for(const e in s)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(s[e])===JSON.stringify(n.def[e])&&delete s[e]}const i=t._zod.parent;if(i&&i!==o){r(i);const t=e.seen.get(i);if(t?.schema.$ref&&(s.$ref=t.schema.$ref,t.def))for(const e in s)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(s[e])===JSON.stringify(t.def[e])&&delete s[e]}e.override({zodSchema:t,jsonSchema:s,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const s={};if("draft-2020-12"===e.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?s.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(n)}Object.assign(s,n.def??n.schema);const a=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?s.$defs=a:s.definitions=a);try{const n=JSON.parse(JSON.stringify(s));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:va(t,"input",e.processors),output:va(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function _a(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return _a(r.element,n);if("set"===r.type)return _a(r.valueType,n);if("lazy"===r.type)return _a(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return _a(r.innerType,n);if("intersection"===r.type)return _a(r.left,n)||_a(r.right,n);if("record"===r.type||"map"===r.type)return _a(r.keyType,n)||_a(r.valueType,n);if("pipe"===r.type)return _a(r.in,n)||_a(r.out,n);if("object"===r.type){for(const e in r.shape)if(_a(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(_a(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(_a(e,n))return!0;return!(!r.rest||!_a(r.rest,n))}return!1}const va=(e,t,n={})=>r=>{const{libraryOptions:s,target:a}=r??{},o=ma({...s??{},target:a,io:t,processors:n});return fa(e,o),ga(o,e),ya(o,e)},wa={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ba=(e,t,n,r)=>{const s=n;s.type="string";const{minimum:a,maximum:o,format:i,patterns:c,contentEncoding:u}=e._zod.bag;if("number"==typeof a&&(s.minLength=a),"number"==typeof o&&(s.maxLength=o),i&&(s.format=wa[i]??i,""===s.format&&delete s.format,"time"===i&&delete s.format),u&&(s.contentEncoding=u),c&&c.size>0){const e=[...c];1===e.length?s.pattern=e[0].source:e.length>1&&(s.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},ka=(e,t,n,r)=>{const s=n,{minimum:a,maximum:o,format:i,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;"string"==typeof i&&i.includes("int")?s.type="integer":s.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.minimum=d,s.exclusiveMinimum=!0):s.exclusiveMinimum=d),"number"==typeof a&&(s.minimum=a,"number"==typeof d&&"draft-04"!==t.target&&(d>=a?delete s.minimum:delete s.exclusiveMinimum)),"number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(s.maximum=u,s.exclusiveMaximum=!0):s.exclusiveMaximum=u),"number"==typeof o&&(s.maximum=o,"number"==typeof u&&"draft-04"!==t.target&&(u<=o?delete s.maximum:delete s.exclusiveMaximum)),"number"==typeof c&&(s.multipleOf=c)},$a=(e,t,n,r)=>{n.type="boolean"},Sa=(e,t,n,r)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ea=(e,t,n,r)=>{n.not={}},Ta=(e,t,n,r)=>{const s=cn(e._zod.def.entries);s.every(e=>"number"==typeof e)&&(n.type="number"),s.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=s},xa=(e,t,n,r)=>{const s=e._zod.def,a=[];for(const e of s.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(e))}else a.push(e);if(0===a.length);else if(1===a.length){const e=a[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else a.every(e=>"number"==typeof e)&&(n.type="number"),a.every(e=>"string"==typeof e)&&(n.type="string"),a.every(e=>"boolean"==typeof e)&&(n.type="boolean"),a.every(e=>null===e)&&(n.type="null"),n.enum=a},Oa=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")},Na=(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")},Ia=(e,t,n,r)=>{const s=n,a=e._zod.def,{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(s.minItems=o),"number"==typeof i&&(s.maxItems=i),s.type="array",s.items=fa(a.element,t,{...r,path:[...r.path,"items"]})},Pa=(e,t,n,r)=>{const s=n,a=e._zod.def;s.type="object",s.properties={};const o=a.shape;for(const e in o)s.properties[e]=fa(o[e],t,{...r,path:[...r.path,"properties",e]});const i=new Set(Object.keys(o)),c=new Set([...i].filter(e=>{const n=a.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(s.required=Array.from(c)),"never"===a.catchall?._zod.def.type?s.additionalProperties=!1:a.catchall?a.catchall&&(s.additionalProperties=fa(a.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)},Ra=(e,t,n,r)=>{const s=e._zod.def,a=!1===s.inclusive,o=s.options.map((e,n)=>fa(e,t,{...r,path:[...r.path,a?"oneOf":"anyOf",n]}));a?n.oneOf=o:n.anyOf=o},Ca=(e,t,n,r)=>{const s=e._zod.def,a=fa(s.left,t,{...r,path:[...r.path,"allOf",0]}),o=fa(s.right,t,{...r,path:[...r.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,c=[...i(a)?a.allOf:[a],...i(o)?o.allOf:[o]];n.allOf=c},ja=(e,t,n,r)=>{const s=n,a=e._zod.def;s.type="object";const o=a.keyType,i=o._zod.bag,c=i?.patterns;if("loose"===a.mode&&c&&c.size>0){const e=fa(a.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const t of c)s.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(s.propertyNames=fa(a.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=fa(a.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const u=o._zod.values;if(u){const e=[...u].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(s.required=e)}},za=(e,t,n,r)=>{const s=e._zod.def,a=fa(s.innerType,t,r),o=t.seen.get(e);"openapi-3.0"===t.target?(o.ref=s.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},Aa=(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType},Ma=(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},Da=(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},Za=(e,t,n,r)=>{const s=e._zod.def;let a;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType;try{a=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},La=(e,t,n,r)=>{const s=e._zod.def,a="input"===t.io?"transform"===s.in._zod.def.type?s.out:s.in:s.out;fa(a,t,r),t.seen.get(e).ref=a},Fa=(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.readOnly=!0},qa=(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType},Ua={string:ba,number:ka,boolean:$a,bigint:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")},null:Sa,undefined:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")},void:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")},never:Ea,any:(e,t,n,r)=>{},unknown:(e,t,n,r)=>{},date:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")},enum:Ta,literal:xa,nan:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,n,r)=>{const s=n,a=e._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");s.type="string",s.pattern=a.source},file:(e,t,n,r)=>{const s=n,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:i,mime:c}=e._zod.bag;void 0!==o&&(a.minLength=o),void 0!==i&&(a.maxLength=i),c?1===c.length?(a.contentMediaType=c[0],Object.assign(s,a)):(Object.assign(s,a),s.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(s,a)},success:(e,t,n,r)=>{n.type="boolean"},custom:Oa,function:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")},transform:Na,map:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")},set:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")},array:Ia,object:Pa,union:Ra,intersection:Ca,tuple:(e,t,n,r)=>{const s=n,a=e._zod.def;s.type="array";const o="draft-2020-12"===t.target?"prefixItems":"items",i="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=a.items.map((e,n)=>fa(e,t,{...r,path:[...r.path,o,n]})),u=a.rest?fa(a.rest,t,{...r,path:[...r.path,i,..."openapi-3.0"===t.target?[a.items.length]:[]]}):null;"draft-2020-12"===t.target?(s.prefixItems=c,u&&(s.items=u)):"openapi-3.0"===t.target?(s.items={anyOf:c},u&&s.items.anyOf.push(u),s.minItems=c.length,u||(s.maxItems=c.length)):(s.items=c,u&&(s.additionalItems=u));const{minimum:d,maximum:l}=e._zod.bag;"number"==typeof d&&(s.minItems=d),"number"==typeof l&&(s.maxItems=l)},record:ja,nullable:za,nonoptional:Aa,default:Ma,prefault:Da,catch:Za,pipe:La,readonly:Fa,promise:(e,t,n,r)=>{const s=e._zod.def;fa(s.innerType,t,r),t.seen.get(e).ref=s.innerType},optional:qa,lazy:(e,t,n,r)=>{const s=e._zod.innerType;fa(s,t,r),t.seen.get(e).ref=s}},Va=nn("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Vr.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Dn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>qn(e,t,n),e.parseAsync=async(t,n)=>Ln(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Vn(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>En(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),Ha=nn("ZodMiniObject",(e,t)=>{Os.init(e,t),Va.init(e,t),mn(e,"shape",()=>t.shape)});function Ja(e,t){const n={type:"object",shape:e??{},...Tn(t)};return new Ha(n)}function Ka(e){return!!e._zod}function Ba(e){const t=Object.values(e);if(0===t.length)return Ja({});const n=t.every(Ka),r=t.every(e=>!Ka(e));if(n)return Ja(e);if(r)return tn(e);throw new Error("Mixed Zod versions detected in object shape.")}function Wa(e,t){return Ka(e)?qn(e,t):e.safeParse(t)}async function Ga(e,t){if(Ka(e))return await Vn(e,t);const n=e;return await n.safeParseAsync(t)}function Xa(e){if(!e)return;let t;if(Ka(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function Ya(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return Ba(e)}}if(Ka(e)){const t=e,n=t._zod?.def;if(n&&("object"===n.type||void 0!==n.shape))return e}else if(void 0!==e.shape)return e}}function Qa(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function eo(e){if(Ka(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;if(void 0!==n)return n}const to=nn("ZodISODateTime",(e,t)=>{ss.init(e,t),So.init(e,t)});function no(e){return function(e,t){return new to({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Tn(t)})}(0,e)}const ro=nn("ZodISODate",(e,t)=>{as.init(e,t),So.init(e,t)});const so=nn("ZodISOTime",(e,t)=>{os.init(e,t),So.init(e,t)});const ao=nn("ZodISODuration",(e,t)=>{is.init(e,t),So.init(e,t)});const oo=nn("ZodError",(e,t)=>{zn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>r({issues:e}));else if("invalid_key"===s.code)r({issues:s.issues});else if("invalid_element"===s.code)r({issues:s.issues});else if(0===s.path.length)n._errors.push(t(s));else{let e=n,r=0;for(;r<s.path.length;){const n=s.path[r];r===s.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(s))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,un,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,un,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),io=Mn(oo),co=Zn(oo),uo=Fn(oo),lo=Un(oo),po=Hn(oo),ho=Jn(oo),mo=Kn(oo),fo=Bn(oo),go=Wn(oo),yo=Gn(oo),_o=Xn(oo),vo=Yn(oo),wo=nn("ZodType",(e,t)=>(Vr.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:va(e,"input"),output:va(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=ma({...n,processors:t});return fa(e,r),ga(r,e),ya(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(gn(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>En(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>io(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>uo(e,t,n),e.parseAsync=async(t,n)=>co(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>lo(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>po(e,t,n),e.decode=(t,n)=>ho(e,t,n),e.encodeAsync=async(t,n)=>mo(e,t,n),e.decodeAsync=async(t,n)=>fo(e,t,n),e.safeEncode=(t,n)=>go(e,t,n),e.safeDecode=(t,n)=>yo(e,t,n),e.safeEncodeAsync=async(t,n)=>_o(e,t,n),e.safeDecodeAsync=async(t,n)=>vo(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new Ri({type:"custom",check:"custom",fn:t,...Tn(n)})}(0,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new Er({check:"custom",...Tn(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Cn(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(Cn(r))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check(ha(t)),e.optional=()=>bi(e),e.exactOptional=()=>new ki({type:"optional",innerType:e}),e.nullable=()=>Si(e),e.nullish=()=>bi(Si(e)),e.nonoptional=t=>function(e,t){return new xi({type:"nonoptional",innerType:e,...Tn(t)})}(e,t),e.array=()=>ni(e),e.or=t=>ii([e,t]),e.and=t=>li(e,t),e.transform=t=>Ii(e,vi(t)),e.default=t=>{return n=t,new Ei({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():kn(n)}});var n},e.prefault=t=>{return n=t,new Ti({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():kn(n)}});var n},e.catch=t=>{return new Oi({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Ii(e,t),e.readonly=()=>new Pi({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return ra.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>ra.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return ra.get(e);const n=e.clone();return ra.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),bo=nn("_ZodString",(e,t)=>{Hr.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ba(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new zr({check:"string_format",format:"regex",...Tn(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Dr({check:"string_format",format:"includes",...Tn(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Zr({check:"string_format",format:"starts_with",...Tn(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Lr({check:"string_format",format:"ends_with",...Tn(t),suffix:e})}(...t)),e.min=(...t)=>e.check(la(...t)),e.max=(...t)=>e.check(da(...t)),e.length=(...t)=>e.check(pa(...t)),e.nonempty=(...t)=>e.check(la(1,...t)),e.lowercase=t=>e.check(function(e){return new Ar({check:"string_format",format:"lowercase",...Tn(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Mr({check:"string_format",format:"uppercase",...Tn(e)})}(t)),e.trim=()=>e.check(ha(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return ha(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(ha(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(ha(e=>e.toUpperCase())),e.slugify=()=>e.check(ha(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),ko=nn("ZodString",(e,t)=>{Hr.init(e,t),bo.init(e,t),e.email=t=>e.check(function(e,t){return new Eo({type:"string",format:"email",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new Oo({type:"string",format:"url",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new Uo({type:"string",format:"jwt",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new No({type:"string",format:"emoji",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.guid=t=>e.check(sa(To,t)),e.uuid=t=>e.check(function(e,t){return new xo({type:"string",format:"uuid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new xo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Tn(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new xo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Tn(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new xo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Tn(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new Io({type:"string",format:"nanoid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.guid=t=>e.check(sa(To,t)),e.cuid=t=>e.check(function(e,t){return new Po({type:"string",format:"cuid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new Ro({type:"string",format:"cuid2",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new Co({type:"string",format:"ulid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new Lo({type:"string",format:"base64",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new Fo({type:"string",format:"base64url",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new jo({type:"string",format:"xid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new zo({type:"string",format:"ksuid",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Ao({type:"string",format:"ipv4",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Mo({type:"string",format:"ipv6",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Do({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new Zo({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new qo({type:"string",format:"e164",check:"string_format",abort:!1,...Tn(t)})}(0,t)),e.datetime=t=>e.check(no(t)),e.date=t=>e.check(function(e){return function(e,t){return new ro({type:"string",format:"date",check:"string_format",...Tn(t)})}(0,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new so({type:"string",format:"time",check:"string_format",precision:null,...Tn(t)})}(0,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new ao({type:"string",format:"duration",check:"string_format",...Tn(t)})}(0,e)}(t))});function $o(e){return function(e,t){return new ko({type:"string",...Tn(t)})}(0,e)}const So=nn("ZodStringFormat",(e,t)=>{Jr.init(e,t),bo.init(e,t)}),Eo=nn("ZodEmail",(e,t)=>{Wr.init(e,t),So.init(e,t)}),To=nn("ZodGUID",(e,t)=>{Kr.init(e,t),So.init(e,t)}),xo=nn("ZodUUID",(e,t)=>{Br.init(e,t),So.init(e,t)}),Oo=nn("ZodURL",(e,t)=>{Gr.init(e,t),So.init(e,t)}),No=nn("ZodEmoji",(e,t)=>{Xr.init(e,t),So.init(e,t)}),Io=nn("ZodNanoID",(e,t)=>{Yr.init(e,t),So.init(e,t)}),Po=nn("ZodCUID",(e,t)=>{Qr.init(e,t),So.init(e,t)}),Ro=nn("ZodCUID2",(e,t)=>{es.init(e,t),So.init(e,t)}),Co=nn("ZodULID",(e,t)=>{ts.init(e,t),So.init(e,t)}),jo=nn("ZodXID",(e,t)=>{ns.init(e,t),So.init(e,t)}),zo=nn("ZodKSUID",(e,t)=>{rs.init(e,t),So.init(e,t)}),Ao=nn("ZodIPv4",(e,t)=>{cs.init(e,t),So.init(e,t)}),Mo=nn("ZodIPv6",(e,t)=>{us.init(e,t),So.init(e,t)}),Do=nn("ZodCIDRv4",(e,t)=>{ds.init(e,t),So.init(e,t)}),Zo=nn("ZodCIDRv6",(e,t)=>{ls.init(e,t),So.init(e,t)}),Lo=nn("ZodBase64",(e,t)=>{hs.init(e,t),So.init(e,t)}),Fo=nn("ZodBase64URL",(e,t)=>{ms.init(e,t),So.init(e,t)}),qo=nn("ZodE164",(e,t)=>{fs.init(e,t),So.init(e,t)}),Uo=nn("ZodJWT",(e,t)=>{gs.init(e,t),So.init(e,t)}),Vo=nn("ZodNumber",(e,t)=>{ys.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ka(e,t,n),e.gt=(t,n)=>e.check(ia(t,n)),e.gte=(t,n)=>e.check(ca(t,n)),e.min=(t,n)=>e.check(ca(t,n)),e.lt=(t,n)=>e.check(aa(t,n)),e.lte=(t,n)=>e.check(oa(t,n)),e.max=(t,n)=>e.check(oa(t,n)),e.int=t=>e.check(Ko(t)),e.safe=t=>e.check(Ko(t)),e.positive=t=>e.check(ia(0,t)),e.nonnegative=t=>e.check(ca(0,t)),e.negative=t=>e.check(aa(0,t)),e.nonpositive=t=>e.check(oa(0,t)),e.multipleOf=(t,n)=>e.check(ua(t,n)),e.step=(t,n)=>e.check(ua(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Ho(e){return function(e,t){return new Vo({type:"number",checks:[],...Tn(t)})}(0,e)}const Jo=nn("ZodNumberFormat",(e,t)=>{_s.init(e,t),Vo.init(e,t)});function Ko(e){return function(e,t){return new Jo({type:"number",check:"number_format",abort:!1,format:"safeint",...Tn(t)})}(0,e)}const Bo=nn("ZodBoolean",(e,t)=>{vs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>$a(0,0,t)});function Wo(e){return function(e,t){return new Bo({type:"boolean",...Tn(t)})}(0,e)}const Go=nn("ZodNull",(e,t)=>{ws.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Sa(0,e,t)});function Xo(e){return function(e,t){return new Go({type:"null",...Tn(t)})}(0,e)}const Yo=nn("ZodUnknown",(e,t)=>{bs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Qo(){return new Yo({type:"unknown"})}const ei=nn("ZodNever",(e,t)=>{ks.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ea(0,0,t)});const ti=nn("ZodArray",(e,t)=>{Ss.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ia(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(la(t,n)),e.nonempty=t=>e.check(la(1,t)),e.max=(t,n)=>e.check(da(t,n)),e.length=(t,n)=>e.check(pa(t,n)),e.unwrap=()=>e.element});function ni(e,t){return function(e,t,n){return new ti({type:"array",element:t,...Tn(n)})}(0,e,t)}const ri=nn("ZodObject",(e,t)=>{Ns.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pa(e,t,n,r),mn(e,"shape",()=>t.shape),e.keyof=()=>fi(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Qo()}),e.loose=()=>e.clone({...e._zod.def,catchall:Qo()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new ei({type:"never",...Tn(t)})}(0,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!bn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=gn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return fn(this,"shape",n),n}});return En(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!bn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=gn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return fn(this,"shape",n),n}});return En(e,n)}(e,t),e.merge=t=>function(e,t){const n=gn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return fn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return En(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return En(e,gn(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return fn(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=gn(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return fn(this,"shape",r),r},checks:[]});return En(e,s)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=gn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)s[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return fn(this,"shape",s),s},checks:[]});return En(t,s)}(wi,e,t[0]),e.required=(...t)=>function(e,t,n){const r=gn(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)s[t]=new e({type:"nonoptional",innerType:r[t]});return fn(this,"shape",s),s}});return En(t,r)}(xi,e,t[0])});function si(e,t){const n={type:"object",shape:e??{},...Tn(t)};return new ri(n)}function ai(e,t){return new ri({type:"object",shape:e,catchall:Qo(),...Tn(t)})}const oi=nn("ZodUnion",(e,t)=>{Ps.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ra(e,t,n,r),e.options=t.options});function ii(e,t){return new oi({type:"union",options:e,...Tn(t)})}const ci=nn("ZodDiscriminatedUnion",(e,t)=>{oi.init(e,t),Rs.init(e,t)});function ui(e,t,n){return new ci({type:"union",options:t,discriminator:e,...Tn(n)})}const di=nn("ZodIntersection",(e,t)=>{Cs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ca(e,t,n,r)});function li(e,t){return new di({type:"intersection",left:e,right:t})}const pi=nn("ZodRecord",(e,t)=>{As.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ja(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function hi(e,t,n){return new pi({type:"record",keyType:e,valueType:t,...Tn(n)})}const mi=nn("ZodEnum",(e,t)=>{Ms.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ta(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const s={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);s[r]=t.entries[r]}return new mi({...t,checks:[],...Tn(r),entries:s})},e.exclude=(e,r)=>{const s={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new mi({...t,checks:[],...Tn(r),entries:s})}});function fi(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new mi({type:"enum",entries:n,...Tn(t)})}const gi=nn("ZodLiteral",(e,t)=>{Ds.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xa(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function yi(e,t){return new gi({type:"literal",values:Array.isArray(e)?e:[e],...Tn(t)})}const _i=nn("ZodTransform",(e,t)=>{Zs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Na(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new sn(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Cn(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Cn(t))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(e=>(n.value=e,n)):(n.value=s,n)}});function vi(e){return new _i({type:"transform",transform:e})}const wi=nn("ZodOptional",(e,t)=>{Fs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function bi(e){return new wi({type:"optional",innerType:e})}const ki=nn("ZodExactOptional",(e,t)=>{qs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),$i=nn("ZodNullable",(e,t)=>{Us.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>za(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Si(e){return new $i({type:"nullable",innerType:e})}const Ei=nn("ZodDefault",(e,t)=>{Vs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Ti=nn("ZodPrefault",(e,t)=>{Js.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Da(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),xi=nn("ZodNonOptional",(e,t)=>{Ks.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Aa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Oi=nn("ZodCatch",(e,t)=>{Ws.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Za(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Ni=nn("ZodPipe",(e,t)=>{Gs.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>La(e,t,0,r),e.in=t.in,e.out=t.out});function Ii(e,t){return new Ni({type:"pipe",in:e,out:t})}const Pi=nn("ZodReadonly",(e,t)=>{Ys.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Ri=nn("ZodCustom",(e,t)=>{ea.init(e,t),wo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Oa(0,e)});function Ci(e,t){return Ii(vi(e),t)}const ji="2025-11-25",zi=[ji,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ai="io.modelcontextprotocol/related-task",Mi="2.0",Di=function(e,t,n){const r=Tn(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...r})}(Ri,0,void 0);const Zi=ii([$o(),Ho().int()]),Li=$o();ai({ttl:ii([Ho(),Xo()]).optional(),pollInterval:Ho().optional()});const Fi=si({ttl:Ho().optional()}),qi=si({taskId:$o()}),Ui=ai({progressToken:Zi.optional(),[Ai]:qi.optional()}),Vi=si({_meta:Ui.optional()}),Hi=Vi.extend({task:Fi.optional()}),Ji=si({method:$o(),params:Vi.loose().optional()}),Ki=si({_meta:Ui.optional()}),Bi=si({method:$o(),params:Ki.loose().optional()}),Wi=ai({_meta:Ui.optional()}),Gi=ii([$o(),Ho().int()]),Xi=si({jsonrpc:yi(Mi),id:Gi,...Ji.shape}).strict(),Yi=e=>Xi.safeParse(e).success,Qi=si({jsonrpc:yi(Mi),...Bi.shape}).strict(),ec=si({jsonrpc:yi(Mi),id:Gi,result:Wi}).strict(),tc=e=>ec.safeParse(e).success;var nc;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(nc||(nc={}));const rc=si({jsonrpc:yi(Mi),id:Gi.optional(),error:si({code:Ho().int(),message:$o(),data:Qo().optional()})}).strict(),sc=ii([Xi,Qi,ec,rc]);ii([ec,rc]);const ac=Wi.strict(),oc=Ki.extend({requestId:Gi.optional(),reason:$o().optional()}),ic=Bi.extend({method:yi("notifications/cancelled"),params:oc}),cc=si({src:$o(),mimeType:$o().optional(),sizes:ni($o()).optional(),theme:fi(["light","dark"]).optional()}),uc=si({icons:ni(cc).optional()}),dc=si({name:$o(),title:$o().optional()}),lc=dc.extend({...dc.shape,...uc.shape,version:$o(),websiteUrl:$o().optional(),description:$o().optional()}),pc=li(si({applyDefaults:Wo().optional()}),hi($o(),Qo())),hc=Ci(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,li(si({form:pc.optional(),url:Di.optional()}),hi($o(),Qo()).optional())),mc=ai({list:Di.optional(),cancel:Di.optional(),requests:ai({sampling:ai({createMessage:Di.optional()}).optional(),elicitation:ai({create:Di.optional()}).optional()}).optional()}),fc=ai({list:Di.optional(),cancel:Di.optional(),requests:ai({tools:ai({call:Di.optional()}).optional()}).optional()}),gc=si({experimental:hi($o(),Di).optional(),sampling:si({context:Di.optional(),tools:Di.optional()}).optional(),elicitation:hc.optional(),roots:si({listChanged:Wo().optional()}).optional(),tasks:mc.optional()}),yc=Vi.extend({protocolVersion:$o(),capabilities:gc,clientInfo:lc}),_c=Ji.extend({method:yi("initialize"),params:yc}),vc=si({experimental:hi($o(),Di).optional(),logging:Di.optional(),completions:Di.optional(),prompts:si({listChanged:Wo().optional()}).optional(),resources:si({subscribe:Wo().optional(),listChanged:Wo().optional()}).optional(),tools:si({listChanged:Wo().optional()}).optional(),tasks:fc.optional()}),wc=Wi.extend({protocolVersion:$o(),capabilities:vc,serverInfo:lc,instructions:$o().optional()}),bc=Bi.extend({method:yi("notifications/initialized"),params:Ki.optional()}),kc=Ji.extend({method:yi("ping"),params:Vi.optional()}),$c=si({progress:Ho(),total:bi(Ho()),message:bi($o())}),Sc=si({...Ki.shape,...$c.shape,progressToken:Zi}),Ec=Bi.extend({method:yi("notifications/progress"),params:Sc}),Tc=Vi.extend({cursor:Li.optional()}),xc=Ji.extend({params:Tc.optional()}),Oc=Wi.extend({nextCursor:Li.optional()}),Nc=fi(["working","input_required","completed","failed","cancelled"]),Ic=si({taskId:$o(),status:Nc,ttl:ii([Ho(),Xo()]),createdAt:$o(),lastUpdatedAt:$o(),pollInterval:bi(Ho()),statusMessage:bi($o())}),Pc=Wi.extend({task:Ic}),Rc=Ki.merge(Ic),Cc=Bi.extend({method:yi("notifications/tasks/status"),params:Rc}),jc=Ji.extend({method:yi("tasks/get"),params:Vi.extend({taskId:$o()})}),zc=Wi.merge(Ic),Ac=Ji.extend({method:yi("tasks/result"),params:Vi.extend({taskId:$o()})});Wi.loose();const Mc=xc.extend({method:yi("tasks/list")}),Dc=Oc.extend({tasks:ni(Ic)}),Zc=Ji.extend({method:yi("tasks/cancel"),params:Vi.extend({taskId:$o()})}),Lc=Wi.merge(Ic),Fc=si({uri:$o(),mimeType:bi($o()),_meta:hi($o(),Qo()).optional()}),qc=Fc.extend({text:$o()}),Uc=$o().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vc=Fc.extend({blob:Uc}),Hc=fi(["user","assistant"]),Jc=si({audience:ni(Hc).optional(),priority:Ho().min(0).max(1).optional(),lastModified:no({offset:!0}).optional()}),Kc=si({...dc.shape,...uc.shape,uri:$o(),description:bi($o()),mimeType:bi($o()),annotations:Jc.optional(),_meta:bi(ai({}))}),Bc=si({...dc.shape,...uc.shape,uriTemplate:$o(),description:bi($o()),mimeType:bi($o()),annotations:Jc.optional(),_meta:bi(ai({}))}),Wc=xc.extend({method:yi("resources/list")}),Gc=Oc.extend({resources:ni(Kc)}),Xc=xc.extend({method:yi("resources/templates/list")}),Yc=Oc.extend({resourceTemplates:ni(Bc)}),Qc=Vi.extend({uri:$o()}),eu=Qc,tu=Ji.extend({method:yi("resources/read"),params:eu}),nu=Wi.extend({contents:ni(ii([qc,Vc]))}),ru=Bi.extend({method:yi("notifications/resources/list_changed"),params:Ki.optional()}),su=Qc,au=Ji.extend({method:yi("resources/subscribe"),params:su}),ou=Qc,iu=Ji.extend({method:yi("resources/unsubscribe"),params:ou}),cu=Ki.extend({uri:$o()}),uu=Bi.extend({method:yi("notifications/resources/updated"),params:cu}),du=si({name:$o(),description:bi($o()),required:bi(Wo())}),lu=si({...dc.shape,...uc.shape,description:bi($o()),arguments:bi(ni(du)),_meta:bi(ai({}))}),pu=xc.extend({method:yi("prompts/list")}),hu=Oc.extend({prompts:ni(lu)}),mu=Vi.extend({name:$o(),arguments:hi($o(),$o()).optional()}),fu=Ji.extend({method:yi("prompts/get"),params:mu}),gu=si({type:yi("text"),text:$o(),annotations:Jc.optional(),_meta:hi($o(),Qo()).optional()}),yu=si({type:yi("image"),data:Uc,mimeType:$o(),annotations:Jc.optional(),_meta:hi($o(),Qo()).optional()}),_u=si({type:yi("audio"),data:Uc,mimeType:$o(),annotations:Jc.optional(),_meta:hi($o(),Qo()).optional()}),vu=si({type:yi("tool_use"),name:$o(),id:$o(),input:hi($o(),Qo()),_meta:hi($o(),Qo()).optional()}),wu=si({type:yi("resource"),resource:ii([qc,Vc]),annotations:Jc.optional(),_meta:hi($o(),Qo()).optional()}),bu=ii([gu,yu,_u,Kc.extend({type:yi("resource_link")}),wu]),ku=si({role:Hc,content:bu}),$u=Wi.extend({description:$o().optional(),messages:ni(ku)}),Su=Bi.extend({method:yi("notifications/prompts/list_changed"),params:Ki.optional()}),Eu=si({title:$o().optional(),readOnlyHint:Wo().optional(),destructiveHint:Wo().optional(),idempotentHint:Wo().optional(),openWorldHint:Wo().optional()}),Tu=si({taskSupport:fi(["required","optional","forbidden"]).optional()}),xu=si({...dc.shape,...uc.shape,description:$o().optional(),inputSchema:si({type:yi("object"),properties:hi($o(),Di).optional(),required:ni($o()).optional()}).catchall(Qo()),outputSchema:si({type:yi("object"),properties:hi($o(),Di).optional(),required:ni($o()).optional()}).catchall(Qo()).optional(),annotations:Eu.optional(),execution:Tu.optional(),_meta:hi($o(),Qo()).optional()}),Ou=xc.extend({method:yi("tools/list")}),Nu=Oc.extend({tools:ni(xu)}),Iu=Wi.extend({content:ni(bu).default([]),structuredContent:hi($o(),Qo()).optional(),isError:Wo().optional()});Iu.or(Wi.extend({toolResult:Qo()}));const Pu=Hi.extend({name:$o(),arguments:hi($o(),Qo()).optional()}),Ru=Ji.extend({method:yi("tools/call"),params:Pu}),Cu=Bi.extend({method:yi("notifications/tools/list_changed"),params:Ki.optional()});si({autoRefresh:Wo().default(!0),debounceMs:Ho().int().nonnegative().default(300)});const ju=fi(["debug","info","notice","warning","error","critical","alert","emergency"]),zu=Vi.extend({level:ju}),Au=Ji.extend({method:yi("logging/setLevel"),params:zu}),Mu=Ki.extend({level:ju,logger:$o().optional(),data:Qo()}),Du=Bi.extend({method:yi("notifications/message"),params:Mu}),Zu=si({name:$o().optional()}),Lu=si({hints:ni(Zu).optional(),costPriority:Ho().min(0).max(1).optional(),speedPriority:Ho().min(0).max(1).optional(),intelligencePriority:Ho().min(0).max(1).optional()}),Fu=si({mode:fi(["auto","required","none"]).optional()}),qu=si({type:yi("tool_result"),toolUseId:$o().describe("The unique identifier for the corresponding tool call."),content:ni(bu).default([]),structuredContent:si({}).loose().optional(),isError:Wo().optional(),_meta:hi($o(),Qo()).optional()}),Uu=ui("type",[gu,yu,_u]),Vu=ui("type",[gu,yu,_u,vu,qu]),Hu=si({role:Hc,content:ii([Vu,ni(Vu)]),_meta:hi($o(),Qo()).optional()}),Ju=Hi.extend({messages:ni(Hu),modelPreferences:Lu.optional(),systemPrompt:$o().optional(),includeContext:fi(["none","thisServer","allServers"]).optional(),temperature:Ho().optional(),maxTokens:Ho().int(),stopSequences:ni($o()).optional(),metadata:Di.optional(),tools:ni(xu).optional(),toolChoice:Fu.optional()}),Ku=Ji.extend({method:yi("sampling/createMessage"),params:Ju}),Bu=Wi.extend({model:$o(),stopReason:bi(fi(["endTurn","stopSequence","maxTokens"]).or($o())),role:Hc,content:Uu}),Wu=Wi.extend({model:$o(),stopReason:bi(fi(["endTurn","stopSequence","maxTokens","toolUse"]).or($o())),role:Hc,content:ii([Vu,ni(Vu)])}),Gu=si({type:yi("boolean"),title:$o().optional(),description:$o().optional(),default:Wo().optional()}),Xu=si({type:yi("string"),title:$o().optional(),description:$o().optional(),minLength:Ho().optional(),maxLength:Ho().optional(),format:fi(["email","uri","date","date-time"]).optional(),default:$o().optional()}),Yu=si({type:fi(["number","integer"]),title:$o().optional(),description:$o().optional(),minimum:Ho().optional(),maximum:Ho().optional(),default:Ho().optional()}),Qu=si({type:yi("string"),title:$o().optional(),description:$o().optional(),enum:ni($o()),default:$o().optional()}),ed=si({type:yi("string"),title:$o().optional(),description:$o().optional(),oneOf:ni(si({const:$o(),title:$o()})),default:$o().optional()}),td=si({type:yi("string"),title:$o().optional(),description:$o().optional(),enum:ni($o()),enumNames:ni($o()).optional(),default:$o().optional()}),nd=ii([Qu,ed]),rd=ii([si({type:yi("array"),title:$o().optional(),description:$o().optional(),minItems:Ho().optional(),maxItems:Ho().optional(),items:si({type:yi("string"),enum:ni($o())}),default:ni($o()).optional()}),si({type:yi("array"),title:$o().optional(),description:$o().optional(),minItems:Ho().optional(),maxItems:Ho().optional(),items:si({anyOf:ni(si({const:$o(),title:$o()}))}),default:ni($o()).optional()})]),sd=ii([td,nd,rd]),ad=ii([sd,Gu,Xu,Yu]),od=ii([Hi.extend({mode:yi("form").optional(),message:$o(),requestedSchema:si({type:yi("object"),properties:hi($o(),ad),required:ni($o()).optional()})}),Hi.extend({mode:yi("url"),message:$o(),elicitationId:$o(),url:$o().url()})]),id=Ji.extend({method:yi("elicitation/create"),params:od}),cd=Ki.extend({elicitationId:$o()}),ud=Bi.extend({method:yi("notifications/elicitation/complete"),params:cd}),dd=Wi.extend({action:fi(["accept","decline","cancel"]),content:Ci(e=>null===e?void 0:e,hi($o(),ii([$o(),Ho(),Wo(),ni($o())])).optional())}),ld=si({type:yi("ref/resource"),uri:$o()}),pd=si({type:yi("ref/prompt"),name:$o()}),hd=Vi.extend({ref:ii([pd,ld]),argument:si({name:$o(),value:$o()}),context:si({arguments:hi($o(),$o()).optional()}).optional()}),md=Ji.extend({method:yi("completion/complete"),params:hd}),fd=Wi.extend({completion:ai({values:ni($o()).max(100),total:bi(Ho().int()),hasMore:bi(Wo())})}),gd=si({uri:$o().startsWith("file://"),name:$o().optional(),_meta:hi($o(),Qo()).optional()}),yd=Ji.extend({method:yi("roots/list"),params:Vi.optional()}),_d=Wi.extend({roots:ni(gd)}),vd=Bi.extend({method:yi("notifications/roots/list_changed"),params:Ki.optional()});ii([kc,_c,md,Au,fu,pu,Wc,Xc,tu,au,iu,Ru,Ou,jc,Ac,Mc,Zc]),ii([ic,Ec,bc,vd,Cc]),ii([ac,Bu,Wu,dd,_d,zc,Dc,Pc]),ii([kc,Ku,id,yd,jc,Ac,Mc,Zc]),ii([ic,Ec,Du,uu,ru,Cu,Su,Cc,ud]),ii([ac,wc,fd,$u,hu,Gc,Yc,nu,Iu,Nu,zc,Dc,Pc]);class wd extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===nc.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new bd(e.elicitations,t)}return new wd(e,t,n)}}class bd extends wd{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(nc.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function kd(e){return"completed"===e||"failed"===e||"cancelled"===e}const $d=Symbol("Let zodToJsonSchema decide on which parser to use"),Sd={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"};function Ed(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Td(e,t,n,r,s){e[t]=n,Ed(e,t,r,s)}const xd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Od(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?xd(t,e.currentPath):t.join("/")}}function Nd(e,t){return tl(e.type._def,t)}function Id(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Id(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Pd(e,t)}}const Pd=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":Td(n,"minimum",r.value,r.message,t);break;case"max":Td(n,"maximum",r.value,r.message,t)}return n};let Rd;const Cd=/^[cC][^\s-]{8,}$/,jd=/^[0-9a-z]+$/,zd=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ad=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Md=()=>(void 0===Rd&&(Rd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Rd),Dd=/^(?:(?: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])$/,Zd=/^(([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])$/,Ld=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,qd=/^[a-zA-Z0-9_-]{21}$/,Ud=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Vd(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":Td(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":Td(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Kd(n,"email",r.message,t);break;case"format:idn-email":Kd(n,"idn-email",r.message,t);break;case"pattern:zod":Bd(n,Ad,r.message,t)}break;case"url":Kd(n,"uri",r.message,t);break;case"uuid":Kd(n,"uuid",r.message,t);break;case"regex":Bd(n,r.regex,r.message,t);break;case"cuid":Bd(n,Cd,r.message,t);break;case"cuid2":Bd(n,jd,r.message,t);break;case"startsWith":Bd(n,RegExp(`^${Hd(r.value,t)}`),r.message,t);break;case"endsWith":Bd(n,RegExp(`${Hd(r.value,t)}$`),r.message,t);break;case"datetime":Kd(n,"date-time",r.message,t);break;case"date":Kd(n,"date",r.message,t);break;case"time":Kd(n,"time",r.message,t);break;case"duration":Kd(n,"duration",r.message,t);break;case"length":Td(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),Td(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":Bd(n,RegExp(Hd(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&Kd(n,"ipv4",r.message,t),"v4"!==r.version&&Kd(n,"ipv6",r.message,t);break;case"base64url":Bd(n,Fd,r.message,t);break;case"jwt":Bd(n,Ud,r.message,t);break;case"cidr":"v6"!==r.version&&Bd(n,Dd,r.message,t),"v4"!==r.version&&Bd(n,Zd,r.message,t);break;case"emoji":Bd(n,Md(),r.message,t);break;case"ulid":Bd(n,zd,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Kd(n,"binary",r.message,t);break;case"contentEncoding:base64":Td(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":Bd(n,Ld,r.message,t)}break;case"nanoid":Bd(n,qd,r.message,t)}return n}function Hd(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Jd.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Jd=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kd(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Td(e,"format",t,n,r)}function Bd(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Wd(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Td(e,"pattern",Wd(t,r),n,r)}function Wd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),s=e.flags.includes("s"),a=n?e.source.toLowerCase():e.source;let o="",i=!1,c=!1,u=!1;for(let e=0;e<a.length;e++)if(i)o+=a[e],i=!1;else{if(n)if(c){if(a[e].match(/[a-z]/)){u?(o+=a[e],o+=`${a[e-2]}-${a[e]}`.toUpperCase(),u=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(o+=a[e],u=!0):o+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){o+=`[${a[e]}${a[e].toUpperCase()}]`;continue}if(r){if("^"===a[e]){o+="(^|(?<=[\r\n]))";continue}if("$"===a[e]){o+="($|(?=[\r\n]))";continue}}s&&"."===a[e]?o+=c?`${a[e]}\r\n`:`[${a[e]}\r\n]`:(o+=a[e],"\\"===a[e]?i=!0:c&&"]"===a[e]?c=!1:c||"["!==a[e]||(c=!0))}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Gd(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===en.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:tl(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Od(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:tl(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===en.ZodString&&e.keyType._def.checks?.length){const{type:r,...s}=Vd(e.keyType._def,t);return{...n,propertyNames:s}}if(e.keyType?._def.typeName===en.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===en.ZodBranded&&e.keyType._def.type._def.typeName===en.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...s}=Nd(e.keyType._def,t);return{...n,propertyNames:s}}return n}const Xd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},Yd=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>tl(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Qd(e){try{return e.isOptional()}catch{return!0}}const el=(e,t,n)=>{switch(t){case en.ZodString:return Vd(e,n);case en.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Ed(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?Td(n,"minimum",r.value,r.message,t):Td(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Td(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Td(n,"maximum",r.value,r.message,t):Td(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Td(n,"maximum",r.value,r.message,t));break;case"multipleOf":Td(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case en.ZodObject:return function(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},s=[],a=e.shape();for(const e in a){let o=a[e];if(void 0===o||void 0===o._def)continue;let i=Qd(o);i&&n&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),i=!1);const c=tl(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,i||s.push(e))}s.length&&(r.required=s);const o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return tl(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(r.additionalProperties=o),r}(e,n);case en.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?Td(n,"minimum",r.value,r.message,t):Td(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Td(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?Td(n,"maximum",r.value,r.message,t):Td(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Td(n,"maximum",r.value,r.message,t));break;case"multipleOf":Td(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case en.ZodBoolean:return{type:"boolean"};case en.ZodDate:return Id(e,n);case en.ZodUndefined:return function(e){return{not:Od(e)}}(n);case en.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case en.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==en.ZodAny&&(n.items=tl(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Td(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Td(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Td(n,"minItems",e.exactLength.value,e.exactLength.message,t),Td(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case en.ZodUnion:case en.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Yd(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Xd&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=Xd[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Yd(e,t)}(e,n);case en.ZodIntersection:return function(e,t){const n=[tl(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),tl(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),s.length?{allOf:s,...r}:void 0}(e,n);case en.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>tl(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:tl(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>tl(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case en.ZodRecord:return Gd(e,n);case en.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case en.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case en.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case en.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:Xd[e.innerType._def.typeName],nullable:!0}:{type:[Xd[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=tl(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=tl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case en.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return tl(e.innerType._def,t);const n=tl(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Od(t)},n]}:Od(t)})(e,n);case en.ZodMap:return function(e,t){return"record"===t.mapStrategy?Gd(e,t):{type:"array",maxItems:125,items:{type:"array",items:[tl(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Od(t),tl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Od(t)],minItems:2,maxItems:2}}}(e,n);case en.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:tl(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Td(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Td(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case en.ZodLazy:return()=>e.getter()._def;case en.ZodPromise:return function(e,t){return tl(e.type._def,t)}(e,n);case en.ZodNaN:case en.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Od({...e,currentPath:[...e.currentPath,"not"]})}}(n);case en.ZodEffects:return function(e,t){return"input"===t.effectStrategy?tl(e.schema._def,t):Od(t)}(e,n);case en.ZodAny:return Od(n);case en.ZodUnknown:return function(e){return Od(e)}(n);case en.ZodDefault:return function(e,t){return{...tl(e.innerType._def,t),default:e.defaultValue()}}(e,n);case en.ZodBranded:return Nd(e,n);case en.ZodReadonly:case en.ZodCatch:return((e,t)=>tl(e.innerType._def,t))(e,n);case en.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return tl(e.in._def,t);if("output"===t.pipeStrategy)return tl(e.out._def,t);const n=tl(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,tl(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case en.ZodFunction:case en.ZodVoid:case en.ZodSymbol:default:return}};function tl(e,t,n=!1){const r=t.seen.get(e);if(t.override){const s=t.override?.(e,t,r,n);if(s!==$d)return s}if(r&&!n){const e=nl(r,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=el(e,e.typeName,t),o="function"==typeof a?tl(a(),t):a;if(o&&rl(e,t,o),t.postProcess){const n=t.postProcess(o,e,t);return s.jsonSchema=o,n}return s.jsonSchema=o,o}const nl=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:xd(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Od(t)):"seen"===t.$refStrategy?Od(t):void 0}},rl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function sl(e,t){return Ka(e)?function(e,t){if("_idmap"in e){const n=e,r=ma({...t,processors:Ua}),s={};for(const e of n._idmap.entries()){const[t,n]=e;fa(n,r)}const a={},o={registry:n,uri:t?.uri,defs:s};r.external=o;for(const e of n._idmap.entries()){const[t,n]=e;ga(r,n),a[t]=ya(r,n)}if(Object.keys(s).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";a.__shared={[e]:s}}return{schemas:a}}const n=ma({...t,processors:Ua});return fa(e,n),ga(n,e),ya(n,e)}(e,{target:(n=t?.target,n?"jsonSchema7"===n||"draft-7"===n?"draft-7":"jsonSchema2019-09"===n||"draft-2020-12"===n?"draft-2020-12":"draft-7":"draft-7"),io:t?.pipeStrategy??"input"}):((e,t)=>{const n=(e=>{const t=(e=>"string"==typeof e?{...Sd,name:e}:{...Sd,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let r=t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:tl(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Od(n)}),{}):void 0;const s="title"===t?.nameStrategy?void 0:t?.name,a=tl(e._def,void 0===s?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??Od(n),o=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=void 0===s?r?{...a,[n.definitionPath]:r}:a:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:a}};return"jsonSchema7"===n.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"});var n}function al(e){const t=Xa(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=eo(n);if("string"!=typeof r)throw new Error("Schema method literal must be a string");return r}function ol(e,t){const n=Wa(e,t);if(!n.success)throw n.error;return n.data}class il{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(ic,e=>{this._oncancel(e)}),this.setNotificationHandler(Ec,e=>{this._onprogress(e)}),this.setRequestHandler(kc,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(jc,async(e,t)=>{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new wd(nc.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ac,async(e,t)=>{const n=async()=>{const r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),"response"===e.type)r(t);else{const e=t;r(new wd(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${n}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const s=await this._taskStore.getTask(r,t.sessionId);if(!s)throw new wd(nc.InvalidParams,`Task not found: ${r}`);if(!kd(s.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(kd(s.status)){const e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Ai]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Mc,async(e,t)=>{try{const{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new wd(nc.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Zc,async(e,t)=>{try{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new wd(nc.InvalidParams,`Task not found: ${e.params.taskId}`);if(kd(n.status))throw new wd(nc.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new wd(nc.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){if(e instanceof wd)throw e;throw new wd(nc.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,n,r,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:r})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),wd.fromError(nc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};const r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var n;r?.(e,t),tc(e)||(n=e,rc.safeParse(n).success)?this._onresponse(e):Yi(e)?this._onrequest(e,t):(e=>Qi.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const t=wd.fromError(nc.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,s=e.params?._meta?.[Ai]?.taskId;if(void 0===n){const t={jsonrpc:"2.0",id:e.id,error:{code:nc.MethodNotFound,message:"Method not found"}};return void(s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const o=(i=e.params,Hi.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,u={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{const n={relatedRequestId:e.id};s&&(n.relatedTask={taskId:s}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{const a={...r,relatedRequestId:e.id};s&&!a.relatedTask&&(a.relatedTask={taskId:s});const o=a.relatedTask?.taskId??s;return o&&c&&await c.updateTaskStatus(o,"input_required"),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async t=>{if(a.signal.aborted)return;const n={result:t,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))},async t=>{if(a.signal.aborted)return;const n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:nc.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:n,timestamp:Date.now()},r?.sessionId):await(r?.send(n))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,r=Number(t),s=this._progressHandlers.get(r);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){return this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),void a(e)}s(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n)return this._requestResolvers.delete(t),void(tc(e)?n(e):n(new wd(e.error.code,e.error.message,e.error.data)));const r=this._responseHandlers.get(t);if(void 0===r)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(tc(e)&&e.result&&"object"==typeof e.result){const n=e.result;if(n.task&&"object"==typeof n.task){const e=n.task;"string"==typeof e.taskId&&(s=!0,this._taskProgressTokens.set(e.taskId,t))}}s||this._progressHandlers.delete(t),tc(e)?r(e):r(wd.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,n){const{task:r}=n??{};if(!r){try{const r=await this.request(e,t,n);yield{type:"result",result:r}}catch(e){yield{type:"error",error:e instanceof wd?e:new wd(nc.InternalError,String(e))}}return}let s;try{const r=await this.request(e,Pc,n);if(!r.task)throw new wd(nc.InternalError,"Task creation did not return a task");for(s=r.task.taskId,yield{type:"taskCreated",task:r.task};;){const e=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:e},kd(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:s},t,n);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new wd(nc.InternalError,`Task ${s} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new wd(nc.InternalError,`Task ${s} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:s},t,n);return void(yield{type:"result",result:e})}const r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof wd?e:new wd(nc.InternalError,String(e))}}}request(e,t,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a,task:o,relatedTask:i}=n??{};return new Promise((c,u)=>{const d=e=>{u(e)};if(!this._transport)return void d(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){return void d(e)}n?.signal?.throwIfAborted();const l=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:l};n?.onprogress&&(this._progressHandlers.set(l,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:l}}),o&&(p.params={...p.params,task:o}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Ai]:i}});const h=e=>{this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:l,reason:String(e)}},{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof wd?e:new wd(nc.RequestTimeout,String(e));u(t)};this._responseHandlers.set(l,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return u(e);try{const n=Wa(t,e.result);n.success?c(n.data):u(n.error)}catch(e){u(e)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const m=n?.timeout??6e4;this._setupTimeout(l,m,n?.maxTotalTimeout,()=>h(wd.fromError(nc.RequestTimeout,"Request timed out",{timeout:m})),n?.resetTimeoutOnProgress??!1);const f=i?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(l);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${l}`))};this._requestResolvers.set(l,e),this._enqueueTaskMessage(f,{type:"request",message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(l),u(e)})}else this._transport.send(p,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(l),u(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},zc,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Dc,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Lc,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ai]:t.relatedTask}}};return void await this._enqueueTaskMessage(n,{type:"notification",message:r,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Ai]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))})}let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Ai]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){const n=al(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{const s=ol(e,n);return Promise.resolve(t(s,r))})}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,t){const n=al(e);this._notificationHandlers.set(n,n=>{const r=ol(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const t of n)if("request"===t.type&&Yi(t.message)){const n=t.message.id,r=this._requestResolvers.get(n);r?(r(new wd(nc.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new wd(nc.InvalidRequest,"Request cancelled"));const s=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new wd(nc.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const r=await n.getTask(e,t);if(!r)throw new wd(nc.InvalidParams,"Failed to retrieve task: Task not found");return r},storeTaskResult:async(e,r,s)=>{await n.storeTaskResult(e,r,s,t);const a=await n.getTask(e,t);if(a){const t=Cc.parse({method:"notifications/tasks/status",params:a});await this.notification(t),kd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,s)=>{const a=await n.getTask(e,t);if(!a)throw new wd(nc.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(kd(a.status))throw new wd(nc.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,s,t);const o=await n.getTask(e,t);if(o){const t=Cc.parse({method:"notifications/tasks/status",params:o});await this.notification(t),kd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}function cl(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ul(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dl,ll={exports:{}},pl={},hl={},ml={},fl={},gl={},yl={};function _l(){return dl||(dl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class r extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){const n=[e[0]];let s=0;for(;s<t.length;)i(n,t[s]),n.push(e[++s]);return new r(n)}e._Code=r,e.nil=new r(""),e._=s;const a=new r("+");function o(e,...t){const n=[u(e[0])];let s=0;for(;s<t.length;)n.push(a),i(n,t[s]),n.push(a,u(e[++s]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const n=c(e[t-1],e[t+1]);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(n),new r(n)}function i(e,t){var s;t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push("number"==typeof(s=t)||"boolean"==typeof s||null===s?s:u(Array.isArray(s)?s.join(","):s))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=o,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`},e.stringify=function(e){return new r(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new r(`.${t}`):s`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new r(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new r(e.toString())}}(yl)),yl}var vl,wl,bl={};function kl(){return vl||(vl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_l();class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var r;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class s{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,n;if((null===(n=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===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}}}e.Scope=s;class a extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=t._`.${new t.Name(n)}[${r}]`}}e.ValueScopeName=a;const o=t._`\n`;e.ValueScope=class extends s{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){var n;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const r=this.toName(e),{prefix:s}=r,a=null!==(n=t.key)&&void 0!==n?n:t.ref;let o=this._values[s];if(o){const e=o.get(a);if(e)return e}else o=this._values[s]=new Map;o.set(a,r);const i=this._scope[s]||(this._scope[s]=[]),c=i.length;return i[c]=t.ref,r.setValue(t,{property:s,itemIndex:c}),r}getValue(e,t){const n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(void 0===n.scopePath)throw new Error(`CodeGen: name "${n}" has no value`);return t._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(s,a,o={},i){let c=t.nil;for(const u in s){const d=s[u];if(!d)continue;const l=o[u]=o[u]||new Map;d.forEach(s=>{if(l.has(s))return;l.set(s,r.Started);let o=a(s);if(o){const n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${n} ${s} = ${o};${this.opts._n}`}else{if(!(o=null==i?void 0:i(s)))throw new n(s);c=t._`${c}${o}${this.opts._n}`}l.set(s,r.Completed)})}return c}}}(bl)),bl}function $l(){return wl||(wl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=_l(),n=kl();var r=_l();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var s=kl();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class a{optimizeNodes(){return this}optimizeNames(e,t){return this}}class o extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){const r=e?n.varKinds.var:this.varKind,s=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=N(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=N(this.rhs,e,n),this}get names(){return O(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class d extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class l extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=N(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:n}=this;let r=n.length;for(;r--;){const s=n[r];s.optimizeNames(e,t)||(I(e,s.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>x(e,t.names),{})}}class m extends h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class f extends h{}class g extends m{}g.kind="else";class y extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(P(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var n;if(this.else=null===(n=this.else)||void 0===n?void 0:n.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=N(this.condition,e,t),this}get names(){const e=super.names;return O(e,this.condition),this.else&&x(e,this.else.names),e}}y.kind="if";class _ extends m{}_.kind="for";class v extends _{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=N(this.iteration,e,t),this}get names(){return x(super.names,this.iteration.names)}}class w extends _{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:r,from:s,to:a}=this;return`for(${t} ${r}=${s}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){const e=O(super.names,this.from);return O(e,this.to)}}class b extends _{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=N(this.iterable,e,t),this}get names(){return x(super.names,this.iterable.names)}}class k extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}k.kind="func";class $ extends h{render(e){return"return "+super.render(e)}}$.kind="return";class S extends m{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),null===(n=this.catch)||void 0===n||n.optimizeNames(e,t),null===(r=this.finally)||void 0===r||r.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&x(e,this.catch.names),this.finally&&x(e,this.finally.names),e}}class E extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}E.kind="catch";class T extends m{render(e){return"finally"+super.render(e)}}function x(e,t){for(const n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function O(e,n){return n instanceof t._CodeOrName?x(e,n.names):e}function N(e,n,r){return e instanceof t.Name?a(e):(s=e)instanceof t._Code&&s._items.some(e=>e instanceof t.Name&&1===n[e.str]&&void 0!==r[e.str])?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=a(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;var s;function a(e){const t=r[e.str];return void 0===t||1!==n[e.str]?e:(delete n[e.str],t)}}function I(e,t){for(const n in t)e[n]=(e[n]||0)-(t[n]||0)}function P(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}T.kind="finally",e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){const s=this._scope.toName(t);return void 0!==n&&r&&(this._constants[s.str]=n),this._leafNode(new o(e,s,n)),s}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new i(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const n=["{"];for(const[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,t.addCodeArg)(n,s));return n.push("}"),new t._Code(n)}if(e,t,n){if(this._blockNode(new y(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new v(e),t)}forRange(e,t,r,s,a=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const o=this._scope.toName(e);return this._for(new w(a,o,t,r),()=>s(o))}forOf(e,r,s,a=n.varKinds.const){const o=this._scope.toName(e);if(this.opts.es5){const e=r instanceof t.Name?r:this.var("_arr",r);return this.forRange("_i",0,t._`${e}.length`,n=>{this.var(o,t._`${e}[${n}]`),s(o)})}return this._for(new b("of",a,o,r),()=>s(o))}forIn(e,r,s,a=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${r})`,s);const o=this._scope.toName(e);return this._for(new b("in",a,o,r),()=>s(o))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new d(e))}return(e){const t=new $;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');const r=new S;if(this._blockNode(r),this.code(e),t){const e=this.name("e");this._currNode=r.catch=new E(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(E,T)}throw(e){return this._leafNode(new l(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const n=this._nodes.length-t;if(n<0||void 0!==e&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,s){return this._blockNode(new k(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(k)}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,t){const n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=P;const R=j(e.operators.AND);e.and=function(...e){return e.reduce(R)};const C=j(e.operators.OR);function j(e){return(n,r)=>n===t.nil?r:r===t.nil?n:t._`${z(n)} ${e} ${z(r)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(C)}}(gl)),gl}var Sl,El={};function Tl(){if(Sl)return El;Sl=1,Object.defineProperty(El,"__esModule",{value:!0}),El.checkStrictMode=El.getErrorPath=El.Type=El.useFunc=El.setEvaluated=El.evaluatedPropsToName=El.mergeEvaluated=El.eachItem=El.unescapeJsonPointer=El.escapeJsonPointer=El.escapeFragment=El.unescapeFragment=El.schemaRefOrVal=El.schemaHasRulesButRef=El.schemaHasRules=El.checkUnknownRules=El.alwaysValidSchema=El.toHash=void 0;const e=$l(),t=_l();function n(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema)return;if("boolean"==typeof t)return;const s=r.RULES.keywords;for(const n in t)s[n]||l(e,`unknown keyword: "${n}"`)}function r(e,t){if("boolean"==typeof e)return!e;for(const n in e)if(t[n])return!0;return!1}function s(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function a(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function o({mergeNames:t,mergeToName:n,mergeValues:r,resultToName:s}){return(a,o,i,c)=>{const u=void 0===i?o:i instanceof e.Name?(o instanceof e.Name?t(a,o,i):n(a,o,i),i):o instanceof e.Name?(n(a,i,o),o):r(o,i);return c!==e.Name||u instanceof e.Name?u:s(a,u)}}function i(t,n){if(!0===n)return t.var("props",!0);const r=t.var("props",e._`{}`);return void 0!==n&&c(t,r,n),r}function c(t,n,r){Object.keys(r).forEach(r=>t.assign(e._`${n}${(0,e.getProperty)(r)}`,!0))}El.toHash=function(e){const t={};for(const n of e)t[n]=!0;return t},El.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(n(e,t),!r(t,e.self.RULES.all))},El.checkUnknownRules=n,El.schemaHasRules=r,El.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const n in e)if("$ref"!==n&&t.all[n])return!0;return!1},El.schemaRefOrVal=function({topSchemaRef:t,schemaPath:n},r,s,a){if(!a){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return e._`${r}`}return e._`${t}${n}${(0,e.getProperty)(s)}`},El.unescapeFragment=function(e){return a(decodeURIComponent(e))},El.escapeFragment=function(e){return encodeURIComponent(s(e))},El.escapeJsonPointer=s,El.unescapeJsonPointer=a,El.eachItem=function(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)},El.mergeEvaluated={props:o({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>{t.if(e._`${n} === true`,()=>t.assign(r,!0),()=>t.assign(r,e._`${r} || {}`).code(e._`Object.assign(${r}, ${n})`))}),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>{!0===n?t.assign(r,!0):(t.assign(r,e._`${r} || {}`),c(t,r,n))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:i}),items:o({mergeNames:(t,n,r)=>t.if(e._`${r} !== true && ${n} !== undefined`,()=>t.assign(r,e._`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(t,n,r)=>t.if(e._`${r} !== true`,()=>t.assign(r,!0===n||e._`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},El.evaluatedPropsToName=i,El.setEvaluated=c;const u={};var d;function l(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,!0===n)throw new Error(t);e.self.logger.warn(t)}}return El.useFunc=function(e,n){return e.scopeValue("func",{ref:n,code:u[n.code]||(u[n.code]=new t._Code(n.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(d||(El.Type=d={})),El.getErrorPath=function(t,n,r){if(t instanceof e.Name){const s=n===d.Num;return r?s?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:s?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,e.getProperty)(t).toString():"/"+s(t)},El.checkStrictMode=l,El}var xl,Ol,Nl,Il={};function Pl(){if(xl)return Il;xl=1,Object.defineProperty(Il,"__esModule",{value:!0});const e=$l(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Il.default=t,Il}function Rl(){return Ol||(Ol=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=$l(),n=Tl(),r=Pl();function s(e,n){const s=e.const("err",n);e.if(t._`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,t._`[${s}]`),t._`${r.default.vErrors}.push(${s})`),e.code(t._`${r.default.errors}++`)}function a(e,n){const{gen:r,validateName:s,schemaEnv:a}=e;a.$async?r.throw(t._`new ${e.ValidationError}(${n})`):(r.assign(t._`${s}.errors`,n),r.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?t.str`"${e}" keyword must be ${n} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(n,r=e.keywordError,o,c){const{it:u}=n,{gen:d,compositeRule:l,allErrors:p}=u,h=i(n,r,o);(null!=c?c:l||p)?s(d,h):a(u,t._`[${h}]`)},e.reportExtraError=function(t,n=e.keywordError,o){const{it:c}=t,{gen:u,compositeRule:d,allErrors:l}=c;s(u,i(t,n,o)),d||l||a(c,r.default.vErrors)},e.resetErrorsCount=function(e,n){e.assign(r.default.errors,n),e.if(t._`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign(t._`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:n,schemaValue:s,data:a,errsCount:o,it:i}){if(void 0===o)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",o,r.default.errors,o=>{e.const(c,t._`${r.default.vErrors}[${o}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${n}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,s),e.assign(t._`${c}.data`,a))})};const o={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,n,s){const{createErrors:a}=e.it;return!1===a?t._`{}`:function(e,n,s={}){const{gen:a,it:i}=e,d=[c(i,s),u(e,s)];return function(e,{params:n,message:s},a){const{keyword:i,data:c,schemaValue:u,it:d}=e,{opts:l,propertyName:p,topSchemaRef:h,schemaPath:m}=d;a.push([o.keyword,i],[o.params,"function"==typeof n?n(e):n||t._`{}`]),l.messages&&a.push([o.message,"function"==typeof s?s(e):s]),l.verbose&&a.push([o.schema,u],[o.parentSchema,t._`${h}${m}`],[r.default.data,c]),p&&a.push([o.propertyName,p])}(e,n,d),a.object(...d)}(e,n,s)}function c({errorPath:e},{instancePath:s}){const a=s?t.str`${e}${(0,n.getErrorPath)(s,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function u({keyword:e,it:{errSchemaPath:r}},{schemaPath:s,parentSchema:a}){let i=a?r:t.str`${r}/${e}`;return s&&(i=t.str`${i}${(0,n.getErrorPath)(s,n.Type.Str)}`),[o.schemaPath,i]}}(fl)),fl}var Cl,jl={},zl={};function Al(){if(Cl)return zl;Cl=1,Object.defineProperty(zl,"__esModule",{value:!0}),zl.getRules=zl.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return zl.isJSONType=function(t){return"string"==typeof t&&e.has(t)},zl.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},zl}var Ml,Dl,Zl={};function Ll(){if(Ml)return Zl;function e(e,n){return n.rules.some(n=>t(e,n))}function t(e,t){var n;return void 0!==e[t.keyword]||(null===(n=t.definition.implements)||void 0===n?void 0:n.some(t=>void 0!==e[t]))}return Ml=1,Object.defineProperty(Zl,"__esModule",{value:!0}),Zl.shouldUseRule=Zl.shouldUseGroup=Zl.schemaHasRulesForType=void 0,Zl.schemaHasRulesForType=function({schema:t,self:n},r){const s=n.RULES.types[r];return s&&!0!==s&&e(t,s)},Zl.shouldUseGroup=e,Zl.shouldUseRule=t,Zl}function Fl(){if(Dl)return jl;Dl=1,Object.defineProperty(jl,"__esModule",{value:!0}),jl.reportTypeError=jl.checkDataTypes=jl.checkDataType=jl.coerceAndCheckDataType=jl.getJSONTypes=jl.getSchemaTypes=jl.DataType=void 0;const e=Al(),t=Ll(),n=Rl(),r=$l(),s=Tl();var a;function o(t){const n=Array.isArray(t)?t:t?[t]:[];if(n.every(e.isJSONType))return n;throw new Error("type must be JSONType or JSONType[]: "+n.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(a||(jl.DataType=a={})),jl.getSchemaTypes=function(e){const t=o(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},jl.getJSONTypes=o,jl.coerceAndCheckDataType=function(e,n){const{gen:s,data:o,opts:c}=e,d=function(e,t){return t?e.filter(e=>i.has(e)||"array"===t&&"array"===e):[]}(n,c.coerceTypes),p=n.length>0&&!(0===d.length&&1===n.length&&(0,t.schemaHasRulesForType)(e,n[0]));if(p){const t=u(n,o,c.strictNumbers,a.Wrong);s.if(t,()=>{d.length?function(e,t,n){const{gen:s,data:a,opts:o}=e,c=s.let("dataType",r._`typeof ${a}`),d=s.let("coerced",r._`undefined`);"array"===o.coerceTypes&&s.if(r._`${c} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>s.assign(a,r._`${a}[0]`).assign(c,r._`typeof ${a}`).if(u(t,a,o.strictNumbers),()=>s.assign(d,a))),s.if(r._`${d} !== undefined`);for(const e of n)(i.has(e)||"array"===e&&"array"===o.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void s.elseIf(r._`${c} == "number" || ${c} == "boolean"`).assign(d,r._`"" + ${a}`).elseIf(r._`${a} === null`).assign(d,r._`""`);case"number":return void s.elseIf(r._`${c} == "boolean" || ${a} === null
3
- || (${c} == "string" && ${a} && ${a} == +${a})`).assign(d,r._`+${a}`);case"integer":return void s.elseIf(r._`${c} === "boolean" || ${a} === null
4
- || (${c} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(d,r._`+${a}`);case"boolean":return void s.elseIf(r._`${a} === "false" || ${a} === 0 || ${a} === null`).assign(d,!1).elseIf(r._`${a} === "true" || ${a} === 1`).assign(d,!0);case"null":return s.elseIf(r._`${a} === "" || ${a} === 0 || ${a} === false`),void s.assign(d,null);case"array":s.elseIf(r._`${c} === "string" || ${c} === "number"
5
- || ${c} === "boolean" || ${a} === null`).assign(d,r._`[${a}]`)}}s.else(),l(e),s.endIf(),s.if(r._`${d} !== undefined`,()=>{s.assign(a,d),function({gen:e,parentData:t,parentDataProperty:n},s){e.if(r._`${t} !== undefined`,()=>e.assign(r._`${t}[${n}]`,s))}(e,d)})}(e,n,d):l(e)})}return p};const i=new Set(["string","number","integer","boolean","null"]);function c(e,t,n,s=a.Correct){const o=s===a.Correct?r.operators.EQ:r.operators.NEQ;let i;switch(e){case"null":return r._`${t} ${o} null`;case"array":i=r._`Array.isArray(${t})`;break;case"object":i=r._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=c(r._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=c();break;default:return r._`typeof ${t} ${o} ${e}`}return s===a.Correct?i:(0,r.not)(i);function c(e=r.nil){return(0,r.and)(r._`typeof ${t} == "number"`,e,n?r._`isFinite(${t})`:r.nil)}}function u(e,t,n,a){if(1===e.length)return c(e[0],t,n,a);let o;const i=(0,s.toHash)(e);if(i.array&&i.object){const e=r._`typeof ${t} != "object"`;o=i.null?e:r._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else o=r.nil;i.number&&delete i.integer;for(const e in i)o=(0,r.and)(o,c(e,t,n,a));return o}jl.checkDataType=c,jl.checkDataTypes=u;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?r._`{type: ${e}}`:r._`{type: ${t}}`};function l(e){const t=function(e){const{gen:t,data:n,schema:r}=e,a=(0,s.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:a,schemaValue:a,parentSchema:r,params:{},it:e}}(e);(0,n.reportError)(t,d)}return jl.reportTypeError=l,jl}var ql,Ul,Vl,Hl={},Jl={},Kl={};function Bl(){if(Ul)return Kl;Ul=1,Object.defineProperty(Kl,"__esModule",{value:!0}),Kl.validateUnion=Kl.validateArray=Kl.usePattern=Kl.callValidateCode=Kl.schemaProperties=Kl.allSchemaProperties=Kl.noPropertyInData=Kl.propertyInData=Kl.isOwnProperty=Kl.hasPropFunc=Kl.reportMissingProp=Kl.checkMissingProp=Kl.checkReportMissingProp=void 0;const e=$l(),t=Tl(),n=Pl(),r=Tl();function s(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function a(t,n,r){return e._`${s(t)}.call(${n}, ${r})`}function o(t,n,r,s){const o=e._`${n}${(0,e.getProperty)(r)} === undefined`;return s?(0,e.or)(o,(0,e.not)(a(t,n,r))):o}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}Kl.checkReportMissingProp=function(t,n){const{gen:r,data:s,it:a}=t;r.if(o(r,s,n,a.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${n}`},!0),t.error()})},Kl.checkMissingProp=function({gen:t,data:n,it:{opts:r}},s,a){return(0,e.or)(...s.map(s=>(0,e.and)(o(t,n,s,r.ownProperties),e._`${a} = ${s}`)))},Kl.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Kl.hasPropFunc=s,Kl.isOwnProperty=a,Kl.propertyInData=function(t,n,r,s){const o=e._`${n}${(0,e.getProperty)(r)} !== undefined`;return s?e._`${o} && ${a(t,n,r)}`:o},Kl.noPropertyInData=o,Kl.allSchemaProperties=i,Kl.schemaProperties=function(e,n){return i(n).filter(r=>!(0,t.alwaysValidSchema)(e,n[r]))},Kl.callValidateCode=function({schemaCode:t,data:r,it:{gen:s,topSchemaRef:a,schemaPath:o,errorPath:i},it:c},u,d,l){const p=l?e._`${t}, ${r}, ${a}${o}`:r,h=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,i)],[n.default.parentData,c.parentData],[n.default.parentDataProperty,c.parentDataProperty],[n.default.rootData,n.default.rootData]];c.opts.dynamicRef&&h.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const m=e._`${p}, ${s.object(...h)}`;return d!==e.nil?e._`${u}.call(${d}, ${m})`:e._`${u}(${m})`};const c=e._`new RegExp`;return Kl.usePattern=function({gen:t,it:{opts:n}},s){const a=n.unicodeRegExp?"u":"",{regExp:o}=n.code,i=o(s,a);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===o.code?c:(0,r.useFunc)(t,o)}(${s}, ${a})`})},Kl.validateArray=function(n){const{gen:r,data:s,keyword:a,it:o}=n,i=r.name("valid");if(o.allErrors){const e=r.let("valid",!0);return c(()=>r.assign(e,!1)),e}return r.var(i,!0),c(()=>r.break()),i;function c(o){const c=r.const("len",e._`${s}.length`);r.forRange("i",0,c,s=>{n.subschema({keyword:a,dataProp:s,dataPropType:t.Type.Num},i),r.if((0,e.not)(i),o)})}},Kl.validateUnion=function(n){const{gen:r,schema:s,keyword:a,it:o}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(s.some(e=>(0,t.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;const i=r.let("valid",!1),c=r.name("_valid");r.block(()=>s.forEach((t,s)=>{const o=n.subschema({keyword:a,schemaProp:s,compositeRule:!0},c);r.assign(i,e._`${i} || ${c}`),n.mergeValidEvaluated(o,c)||r.if((0,e.not)(i))})),n.result(i,()=>n.reset(),()=>n.error(!0))},Kl}var Wl,Gl,Xl,Yl={},Ql={};function ep(){return Xl||(Xl=1,Gl=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var r,s,a;if(Array.isArray(t)){if((r=t.length)!=n.length)return!1;for(s=r;0!==s--;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((r=(a=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(s=r;0!==s--;)if(!Object.prototype.hasOwnProperty.call(n,a[s]))return!1;for(s=r;0!==s--;){var o=a[s];if(!e(t[o],n[o]))return!1}return!0}return t!=t&&n!=n}),Gl}var tp,np,rp,sp={exports:{}};function ap(){if(tp)return sp.exports;tp=1;var e=sp.exports=function(e,n,r){"function"==typeof n&&(r=n,n={}),t(n,"function"==typeof(r=n.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function t(r,s,a,o,i,c,u,d,l,p){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var h in s(o,i,c,u,d,l,p),o){var m=o[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var f=0;f<m.length;f++)t(r,s,a,m[f],i+"/"+h+"/"+f,c,i,h,o,f)}else if(h in e.propsKeywords){if(m&&"object"==typeof m)for(var g in m)t(r,s,a,m[g],i+"/"+h+"/"+n(g),c,i,h,o,g)}else(h in e.keywords||r.allKeys&&!(h in e.skipKeywords))&&t(r,s,a,m,i+"/"+h,c,i,h,o)}a(o,i,c,u,d,l,p)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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},sp.exports}function op(){if(np)return Ql;np=1,Object.defineProperty(Ql,"__esModule",{value:!0}),Ql.getSchemaRefs=Ql.resolveUrl=Ql.normalizeId=Ql._getFullPath=Ql.getFullPath=Ql.inlineRef=void 0;const e=Tl(),t=ep(),n=ap(),r=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);Ql.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!a(e):!!t&&o(e)<=t)};const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(e){for(const t in e){if(s.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(a))return!0;if("object"==typeof n&&a(n))return!0}return!1}function o(t){let n=0;for(const s in t){if("$ref"===s)return 1/0;if(n++,!r.has(s)&&("object"==typeof t[s]&&(0,e.eachItem)(t[s],e=>n+=o(e)),n===1/0))return 1/0}return n}function i(e,t="",n){!1!==n&&(t=d(t));const r=e.parse(t);return c(e,r)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}Ql.getFullPath=i,Ql._getFullPath=c;const u=/#\/?$/;function d(e){return e?e.replace(u,""):""}Ql.normalizeId=d,Ql.resolveUrl=function(e,t,n){return n=d(n),e.resolve(t,n)};const l=/^[a-z_][-a-z0-9._]*$/i;return Ql.getSchemaRefs=function(e,r){if("boolean"==typeof e)return{};const{schemaId:s,uriResolver:a}=this.opts,o=d(e[s]||r),c={"":o},u=i(a,o,!1),p={},h=new Set;return n(e,{allKeys:!0},(e,t,n,r)=>{if(void 0===r)return;const a=u+t;let o=c[r];function i(t){const n=this.opts.uriResolver.resolve;if(t=d(o?n(o,t):t),h.has(t))throw f(t);h.add(t);let r=this.refs[t];return"string"==typeof r&&(r=this.refs[r]),"object"==typeof r?m(e,r.schema,t):t!==d(a)&&("#"===t[0]?(m(e,p[t],t),p[t]=e):this.refs[t]=a),t}function g(e){if("string"==typeof e){if(!l.test(e))throw new Error(`invalid anchor "${e}"`);i.call(this,`#${e}`)}}"string"==typeof e[s]&&(o=i.call(this,e[s])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=o}),p;function m(e,n,r){if(void 0!==n&&!t(e,n))throw f(r)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},Ql}function ip(){if(rp)return hl;rp=1,Object.defineProperty(hl,"__esModule",{value:!0}),hl.getData=hl.KeywordCxt=hl.validateFunctionCode=void 0;const e=function(){if(Nl)return ml;Nl=1,Object.defineProperty(ml,"__esModule",{value:!0}),ml.boolOrEmptySchema=ml.topBoolOrEmptySchema=void 0;const e=Rl(),t=$l(),n=Pl(),r={message:"boolean schema is false"};function s(t,n){const{gen:s,data:a}=t,o={gen:s,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(o,r,void 0,n)}return ml.topBoolOrEmptySchema=function(e){const{gen:r,schema:a,validateName:o}=e;!1===a?s(e,!1):"object"==typeof a&&!0===a.$async?r.return(n.default.data):(r.assign(t._`${o}.errors`,null),r.return(!0))},ml.boolOrEmptySchema=function(e,t){const{gen:n,schema:r}=e;!1===r?(n.var(t,!1),s(e)):n.var(t,!0)},ml}(),t=Fl(),n=Ll(),r=Fl(),s=function(){if(ql)return Hl;ql=1,Object.defineProperty(Hl,"__esModule",{value:!0}),Hl.assignDefaults=void 0;const e=$l(),t=Tl();function n(n,r,s){const{gen:a,compositeRule:o,data:i,opts:c}=n;if(void 0===s)return;const u=e._`${i}${(0,e.getProperty)(r)}`;if(o)return void(0,t.checkStrictMode)(n,`default is ignored for: ${u}`);let d=e._`${u} === undefined`;"empty"===c.useDefaults&&(d=e._`${d} || ${u} === null || ${u} === ""`),a.if(d,e._`${u} = ${(0,e.stringify)(s)}`)}return Hl.assignDefaults=function(e,t){const{properties:r,items:s}=e.schema;if("object"===t&&r)for(const t in r)n(e,t,r[t].default);else"array"===t&&Array.isArray(s)&&s.forEach((t,r)=>n(e,r,t.default))},Hl}(),a=function(){if(Vl)return Jl;Vl=1,Object.defineProperty(Jl,"__esModule",{value:!0}),Jl.validateKeywordUsage=Jl.validSchemaType=Jl.funcKeywordCode=Jl.macroKeywordCode=void 0;const e=$l(),t=Pl(),n=Bl(),r=Rl();function s(t){const{gen:n,data:r,it:s}=t;n.if(s.parentData,()=>n.assign(r,e._`${s.parentData}[${s.parentDataProperty}]`))}function a(t,n,r){if(void 0===r)throw new Error(`keyword "${n}" failed to compile`);return t.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,e.stringify)(r)})}return Jl.macroKeywordCode=function(t,n){const{gen:r,keyword:s,schema:o,parentSchema:i,it:c}=t,u=n.macro.call(c.self,o,i,c),d=a(r,s,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const l=r.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${s}`,topSchemaRef:d,compositeRule:!0},l),t.pass(l,()=>t.error(!0))},Jl.funcKeywordCode=function(o,i){var c;const{gen:u,keyword:d,schema:l,parentSchema:p,$data:h,it:m}=o;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,i);const f=!h&&i.compile?i.compile.call(m.self,l,p,m):i.validate,g=a(u,d,f),y=u.let("valid");function _(r=(i.async?e._`await `:e.nil)){const s=m.opts.passContext?t.default.this:t.default.self,a=!("compile"in i&&!h||!1===i.schema);u.assign(y,e._`${r}${(0,n.callValidateCode)(o,g,s,a)}`,i.modifying)}function v(t){var n;u.if((0,e.not)(null!==(n=i.valid)&&void 0!==n?n:y),t)}o.block$data(y,function(){if(!1===i.errors)_(),i.modifying&&s(o),v(()=>o.error());else{const n=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>_(e._`await `),n=>u.assign(y,!1).if(e._`${n} instanceof ${m.ValidationError}`,()=>u.assign(t,e._`${n}.errors`),()=>u.throw(n))),t}():function(){const t=e._`${g}.errors`;return u.assign(t,null),_(e.nil),t}();i.modifying&&s(o),v(()=>function(n,s){const{gen:a}=n;a.if(e._`Array.isArray(${s})`,()=>{a.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${s} : ${t.default.vErrors}.concat(${s})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,r.extendErrors)(n)},()=>n.error())}(o,n))}}),o.ok(null!==(c=i.valid)&&void 0!==c?c:y)},Jl.validSchemaType=function(e,t,n=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e)},Jl.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:r},s,a){if(Array.isArray(s.keyword)?!s.keyword.includes(a):s.keyword!==a)throw new Error("ajv implementation error");const o=s.dependencies;if(null==o?void 0:o.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(e[a])){const e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}},Jl}(),o=function(){if(Wl)return Yl;Wl=1,Object.defineProperty(Yl,"__esModule",{value:!0}),Yl.extendSubschemaMode=Yl.extendSubschemaData=Yl.getSubschema=void 0;const e=$l(),t=Tl();return Yl.getSubschema=function(n,{keyword:r,schemaProp:s,schema:a,schemaPath:o,errSchemaPath:i,topSchemaRef:c}){if(void 0!==r&&void 0!==a)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==r){const a=n.schema[r];return void 0===s?{schema:a,schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}`,errSchemaPath:`${n.errSchemaPath}/${r}`}:{schema:a[s],schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(r)}${(0,e.getProperty)(s)}`,errSchemaPath:`${n.errSchemaPath}/${r}/${(0,t.escapeFragment)(s)}`}}if(void 0!==a){if(void 0===o||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},Yl.extendSubschemaData=function(n,r,{dataProp:s,dataPropType:a,data:o,dataTypes:i,propertyName:c}){if(void 0!==o&&void 0!==s)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=r;if(void 0!==s){const{errorPath:o,dataPathArr:i,opts:c}=r;d(u.let("data",e._`${r.data}${(0,e.getProperty)(s)}`,!0)),n.errorPath=e.str`${o}${(0,t.getErrorPath)(s,a,c.jsPropertySyntax)}`,n.parentDataProperty=e._`${s}`,n.dataPathArr=[...i,n.parentDataProperty]}function d(e){n.data=e,n.dataLevel=r.dataLevel+1,n.dataTypes=[],r.definedProperties=new Set,n.parentData=r.data,n.dataNames=[...r.dataNames,e]}void 0!==o&&(d(o instanceof e.Name?o:u.let("data",o,!0)),void 0!==c&&(n.propertyName=c)),i&&(n.dataTypes=i)},Yl.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:a}){void 0!==r&&(e.compositeRule=r),void 0!==s&&(e.createErrors=s),void 0!==a&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n},Yl}(),i=$l(),c=Pl(),u=op(),d=Tl(),l=Rl();function p({gen:e,validateName:t,schema:n,schemaEnv:r,opts:s},a){s.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,r.$async,()=>{e.code(i._`"use strict"; ${h(n,s)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,s),e.code(a)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(s)}`,r.$async,()=>e.code(h(n,s)).code(a))}function h(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?i._`/*# sourceURL=${n} */`:i.nil}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function f(e){return"boolean"!=typeof e.schema}function g(e){(0,d.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:r,self:s}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function y(e,n){if(e.opts.jtd)return v(e,[],!1,n);const r=(0,t.getSchemaTypes)(e.schema);v(e,r,!(0,t.coerceAndCheckDataType)(e,r),n)}function _({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:s}){const a=n.$comment;if(!0===s.$comment)e.code(i._`${c.default.self}.logger.log(${a})`);else if("function"==typeof s.$comment){const n=i.str`${r}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${a}, ${n}, ${s}.schema)`)}}function v(e,t,s,a){const{gen:o,schema:u,data:l,allErrors:p,opts:h,self:m}=e,{RULES:f}=m;function g(d){(0,n.shouldUseGroup)(u,d)&&(d.type?(o.if((0,r.checkDataType)(d.type,l,h.strictNumbers)),w(e,d),1===t.length&&t[0]===d.type&&s&&(o.else(),(0,r.reportTypeError)(e)),o.endIf()):w(e,d),p||o.if(i._`${c.default.errors} === ${a||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(u,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{b(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const n=[];for(const r of e.dataTypes)b(t,r)?n.push(r):t.includes("integer")&&"number"===r&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const s in r){const a=r[s];if("object"==typeof a&&(0,n.shouldUseRule)(e.schema,a)){const{type:n}=a.definition;n.length&&!n.some(e=>{return r=e,(n=t).includes(r)||"number"===r&&n.includes("integer");var n,r})&&k(e,`missing type "${n.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),o.block(()=>{for(const e of f.rules)g(e);g(f.post)})):o.block(()=>S(e,"$ref",f.all.$ref.definition))}function w(e,t){const{gen:r,schema:a,opts:{useDefaults:o}}=e;o&&(0,s.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,n.shouldUseRule)(a,r)&&S(e,r.keyword,r.definition,t.type)})}function b(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}hl.validateFunctionCode=function(t){f(t)&&(g(t),m(t))?function(e){const{schema:t,opts:n,gen:r}=e;p(e,()=>{n.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,"default is ignored in the schema root")}(e),r.let(c.default.vErrors,null),r.let(c.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",i._`${n}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),y(e),function(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:s,opts:a}=e;n.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${s}(${c.default.vErrors})`)):(t.assign(i._`${r}.errors`,c.default.vErrors),a.unevaluated&&function({gen:e,evaluated:t,props:n,items:r}){n instanceof i.Name&&e.assign(i._`${t}.props`,n),r instanceof i.Name&&e.assign(i._`${t}.items`,r)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class ${constructor(e,t,n){if((0,a.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",x(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,n){this.failResult((0,i.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?l.reportExtraError:l.reportError)(this,this.def.error,t)}$dataError(){(0,l.reportError)(this,this.def.$dataError||l.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,l.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=i.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:n,schemaCode:r,schemaType:s,def:a}=this;n.if((0,i.or)(i._`${r} === undefined`,t)),e!==i.nil&&n.assign(e,!0),(s.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:s,it:a}=this;return(0,i.or)(function(){if(n.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return i._`${(0,r.checkDataTypes)(e,t,a.opts.strictNumbers,r.DataType.Wrong)}`}return i.nil}(),function(){if(s.validateSchema){const n=e.scopeValue("validate$data",{ref:s.validateSchema});return i._`!${n}(${t})`}return i.nil}())}subschema(t,n){const r=(0,o.getSubschema)(this.it,t);(0,o.extendSubschemaData)(r,this.it,t),(0,o.extendSubschemaMode)(r,t);const s={...this.it,...r,items:void 0,props:void 0};return function(t,n){f(t)&&(g(t),m(t))?function(e,t){const{schema:n,gen:r,opts:s}=e;s.$comment&&n.$comment&&_(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const a=r.const("_errs",c.default.errors);y(e,a),r.var(t,i._`${a} === ${c.default.errors}`)}(t,n):(0,e.boolOrEmptySchema)(t,n)}(s,n),s}mergeEvaluated(e,t){const{it:n,gen:r}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:r}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return r.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function S(e,t,n,r){const s=new $(e,n,t);"code"in n?n.code(s,r):s.$data&&n.validate?(0,a.funcKeywordCode)(s,n):"macro"in n?(0,a.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,a.funcKeywordCode)(s,n)}hl.KeywordCxt=$;const E=/^\/(?:[^~]|~0|~1)*$/,T=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function x(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let s,a;if(""===e)return c.default.rootData;if("/"===e[0]){if(!E.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);s=e,a=c.default.rootData}else{const o=T.exec(e);if(!o)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+o[1];if(s=o[2],"#"===s){if(i>=t)throw new Error(l("property/index",i));return r[t-i]}if(i>t)throw new Error(l("data",i));if(a=n[t-i],!s)return a}let o=a;const u=s.split("/");for(const e of u)e&&(a=i._`${a}${(0,i.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=i._`${o} && ${a}`);return o;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}return hl.getData=x,hl}var cp,up={};function dp(){if(cp)return up;cp=1,Object.defineProperty(up,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return up.default=e,up}var lp,pp={};function hp(){if(lp)return pp;lp=1,Object.defineProperty(pp,"__esModule",{value:!0});const e=op();class t extends Error{constructor(t,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,e.resolveUrl)(t,n,r),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return pp.default=t,pp}var mp,fp={};function gp(){if(mp)return fp;mp=1,Object.defineProperty(fp,"__esModule",{value:!0}),fp.resolveSchema=fp.getCompilingSchema=fp.resolveRef=fp.compileSchema=fp.SchemaEnv=void 0;const e=$l(),t=dp(),n=Pl(),r=op(),s=Tl(),a=ip();class o{constructor(e){var t;let n;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,r.normalizeId)(null==n?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==n?void 0:n.$async,this.refs={}}}function i(s){const o=u.call(this,s);if(o)return o;const i=(0,r.getFullPath)(this.opts.uriResolver,s.root.baseId),{es5:c,lines:d}=this.opts.code,{ownProperties:l}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:d,ownProperties:l});let h;s.$async&&(h=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const m=p.scopeName("validate");s.validateName=m;const f={gen:p,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue("schema",!0===this.opts.code.source?{ref:s.schema,code:(0,e.stringify)(s.schema)}:{ref:s.schema}),validateName:m,ValidationError:h,schema:s.schema,schemaEnv:s,rootId:i,baseId:s.baseId||i,schemaPath:e.nil,errSchemaPath:s.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(s),(0,a.validateFunctionCode)(f),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(n.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,s));const r=new Function(`${n.default.self}`,`${n.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:r}),r.errors=null,r.schema=s.schema,r.schemaEnv=s,s.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:m,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:n}=f;r.evaluated={props:t instanceof e.Name?void 0:t,items:n instanceof e.Name?void 0:n,dynamicProps:t instanceof e.Name,dynamicItems:n instanceof e.Name},r.source&&(r.source.evaluated=(0,e.stringify)(r.evaluated))}return s.validate=r,s}catch(e){throw delete s.validate,delete s.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(s)}}function c(e){return(0,r.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:i.call(this,e)}function u(e){for(const t of this._compilations)if(d(t,e))return t}function d(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function l(e,t){let n;for(;"string"==typeof(n=this.refs[t]);)t=n;return n||this.schemas[t]||p.call(this,e,t)}function p(e,t){const n=this.opts.uriResolver.parse(t),s=(0,r._getFullPath)(this.opts.uriResolver,n);let a=(0,r.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&s===a)return m.call(this,n,e);const c=(0,r.normalizeId)(s),u=this.refs[c]||this.schemas[c];if("string"==typeof u){const t=p.call(this,e,u);if("object"!=typeof(null==t?void 0:t.schema))return;return m.call(this,n,t)}if("object"==typeof(null==u?void 0:u.schema)){if(u.validate||i.call(this,u),c===(0,r.normalizeId)(t)){const{schema:t}=u,{schemaId:n}=this.opts,s=t[n];return s&&(a=(0,r.resolveUrl)(this.opts.uriResolver,a,s)),new o({schema:t,schemaId:n,root:e,baseId:a})}return m.call(this,n,u)}}fp.SchemaEnv=o,fp.compileSchema=i,fp.resolveRef=function(e,t,n){var s;n=(0,r.resolveUrl)(this.opts.uriResolver,t,n);const a=e.refs[n];if(a)return a;let i=l.call(this,e,n);if(void 0===i){const r=null===(s=e.localRefs)||void 0===s?void 0:s[n],{schemaId:a}=this.opts;r&&(i=new o({schema:r,schemaId:a,root:e,baseId:t}))}return void 0!==i?e.refs[n]=c.call(this,i):void 0},fp.getCompilingSchema=u,fp.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(e,{baseId:t,schema:n,root:a}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(const a of e.fragment.slice(1).split("/")){if("boolean"==typeof n)return;const e=n[(0,s.unescapeFragment)(a)];if(void 0===e)return;const o="object"==typeof(n=e)&&n[this.opts.schemaId];!h.has(a)&&o&&(t=(0,r.resolveUrl)(this.opts.uriResolver,t,o))}let c;if("boolean"!=typeof n&&n.$ref&&!(0,s.schemaHasRulesButRef)(n,this.RULES)){const e=(0,r.resolveUrl)(this.opts.uriResolver,t,n.$ref);c=p.call(this,a,e)}const{schemaId:u}=this.opts;return c=c||new o({schema:n,schemaId:u,root:a,baseId:t}),c.schema!==c.root.schema?c:void 0}return fp}var yp,_p,vp,wp,bp,kp,$p,Sp={$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},Ep={},Tp={exports:{}};function xp(){if(_p)return yp;_p=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=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 n(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),48!==n){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const r=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s(e){return e.length=0,!0}function a(e,t,r){if(e.length){const s=n(e);if(""===s)return r.error=!0,!1;t.push(s),e.length=0}return!0}function o(e){if(function(e){let t=0;for(let n=0;n<e.length;n++)":"===e[n]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const r={error:!1,address:"",zone:""},o=[],i=[];let c=!1,u=!1,d=a;for(let n=0;n<e.length;n++){const a=e[n];if("["!==a&&"]"!==a)if(":"!==a)if("%"===a){if(!d(i,o,r))break;d=s}else i.push(a);else{if(!0===c&&(u=!0),!d(i,o,r))break;if(++t>7){r.error=!0;break}n>0&&":"===e[n-1]&&(c=!0),o.push(":")}}return i.length&&(d===s?r.zone=i.join(""):u?o.push(i.join("")):o.push(n(i))),r.address=o.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}return yp={nonSimpleDomain:r,recomposeAuthority:function(e){const n=[];if(void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host){let r=unescape(e.host);if(!t(r)){const t=o(r);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}n.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){let t=e;const n=[];let r=-1,s=0;for(;s=t.length;){if(1===s){if("."===t)break;if("/"===t){n.push("/");break}n.push(t);break}if(2===s){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){n.push("/");break}}else if(3===s&&"/.."===t){0!==n.length&&n.pop(),n.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==n.length&&n.pop();continue}}if(-1===(r=t.indexOf("/",1))){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")},isIPv4:t,isUUID:e,normalizeIPv6:o,stringArrayToHexStripped:n},yp}function Op(){return $p||($p=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=ip();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=$l();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=dp(),s=hp(),a=Al(),o=gp(),i=$l(),c=op(),u=Fl(),d=Tl(),l=Sp,p=function(){if(kp)return Ep;kp=1,Object.defineProperty(Ep,"__esModule",{value:!0});const e=function(){if(bp)return Tp.exports;bp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:n,normalizeComponentEncoding:r,isIPv4:s,nonSimpleDomain:a}=xp(),{SCHEMES:o,getSchemeHandler:i}=function(){if(wp)return vp;wp=1;const{isUUID:e}=xp(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,n=["http","https","ws","wss","urn","urn:uuid"];function r(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function s(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function a(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const o={scheme:"http",domainHost:!0,parse:s,serialize:a},i={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=r(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(r(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:o,https:{scheme:"https",domainHost:o.domainHost,parse:s,serialize:a},ws:i,wss:{scheme:"wss",domainHost:i.domainHost,parse:i.parse,serialize:i.serialize},urn:{scheme:"urn",parse:function(e,n){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(t);if(r){const t=n.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const s=u(`${t}:${n.nid||e.nid}`);e.path=void 0,s&&(e=s.parse(e,n))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),s=u(`${n}:${t.nid||r}`);s&&(e=s.serialize(e,t));const a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,n){const r=t;return r.uuid=r.nss,r.nss=void 0,n.tolerant||r.uuid&&e(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function u(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),vp={wsIsSecure:r,SCHEMES:c,isValidSchemeName:function(e){return-1!==n.indexOf(e)},getSchemeHandler:u}}();function c(e,n,r,s){const a={};return s||(e=l(u(e,r),r),n=l(u(n,r),r)),!(r=r||{}).tolerant&&n.scheme?(a.scheme=n.scheme,a.userinfo=n.userinfo,a.host=n.host,a.port=n.port,a.path=t(n.path||""),a.query=n.query):(void 0!==n.userinfo||void 0!==n.host||void 0!==n.port?(a.userinfo=n.userinfo,a.host=n.host,a.port=n.port,a.path=t(n.path||""),a.query=n.query):(n.path?("/"===n.path[0]?a.path=t(n.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+n.path:a.path=n.path:a.path="/"+n.path,a.path=t(a.path)),a.query=n.query):(a.path=e.path,void 0!==n.query?a.query=n.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=n.fragment,a}function u(e,r){const s={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},a=Object.assign({},r),o=[],c=i(a.scheme||s.scheme);c&&c.serialize&&c.serialize(s,a),void 0!==s.path&&(a.skipEscape?s.path=unescape(s.path):(s.path=escape(s.path),void 0!==s.scheme&&(s.path=s.path.split("%3A").join(":")))),"suffix"!==a.reference&&s.scheme&&o.push(s.scheme,":");const u=n(s);if(void 0!==u&&("suffix"!==a.reference&&o.push("//"),o.push(u),s.path&&"/"!==s.path[0]&&o.push("/")),void 0!==s.path){let e=s.path;a.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===u&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),o.push(e)}return void 0!==s.query&&o.push("?",s.query),void 0!==s.fragment&&o.push("#",s.fragment),o.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function l(t,n){const r=Object.assign({},n),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===r.reference&&(t=r.scheme?r.scheme+":"+t:"//"+t);const u=t.match(d);if(u){if(o.scheme=u[1],o.userinfo=u[3],o.host=u[4],o.port=parseInt(u[5],10),o.path=u[6]||"",o.query=u[7],o.fragment=u[8],isNaN(o.port)&&(o.port=u[5]),o.host)if(!1===s(o.host)){const t=e(o.host);o.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0;void 0!==o.scheme||void 0!==o.userinfo||void 0!==o.host||void 0!==o.port||void 0!==o.query||o.path?void 0===o.scheme?o.reference="relative":void 0===o.fragment?o.reference="absolute":o.reference="uri":o.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");const n=i(r.scheme||o.scheme);if(!(r.unicodeSupport||n&&n.unicodeSupport)&&o.host&&(r.domainHost||n&&n.domainHost)&&!1===c&&a(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(e){o.error=o.error||"Host's domain name can not be converted to ASCII: "+e}(!n||n&&!n.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==o.scheme&&(o.scheme=unescape(o.scheme)),void 0!==o.host&&(o.host=unescape(o.host))),o.path&&(o.path=escape(unescape(o.path))),o.fragment&&(o.fragment=encodeURI(decodeURIComponent(o.fragment)))),n&&n.parse&&n.parse(o,r)}else o.error=o.error||"URI can not be parsed.";return o}const p={SCHEMES:o,normalize:function(e,t){return"string"==typeof e?e=u(l(e,t),t):"object"==typeof e&&(e=l(u(e,t),t)),e},resolve:function(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},s=c(l(e,r),l(t,r),r,!0);return r.skipEscape=!0,u(s,r)},resolveComponent:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=u(r(l(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=u(r(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=u(r(l(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=u(r(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:u,parse:l};return Tp.exports=p,Tp.exports.default=p,Tp.exports.fastUri=p,Tp.exports}();return e.code='require("ajv/dist/runtime/uri").default',Ep.default=e,Ep}(),h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={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."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function _(e){var t,n,r,s,a,o,i,c,u,d,l,m,f,g,y,_,v,w,b,k,$,S,E,T,x;const O=e.strict,N=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===N||void 0===N?1:N||0,P=null!==(r=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==r?r:h,R=null!==(s=e.uriResolver)&&void 0!==s?s:p.default;return{strictSchema:null===(o=null!==(a=e.strictSchema)&&void 0!==a?a:O)||void 0===o||o,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:O)||void 0===c||c,strictTypes:null!==(d=null!==(u=e.strictTypes)&&void 0!==u?u:O)&&void 0!==d?d:"log",strictTuples:null!==(m=null!==(l=e.strictTuples)&&void 0!==l?l:O)&&void 0!==m?m:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:O)&&void 0!==g&&g,code:e.code?{...e.code,optimize:I,regExp:P}:{optimize:I,regExp:P},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(_=e.loopEnum)&&void 0!==_?_:200,meta:null===(v=e.meta)||void 0===v||v,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===($=e.addUsedSchema)||void 0===$||$,validateSchema:null===(S=e.validateSchema)||void 0===S||S,validateFormats:null===(E=e.validateFormats)||void 0===E||E,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(x=e.int32range)||void 0===x||x,uriResolver:R}}class v{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:f,es5:t,lines:n}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),w.call(this,g,e,"NOT SUPPORTED"),w.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=E.call(this),e.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&S.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let r=l;"id"===n&&(r={...l},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const r=n(t);return"$async"in n||(this.errors=n.errors),r}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const n=await u.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,r);return this}let s;if("object"==typeof e){const{schemaId:t}=this.opts;if(s=e[t],void 0!==s&&"string"!=typeof s)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)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;const r=this.validate(n,e);if(!r&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return r}getSchema(e){let t;for(;"string"==typeof(t=b.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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":{const t=b.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(O.call(this,n,t),!t)return(0,d.eachItem)(n,e=>N.call(this,e)),this;P.call(this,t);const r={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(n,0===r.type.length?e=>N.call(this,e,r):e=>r.type.forEach(t=>N.call(this,e,r,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const r of t){const t=r.split("/").slice(1);let s=e;for(const e of t)s=s[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:r}=t.definition,a=s[e];r&&a&&(s[e]=C(a))}}return e}_removeAllSchemas(e,t){for(const n in e){const r=e[n];t&&!t.test(n)||("string"==typeof r?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,s=this.opts.addUsedSchema){let a;const{schemaId:i}=this.opts;if("object"==typeof e)a=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;n=(0,c.normalizeId)(a||n);const d=c.getSchemaRefs.call(this,e,n);return u=new o.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:n,localRefs:d}),this._cache.set(u.schema,u),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),r&&this.validateSchema(e,!0),u}_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):o.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,n,r="error"){for(const s in e){const a=s;a in t&&this.logger[r](`${n}: option ${s}. ${e[a]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function $(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function S(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function E(){const e={...this.opts};for(const t of m)delete e[t];return e}v.ValidationError=r.default,v.MissingRefError=s.default,e.default=v;const T={log(){},warn(){},error(){}},x=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){const{RULES:n}=this;if((0,d.eachItem)(e,e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!x.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function N(e,t,n){var r;const s=null==t?void 0:t.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:a}=this;let o=s?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?I.call(this,o,i,t.before):o.rules.push(i),a.all[e]=i,null===(r=t.implements)||void 0===r||r.forEach(e=>this.addKeyword(e))}function I(e,t,n){const r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function P(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=C(t)),e.validateSchema=this.compile(t,!0))}const R={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function C(e){return{anyOf:[e,R]}}}(pl)),pl}var Np,Ip,Pp,Rp={},Cp={},jp={},zp={};var Ap,Mp,Dp,Zp,Lp={},Fp={},qp={},Up={},Vp={};var Hp,Jp,Kp,Bp={},Wp={},Gp={};var Xp,Yp,Qp,eh={},th={},nh={};function rh(){if(Yp)return nh;Yp=1,Object.defineProperty(nh,"__esModule",{value:!0});const e=ep();return e.code='require("ajv/dist/runtime/equal").default',nh.default=e,nh}function sh(){if(Qp)return th;Qp=1,Object.defineProperty(th,"__esModule",{value:!0});const e=Fl(),t=$l(),n=Tl(),r=rh(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:n}})=>t.str`must NOT have duplicate items (items ## ${n} and ${e} are identical)`,params:({params:{i:e,j:n}})=>t._`{i: ${e}, j: ${n}}`},code(s){const{gen:a,data:o,$data:i,schema:c,parentSchema:u,schemaCode:d,it:l}=s;if(!i&&!c)return;const p=a.let("valid"),h=u.items?(0,e.getSchemaTypes)(u.items):[];function m(n,r){const i=a.name("item"),c=(0,e.checkDataTypes)(h,i,l.opts.strictNumbers,e.DataType.Wrong),u=a.const("indices",t._`{}`);a.for(t._`;${n}--;`,()=>{a.let(i,t._`${o}[${n}]`),a.if(c,t._`continue`),h.length>1&&a.if(t._`typeof ${i} == "string"`,t._`${i} += "_"`),a.if(t._`typeof ${u}[${i}] == "number"`,()=>{a.assign(r,t._`${u}[${i}]`),s.error(),a.assign(p,!1).break()}).code(t._`${u}[${i}] = ${n}`)})}function f(e,i){const c=(0,n.useFunc)(a,r.default),u=a.name("outer");a.label(u).for(t._`;${e}--;`,()=>a.for(t._`${i} = ${e}; ${i}--;`,()=>a.if(t._`${c}(${o}[${e}], ${o}[${i}])`,()=>{s.error(),a.assign(p,!1).break(u)})))}s.block$data(p,function(){const e=a.let("i",t._`${o}.length`),n=a.let("j");s.setParams({i:e,j:n}),a.assign(p,!0),a.if(t._`${e} > 1`,()=>(h.length>0&&!h.some(e=>"object"===e||"array"===e)?m:f)(e,n))},t._`${d} === false`),s.ok(p)}};return th.default=s,th}var ah,oh,ih,ch={},uh={};function dh(){if(ih)return Lp;ih=1,Object.defineProperty(Lp,"__esModule",{value:!0});const e=function(){if(Ap)return Fp;Ap=1,Object.defineProperty(Fp,"__esModule",{value:!0});const e=$l(),t=e.operators,n={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},r={message:({keyword:t,schemaCode:r})=>e.str`must be ${n[t].okStr} ${r}`,params:({keyword:t,schemaCode:r})=>e._`{comparison: ${n[t].okStr}, limit: ${r}}`},s={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:r,code(t){const{keyword:r,data:s,schemaCode:a}=t;t.fail$data(e._`${s} ${n[r].fail} ${a} || isNaN(${s})`)}};return Fp.default=s,Fp}(),t=function(){if(Mp)return qp;Mp=1,Object.defineProperty(qp,"__esModule",{value:!0});const e=$l(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:n,data:r,schemaCode:s,it:a}=t,o=a.opts.multipleOfPrecision,i=n.let("res"),c=o?e._`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:e._`${i} !== parseInt(${i})`;t.fail$data(e._`(${s} === 0 || (${i} = ${r}/${s}, ${c}))`)}};return qp.default=t,qp}(),n=function(){if(Zp)return Up;Zp=1,Object.defineProperty(Up,"__esModule",{value:!0});const e=$l(),t=Tl(),n=function(){if(Dp)return Vp;function e(e){const t=e.length;let n,r=0,s=0;for(;s<t;)r++,n=e.charCodeAt(s++),n>=55296&&n<=56319&&s<t&&(n=e.charCodeAt(s),56320==(64512&n)&&s++);return r}return Dp=1,Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Vp}(),r={message({keyword:t,schemaCode:n}){const r="maxLength"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:r,code(r){const{keyword:s,data:a,schemaCode:o,it:i}=r,c="maxLength"===s?e.operators.GT:e.operators.LT,u=!1===i.opts.unicode?e._`${a}.length`:e._`${(0,t.useFunc)(r.gen,n.default)}(${a})`;r.fail$data(e._`${u} ${c} ${o}`)}};return Up.default=s,Up}(),r=function(){if(Hp)return Bp;Hp=1,Object.defineProperty(Bp,"__esModule",{value:!0});const e=Bl(),t=$l(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(n){const{data:r,$data:s,schema:a,schemaCode:o,it:i}=n,c=i.opts.unicodeRegExp?"u":"",u=s?t._`(new RegExp(${o}, ${c}))`:(0,e.usePattern)(n,a);n.fail$data(t._`!${u}.test(${r})`)}};return Bp.default=n,Bp}(),s=function(){if(Jp)return Wp;Jp=1,Object.defineProperty(Wp,"__esModule",{value:!0});const e=$l(),t={message({keyword:t,schemaCode:n}){const r="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,a="maxProperties"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${r}).length ${a} ${s}`)}};return Wp.default=n,Wp}(),a=function(){if(Kp)return Gp;Kp=1,Object.defineProperty(Gp,"__esModule",{value:!0});const e=Bl(),t=$l(),n=Tl(),r={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(r){const{gen:s,schema:a,schemaCode:o,data:i,$data:c,it:u}=r,{opts:d}=u;if(!c&&0===a.length)return;const l=a.length>=d.loopRequired;if(u.allErrors?function(){if(l||c)r.block$data(t.nil,p);else for(const t of a)(0,e.checkReportMissingProp)(r,t)}():function(){const n=s.let("missing");if(l||c){const a=s.let("valid",!0);r.block$data(a,()=>function(n,a){r.setParams({missingProperty:n}),s.forOf(n,o,()=>{s.assign(a,(0,e.propertyInData)(s,i,n,d.ownProperties)),s.if((0,t.not)(a),()=>{r.error(),s.break()})},t.nil)}(n,a)),r.ok(a)}else s.if((0,e.checkMissingProp)(r,a,n)),(0,e.reportMissingProp)(r,n),s.else()}(),d.strictRequired){const e=r.parentSchema.properties,{definedProperties:t}=r.it;for(const r of a)if(void 0===(null==e?void 0:e[r])&&!t.has(r)){const e=`required property "${r}" is not defined at "${u.schemaEnv.baseId+u.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(u,e,u.opts.strictRequired)}}function p(){s.forOf("prop",o,t=>{r.setParams({missingProperty:t}),s.if((0,e.noPropertyInData)(s,i,t,d.ownProperties),()=>r.error())})}}};return Gp.default=r,Gp}(),o=function(){if(Xp)return eh;Xp=1,Object.defineProperty(eh,"__esModule",{value:!0});const e=$l(),t={message({keyword:t,schemaCode:n}){const r="maxItems"===t?"more":"fewer";return e.str`must NOT have ${r} than ${n} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:r,schemaCode:s}=t,a="maxItems"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`${r}.length ${a} ${s}`)}};return eh.default=n,eh}(),i=sh(),c=function(){if(ah)return ch;ah=1,Object.defineProperty(ch,"__esModule",{value:!0});const e=$l(),t=Tl(),n=rh(),r={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(r){const{gen:s,data:a,$data:o,schemaCode:i,schema:c}=r;o||c&&"object"==typeof c?r.fail$data(e._`!${(0,t.useFunc)(s,n.default)}(${a}, ${i})`):r.fail(e._`${c} !== ${a}`)}};return ch.default=r,ch}(),u=function(){if(oh)return uh;oh=1,Object.defineProperty(uh,"__esModule",{value:!0});const e=$l(),t=Tl(),n=rh(),r={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(r){const{gen:s,data:a,$data:o,schema:i,schemaCode:c,it:u}=r;if(!o&&0===i.length)throw new Error("enum must have non-empty array");const d=i.length>=u.opts.loopEnum;let l;const p=()=>null!=l?l:l=(0,t.useFunc)(s,n.default);let h;if(d||o)h=s.let("valid"),r.block$data(h,function(){s.assign(h,!1),s.forOf("v",c,t=>s.if(e._`${p()}(${a}, ${t})`,()=>s.assign(h,!0).break()))});else{if(!Array.isArray(i))throw new Error("ajv implementation error");const t=s.const("vSchema",c);h=(0,e.or)(...i.map((n,r)=>function(t,n){const r=i[n];return"object"==typeof r&&null!==r?e._`${p()}(${a}, ${t}[${n}])`:e._`${a} === ${r}`}(t,r)))}r.pass(h)}};return uh.default=r,uh}(),d=[e.default,t.default,n.default,r.default,s.default,a.default,o.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,u.default];return Lp.default=d,Lp}var lh,ph={},hh={};function mh(){if(lh)return hh;lh=1,Object.defineProperty(hh,"__esModule",{value:!0}),hh.validateAdditionalItems=void 0;const e=$l(),t=Tl(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:n,it:s}=e,{items:a}=n;Array.isArray(a)?r(e,a):(0,t.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas')}};function r(n,r){const{gen:s,schema:a,data:o,keyword:i,it:c}=n;c.items=!0;const u=s.const("len",e._`${o}.length`);if(!1===a)n.setParams({len:r.length}),n.pass(e._`${u} <= ${r.length}`);else if("object"==typeof a&&!(0,t.alwaysValidSchema)(c,a)){const a=s.var("valid",e._`${u} <= ${r.length}`);s.if((0,e.not)(a),()=>function(a){s.forRange("i",r.length,u,r=>{n.subschema({keyword:i,dataProp:r,dataPropType:t.Type.Num},a),c.allErrors||s.if((0,e.not)(a),()=>s.break())})}(a)),n.ok(a)}}return hh.validateAdditionalItems=r,hh.default=n,hh}var fh,gh,yh={},_h={};function vh(){if(fh)return _h;fh=1,Object.defineProperty(_h,"__esModule",{value:!0}),_h.validateTuple=void 0;const e=$l(),t=Tl(),n=Bl(),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:r,it:a}=e;if(Array.isArray(r))return s(e,"additionalItems",r);a.items=!0,(0,t.alwaysValidSchema)(a,r)||e.ok((0,n.validateArray)(e))}};function s(n,r,s=n.schema){const{gen:a,parentSchema:o,data:i,keyword:c,it:u}=n;!function(e){const{opts:n,errSchemaPath:a}=u,o=s.length,i=o===e.minItems&&(o===e.maxItems||!1===e[r]);if(n.strictTuples&&!i){const e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,t.checkStrictMode)(u,e,n.strictTuples)}}(o),u.opts.unevaluated&&s.length&&!0!==u.items&&(u.items=t.mergeEvaluated.items(a,s.length,u.items));const d=a.name("valid"),l=a.const("len",e._`${i}.length`);s.forEach((r,s)=>{(0,t.alwaysValidSchema)(u,r)||(a.if(e._`${l} > ${s}`,()=>n.subschema({keyword:c,schemaProp:s,dataProp:s},d)),n.ok(d))})}return _h.validateTuple=s,_h.default=r,_h}var wh,bh,kh={},$h={};var Sh,Eh={};var Th,xh,Oh={},Nh={};function Ih(){if(xh)return Nh;xh=1,Object.defineProperty(Nh,"__esModule",{value:!0});const e=Bl(),t=$l(),n=Pl(),r=Tl(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(s){const{gen:a,schema:o,parentSchema:i,data:c,errsCount:u,it:d}=s;if(!u)throw new Error("ajv implementation error");const{allErrors:l,opts:p}=d;if(d.props=!0,"all"!==p.removeAdditional&&(0,r.alwaysValidSchema)(d,o))return;const h=(0,e.allSchemaProperties)(i.properties),m=(0,e.allSchemaProperties)(i.patternProperties);function f(e){a.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===o)f(e);else{if(!1===o)return s.setParams({additionalProperty:e}),s.error(),void(l||a.break());if("object"==typeof o&&!(0,r.alwaysValidSchema)(d,o)){const n=a.name("valid");"failing"===p.removeAdditional?(y(e,n,!1),a.if((0,t.not)(n),()=>{s.reset(),f(e)})):(y(e,n),l||a.if((0,t.not)(n),()=>a.break()))}}}function y(e,t,n){const a={keyword:"additionalProperties",dataProp:e,dataPropType:r.Type.Str};!1===n&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(a,t)}a.forIn("key",c,n=>{h.length||m.length?a.if(function(n){let o;if(h.length>8){const t=(0,r.schemaRefOrVal)(d,i.properties,"properties");o=(0,e.isOwnProperty)(a,t,n)}else o=h.length?(0,t.or)(...h.map(e=>t._`${n} === ${e}`)):t.nil;return m.length&&(o=(0,t.or)(o,...m.map(r=>t._`${(0,e.usePattern)(s,r)}.test(${n})`))),(0,t.not)(o)}(n),()=>g(n)):g(n)}),s.ok(t._`${u} === ${n.default.errors}`)}};return Nh.default=s,Nh}var Ph,Rh,Ch,jh,zh,Ah,Mh,Dh,Zh,Lh={},Fh={},qh={},Uh={},Vh={},Hh={},Jh={},Kh={};function Bh(){if(Zh)return ph;Zh=1,Object.defineProperty(ph,"__esModule",{value:!0});const e=mh(),t=function(){if(gh)return yh;gh=1,Object.defineProperty(yh,"__esModule",{value:!0});const e=vh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return yh.default=t,yh}(),n=vh(),r=function(){if(wh)return kh;wh=1,Object.defineProperty(kh,"__esModule",{value:!0});const e=$l(),t=Tl(),n=Bl(),r=mh(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:s,parentSchema:a,it:o}=e,{prefixItems:i}=a;o.items=!0,(0,t.alwaysValidSchema)(o,s)||(i?(0,r.validateAdditionalItems)(e,i):e.ok((0,n.validateArray)(e)))}};return kh.default=s,kh}(),s=function(){if(bh)return $h;bh=1,Object.defineProperty($h,"__esModule",{value:!0});const e=$l(),t=Tl(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:n}})=>void 0===n?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${n} valid item(s)`,params:({params:{min:t,max:n}})=>void 0===n?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${n}}`},code(n){const{gen:r,schema:s,parentSchema:a,data:o,it:i}=n;let c,u;const{minContains:d,maxContains:l}=a;i.opts.next?(c=void 0===d?1:d,u=l):c=1;const p=r.const("len",e._`${o}.length`);if(n.setParams({min:c,max:u}),void 0===u&&0===c)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==u&&c>u)return(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),void n.fail();if((0,t.alwaysValidSchema)(i,s)){let t=e._`${p} >= ${c}`;return void 0!==u&&(t=e._`${t} && ${p} <= ${u}`),void n.pass(t)}i.items=!0;const h=r.name("valid");function m(){const t=r.name("_valid"),n=r.let("count",0);f(t,()=>r.if(t,()=>function(t){r.code(e._`${t}++`),void 0===u?r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0).break()):(r.if(e._`${t} > ${u}`,()=>r.assign(h,!1).break()),1===c?r.assign(h,!0):r.if(e._`${t} >= ${c}`,()=>r.assign(h,!0)))}(n)))}function f(e,s){r.forRange("i",0,p,r=>{n.subschema({keyword:"contains",dataProp:r,dataPropType:t.Type.Num,compositeRule:!0},e),s()})}void 0===u&&1===c?f(h,()=>r.if(h,()=>r.break())):0===c?(r.let(h,!0),void 0!==u&&r.if(e._`${o}.length > 0`,m)):(r.let(h,!1),m()),n.result(h,()=>n.reset())}};return $h.default=n,$h}(),a=(Sh||(Sh=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=$l(),n=Tl(),r=Bl();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{const s=1===n?"property":"properties";return t.str`must have ${s} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:s}})=>t._`{property: ${e},
6
- missingProperty: ${s},
2
+ import{Command as e}from"commander";import t,{dirname as n}from"path";import s from"os";import r,{readFileSync as a,existsSync as o,mkdirSync as i,writeFileSync as c}from"fs";import{exec as u}from"child_process";import{fileURLToPath as d}from"url";import l from"better-sqlite3";import p from"simple-git";import{cwd as h}from"process";import{ZodOptional as m,z as f}from"zod";import g from"node:process";import y from"express";import _ from"express-ejs-layouts";import v from"markdown-it";const w=["personal","project","organization"],b=["developer","architect","reviewer","ai"],k=["code_pattern","tool_usage","architecture","config","pitfall","api_usage","exploration"],$={DRAFT:"draft",SUGGESTED:"suggested",VERIFIED:"verified"},E="session_start",S="session_end",T={knowledge_item:`\n CREATE TABLE IF NOT EXISTS knowledge_item (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n\n -- Basic information\n title TEXT NOT NULL,\n summary TEXT NOT NULL,\n content TEXT NOT NULL,\n\n -- Classification dimensions\n scope TEXT NOT NULL CHECK(scope IN (${w.map(e=>`'${e}'`).join(", ")})),\n source_type TEXT NOT NULL CHECK(source_type IN (${b.map(e=>`'${e}'`).join(", ")})),\n knowledge_type TEXT NOT NULL ,\n status TEXT NOT NULL DEFAULT '${$.DRAFT}' CHECK(status IN (${Object.values($).map(e=>`'${e}'`).join(", ")})),\n\n -- Source tracking\n source_file TEXT,\n contributor TEXT,\n\n -- Timestamps\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n `,session:"\n CREATE TABLE IF NOT EXISTS session (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT UNIQUE NOT NULL,\n\n -- Session basic information\n cwd TEXT NOT NULL,\n cwd_updated_at INTEGER NOT NULL,\n git_url TEXT,\n git_branch TEXT,\n git_commit_id TEXT,\n user_name TEXT,\n\n -- First user prompt for the session\n first_user_prompt TEXT,\n\n -- Environment information (stored as JSON)\n env TEXT,\n\n -- Configuration information (stored as JSON)\n config TEXT,\n\n -- Session duration (seconds, calculated on session end)\n duration INTEGER,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n ",session_event:"\n CREATE TABLE IF NOT EXISTS session_event (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n\n -- Hook information\n name TEXT NOT NULL,\n input TEXT NOT NULL,\n output TEXT,\n exit_code INTEGER NOT NULL DEFAULT 0,\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n ",session_detail:"\n CREATE TABLE IF NOT EXISTS session_detail (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n\n -- UUID is the unique key for each transcript entry\n uuid TEXT UNIQUE NOT NULL,\n\n -- Top-level JSON fields as table columns\n type TEXT,\n parentUuid TEXT,\n isSidechain INTEGER, -- SQLite boolean as INTEGER\n userType TEXT,\n cwd TEXT,\n version TEXT,\n gitBranch TEXT,\n parentToolUseID TEXT,\n toolUseID TEXT,\n timestamp TEXT,\n isMeta INTEGER, -- SQLite boolean as INTEGER\n messageId TEXT,\n isSnapshotUpdate INTEGER, -- SQLite boolean as INTEGER\n\n -- Other fields stored as JSON strings\n data TEXT, -- JSON string\n message TEXT, -- JSON string\n snapshot TEXT, -- JSON string\n usage TEXT, -- JSON string\n\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (session_id) REFERENCES session(session_id)\n )\n ",knowledge_item_fts:"\n CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_item_fts USING fts5(\n title, summary, content,\n content='knowledge_item',\n content_rowid='id',\n tokenize='trigram'\n )\n "},O={knowledge_item_fts_insert:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_insert AFTER INSERT ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n ",knowledge_item_fts_delete:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_delete AFTER DELETE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n END\n ",knowledge_item_fts_update:"\n CREATE TRIGGER IF NOT EXISTS knowledge_item_fts_update AFTER UPDATE ON knowledge_item BEGIN\n INSERT INTO knowledge_item_fts(knowledge_item_fts, rowid, title, summary, content)\n VALUES('delete', old.id, old.title, old.summary, old.content);\n INSERT INTO knowledge_item_fts(rowid, title, summary, content)\n VALUES (new.id, new.title, new.summary, new.content);\n END\n "},x={idx_knowledge_scope:"CREATE INDEX IF NOT EXISTS idx_knowledge_scope ON knowledge_item(scope)",idx_knowledge_type:"CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_item(knowledge_type)",idx_knowledge_status:"CREATE INDEX IF NOT EXISTS idx_knowledge_status ON knowledge_item(status)",idx_knowledge_session:"CREATE INDEX IF NOT EXISTS idx_knowledge_session ON knowledge_item(session_id)",idx_session_id:"CREATE INDEX IF NOT EXISTS idx_session_id ON session(session_id)",idx_session_cwd:"CREATE INDEX IF NOT EXISTS idx_session_cwd ON session(cwd)",idx_session_event_session:"CREATE INDEX IF NOT EXISTS idx_session_event_session ON session_event(session_id)",idx_session_event_name:"CREATE INDEX IF NOT EXISTS idx_session_event_name ON session_event(name)",idx_session_detail_session:"CREATE INDEX IF NOT EXISTS idx_session_detail_session ON session_detail(session_id)",idx_session_detail_uuid:"CREATE INDEX IF NOT EXISTS idx_session_detail_uuid ON session_detail(uuid)",idx_session_detail_type:"CREATE INDEX IF NOT EXISTS idx_session_detail_type ON session_detail(type)"};function I(e){Object.values(T).forEach(t=>{e.prepare(t).run()}),Object.values(x).forEach(t=>{e.prepare(t).run()}),Object.values(O).forEach(t=>{e.prepare(t).run()})}const N={logging:{level:"DEBUG"},db:{file:t.join(s.homedir(),".knowledge-bank","knowledge.db"),configs:["journal_mode = WAL","foreign_keys = ON"]},tmp:t.join(s.homedir(),".knowledge-bank","tmp")};let P=null;function R(){if(null===P){const e=process.env.KNOWLEDGE_CONF_DIR||t.join(s.homedir(),".knowledge-bank"),n=t.join(e,"config.json");P={...N,...r.existsSync(n)?JSON.parse(r.readFileSync(n,"utf-8")):{}}}return P}const C=R(),j={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},z=Object.values(j);class A{constructor(e,n){this.loggerName=n;const a=C.logging.path||t.join(s.homedir(),".knowledge-bank","logs");r.mkdirSync(a,{recursive:!0}),this.loggerFile=t.join(a,`${e}.log`),this.logLevel=C.logging.level.toUpperCase()||j.INFO}formatMessage(e,t,n=null){const s=`${(new Date).toISOString().replace("T","-").split(".")[0]} ${this.loggerName} ${e}: ${t}`;return null===n?s:`${s} - ${JSON.stringify(n)}`}isLogLevelEnabled(e){const t=z.indexOf(this.logLevel);return z.indexOf(e)>=t}writeMessage(e,t,n){if(this.isLogLevelEnabled(e)){const s=this.formatMessage(e,t,n);r.appendFileSync(this.loggerFile,`${s}\n`,"utf8")}}logInfo(e,t=null){this.writeMessage(j.INFO,e,t)}logError(e,t=null){if(t instanceof Error){const n={message:t.message,stack:t.stack,name:t.name,...t.cause&&{cause:t.cause},...Object.getOwnPropertyNames(t).reduce((e,n)=>(["message","stack","name"].includes(n)||(e[n]=t[n]),e),{})};this.writeMessage(j.ERROR,e,n)}else this.writeMessage(j.ERROR,e,t)}logWarn(e,t=null){this.writeMessage(j.WARN,e,t)}logDebug(e,t=null){this.writeMessage(j.DEBUG,e,t)}}function D(e,t){return new A(e,t)}class M{constructor(e={}){this.isDev=void 0!==e.isDev?e.isDev:this.detectEnvironment(),this._rootDir=null,this._packageFile=null,this._marketplaceRepo=null}detectEnvironment(){const e=d(import.meta.url),n=t.dirname(e),s=r.existsSync(t.join(n,"..","..","src")),a=n.includes("dist"),o=t.join(n,"..","..","package.json"),i=t.join(n,"..","package.json");return s&&!a||!r.existsSync(i)&&r.existsSync(o)}getRootDir(){if(this._rootDir)return this._rootDir;const e=d(import.meta.url),n=t.dirname(e);if(this.isDev)this._rootDir=t.join(n,"..","..");else if(n.includes("dist")){const e=n.indexOf("dist");this._rootDir=n.substring(0,e-1)}else if(n.includes("src"))this._rootDir=t.join(n,"..","..");else{let e=n;for(;e!==t.dirname(e);){const n=t.join(e,"package.json");if(r.existsSync(n)){this._rootDir=e;break}e=t.dirname(e)}this._rootDir||(this._rootDir=t.dirname(n))}return this._rootDir}getPackageFile(){if(this._packageFile)return this._packageFile;const e=this.getRootDir();if(this._packageFile=t.join(e,"package.json"),!r.existsSync(this._packageFile)){const e=t.join(process.cwd(),"package.json");if(!r.existsSync(e))throw new Error(`package.json not found at ${this._packageFile} or ${e}`);this._packageFile=e}return this._packageFile}getMarketplaceRepo(){if(this._marketplaceRepo)return this._marketplaceRepo;const e=this.getRootDir();if(this.isDev){const n=t.join(e,"dist","claude-marketplace"),s=t.join(e,"src","claude-marketplace");if(r.existsSync(n))this._marketplaceRepo=n;else{if(!r.existsSync(s))throw new Error(`Marketplace directory not found at ${n} or ${s}`);this._marketplaceRepo=s}}else if(this._marketplaceRepo=t.join(e,"dist","claude-marketplace"),!r.existsSync(this._marketplaceRepo))throw new Error(`Marketplace directory not found at ${this._marketplaceRepo}`);return this._marketplaceRepo}getWebViewsPath(){const e=this.getRootDir();return this.isDev?t.join(e,"src","web","views"):t.join(e,"dist","web","views")}getWebPublicPath(){const e=this.getRootDir();return this.isDev?t.join(e,"src","web","public"):t.join(e,"dist","web","public")}}const L=new M,Z=D("common","common"),F=L.getPackageFile(),U=L.getMarketplaceRepo(),q=JSON.parse(a(F,"utf8"));function H(e){return r.existsSync(e)?JSON.parse(r.readFileSync(e,"utf-8")):{}}const V=t.join(s.homedir(),".claude","settings.local.json");function J(){const e=function(){const e=process.env.CLAUDE_PROJECT_DIR||process.cwd(),n=t.join(e,".claude/settings.local.json"),s=t.join(e,".claude/settings.json"),r=H(n),a=H(s);return{...H(V),...a,...r}}(),n=!1!==(e?.knowledge||{}).enabled;return n||Z.logWarn("Knowledge collection is disabled in settings."),{enabled:n}}function K(){return new Promise((e,t)=>{u("claude plugin marketplace list --json",(n,s,r)=>{if(n)t(n);else{r&&console.error(r);try{const t=s.trim()?JSON.parse(s):[];e(t)}catch(e){t(e)}}})})}const B=R(),W=new class{constructor(){this.dbFile=B.db.file,this.initialized=!1}initialize(){if(!this.initialized){const e=n(this.dbFile);o(e)||i(e,{recursive:!0})}return this.initialized=!0,this}_createConnection(){const e=new l(this.dbFile);return B.db.configs.forEach(t=>{e.pragma(t)}),e}withConnection(e){let t=null;try{return t=this.initialize()._createConnection(),e(t)}finally{t&&(t.close(),t=null)}}static install(){W.withConnection(e=>{I(e)})}},G=R();class X{constructor(){this.dbInstance=W}withConnection(e){return this.dbInstance.withConnection(e)}}class Y extends X{create(e){return this.withConnection(t=>{const n=Date.now(),s=t.prepare("\n INSERT INTO knowledge_item (\n session_id,\n title, summary, content,\n scope, source_type, knowledge_type, status,\n source_file, contributor,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @title, @summary, @content,\n @scope, @source_type, @knowledge_type, @status,\n @source_file, @contributor,\n @created_at, @updated_at\n )\n ").run({...e,status:e.status||$.DRAFT,created_at:n,updated_at:n});return this._findById(t,s.lastInsertRowid)})}_findById(e,t){return e.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(t)}findById(e){return this.withConnection(t=>this._findById(t,e))}findByCwd(e,t=10){return this.withConnection(e=>e.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ?").all(t))}findByScope(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE scope = ? ORDER BY updated_at DESC").all(e))}findByStatus(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE status = ? ORDER BY updated_at DESC").all(e))}findByKnowledgeType(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE knowledge_type = ? ORDER BY updated_at DESC").all(e))}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM knowledge_item WHERE session_id = ? ORDER BY updated_at DESC").all(e))}update(e,t){return this.withConnection(n=>{const s=Date.now(),r=Object.keys(t).map(e=>`${e} = @${e}`).join(", ");return n.prepare(`\n UPDATE knowledge_item\n SET ${r},\n updated_at = @updated_at\n WHERE id = @id\n `).run({...t,id:e,updated_at:s}),n.prepare("SELECT * FROM knowledge_item WHERE id = ?").get(e)})}updateStatus(e,t){return this.update(e,{status:t})}delete(e){return this.withConnection(t=>t.prepare("DELETE FROM knowledge_item WHERE id = ?").run(e))}count(e={}){return this.withConnection(t=>{let n="SELECT COUNT(*) as count FROM knowledge_item";const s=[],r=[];return e.scope&&(s.push("scope = ?"),r.push(e.scope)),e.status&&(s.push("status = ?"),r.push(e.status)),e.knowledge_type&&(s.push("knowledge_type = ?"),r.push(e.knowledge_type)),e.session_id&&(s.push("session_id = ?"),r.push(e.session_id)),s.length>0&&(n+=` WHERE ${s.join(" AND ")}`),t.prepare(n).get(...r).count})}findAll(e=100,t=0){return this.withConnection(n=>n.prepare("SELECT * FROM knowledge_item ORDER BY updated_at DESC LIMIT ? OFFSET ?").all(e,t))}search(e,t=10){return this.withConnection(n=>{const s=Array.isArray(e)?e.map(e=>`"${e}"`).join(" OR "):`"${e}"`;return n.prepare("\n SELECT ki.*\n FROM knowledge_item ki\n JOIN knowledge_item_fts fts ON fts.rowid = ki.id\n WHERE knowledge_item_fts MATCH ?\n ORDER BY rank DESC\n LIMIT ?").all(s,t)})}}class Q{constructor(){this.logger=D("knowledge-management","knowledge-management"),this.knowledgeRepo=new Y}getSessionId(){return process.env.CLAUDE_SESSION_ID}buildUpdateData(e){const t={};return["title","summary","content","scope","source_type","knowledge_type","status","source_file","contributor"].forEach(n=>{void 0!==e[n]&&(t[n]=e[n])}),t}aggregateByStatus(e,t){e.forEach(e=>{t.by_status[e]=this.knowledgeRepo.count({status:e})})}aggregateByScope(e,t){e.forEach(e=>{t.by_scope[e]=this.knowledgeRepo.count({scope:e})})}aggregateByType(e,t){e.forEach(e=>{t.by_type[e]=this.knowledgeRepo.count({knowledge_type:e})})}async create(e){return this.logger.logInfo("Creating new knowledge item",{sessionId:e.session_id}),this.knowledgeRepo.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.source_type,knowledge_type:e.knowledge_type,status:e.status,source_file:e.source_file,contributor:e.contributor,session_id:e.session_id||this.getSessionId()})}async update(e,t){this.logger.logInfo(`Updating knowledge item ${e}...`);const n=this.buildUpdateData(t),s=this.knowledgeRepo.update(e,n);return this.logger.logInfo(`✓ Knowledge item ${e} updated`),s}async delete(e){this.logger.logInfo(`Deleting knowledge item ${e}...`),this.knowledgeRepo.delete(e),this.logger.logInfo(`✓ Knowledge item ${e} deleted`)}async get(e){return this.knowledgeRepo.findById(e)||(this.logger.logWarn(`Knowledge item ${e} not found`),null)}async list(e={}){if(e.scope)return this.knowledgeRepo.findByScope(e.scope);if(e.status)return this.knowledgeRepo.findByStatus(e.status);if(e.knowledge_type)return this.knowledgeRepo.findByKnowledgeType(e.knowledge_type);const t=e.limit||100,n=e.offset||0;return this.knowledgeRepo.findAll(t,n)}async search(e,t=10){return this.knowledgeRepo.search(e,t)}async updateStatus(e,t){this.logger.logInfo(`Updating status of knowledge item ${e} to ${t}...`);const n=this.knowledgeRepo.updateStatus(e,t);return this.logger.logInfo(`✓ Status updated to ${t}`),n}async getStats(){const e={total:0,by_status:{draft:0,suggested:0,verified:0},by_scope:{personal:0,project:0,organization:0},by_type:{code_pattern:0,architecture:0,config:0,pitfall:0,api_usage:0}};return e.total=this.knowledgeRepo.count({}),this.aggregateByStatus(["draft","suggested","verified"],e),this.aggregateByScope(["personal","project","organization"],e),this.aggregateByType(["code_pattern","architecture","config","pitfall","api_usage"],e),e}}class ee extends X{create(e){return this.withConnection(t=>{const n=Date.now(),s=t.prepare("\n INSERT INTO session_event (\n session_id,\n name, input, output, exit_code,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @name, @input, @output, @exit_code,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,name:e.name,input:"string"==typeof e.input?e.input:JSON.stringify(e.input),output:void 0===e.output||null===e.output?null:"string"==typeof e.output?e.output:JSON.stringify(e.output),exit_code:e.exit_code||0,created_at:n,updated_at:n}),r=t.prepare("SELECT * FROM session_event WHERE id = ?").get(s.lastInsertRowid);return r&&(r.input&&(r.input=JSON.parse(r.input)),r.output&&(r.output=JSON.parse(r.output))),r})}updateOutput(e,t,n=0){return this.withConnection(s=>{const r=Date.now(),a=s.prepare("\n UPDATE session_event\n SET output = ?, exit_code = ?, updated_at = ?\n WHERE id = ?\n "),o="string"==typeof t?t:JSON.stringify(t);return a.run(o,n,r,e),this._findById(s,e)})}_findById(e,t){const n=e.prepare("SELECT * FROM session_event WHERE id = ?").get(t);return n&&(n.input&&(n.input=JSON.parse(n.input)),n.output&&(n.output=JSON.parse(n.output))),n}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM session_event WHERE session_id = ? ORDER BY id ASC").all(e).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findBySessionAndName(e,t){return this.withConnection(n=>n.prepare("SELECT * FROM session_event WHERE session_id = ? AND name = ? ORDER BY created_at ASC").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findByName(e,t=100){return this.withConnection(n=>n.prepare("SELECT * FROM session_event WHERE name = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(e=>({...e,input:e.input?JSON.parse(e.input):null,output:e.output?JSON.parse(e.output):null})))}findLatestSessionStart(e){return this.withConnection(t=>{const n=t.prepare("\n SELECT * FROM session_event\n WHERE session_id = ? AND name = ?\n ORDER BY created_at DESC\n LIMIT 1\n ").get(e,E);return n&&(n.input&&(n.input=JSON.parse(n.input)),n.output&&(n.output=JSON.parse(n.output))),n})}hasSessionEnded(e){return this.withConnection(t=>t.prepare("\n SELECT COUNT(*) as count FROM session_event\n WHERE session_id = ? AND name = ?\n limit 1\n ").get(e,S).count>0)}delete(e){return this.withConnection(t=>t.prepare("DELETE FROM session_event WHERE id = ?").run(e))}count(e={}){return this.withConnection(t=>{let n="SELECT COUNT(*) as count FROM session_event";const s=[],r=[];return e.session_id&&(s.push("session_id = ?"),r.push(e.session_id)),e.name&&(s.push("name = ?"),r.push(e.name)),s.length>0&&(n+=` WHERE ${s.join(" AND ")}`),t.prepare(n).get(...r).count})}}class te extends X{create(e){return this.withConnection(t=>{const n=t.prepare("SELECT * FROM session WHERE session_id = ?").get(e.session_id);if(n)return n;const s=Date.now(),r=e.config||R(),a=t.prepare("\n INSERT INTO session (\n session_id,\n cwd, cwd_updated_at, git_url, git_branch, git_commit_id, user_name,\n first_user_prompt, env, config, duration,\n created_at, updated_at\n ) VALUES (\n @session_id,\n @cwd, @cwd_updated_at, @git_url, @git_branch, @git_commit_id, @user_name,\n @first_user_prompt, @env, @config, @duration,\n @created_at, @updated_at\n )\n ").run({session_id:e.session_id,cwd:e.cwd,cwd_updated_at:s,git_url:e.git_url||null,git_branch:e.git_branch||null,git_commit_id:e.git_commit_id||null,user_name:e.user_name||null,first_user_prompt:null,env:e.env?JSON.stringify(e.env):null,config:JSON.stringify(r),duration:null,created_at:s,updated_at:s});return this._findById(t,a.lastInsertRowid)})}_findById(e,t){return e.prepare("SELECT * FROM session WHERE id = ?").get(t)}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM session WHERE session_id = ?").get(e))}updateSessionDuration(e){return this.withConnection(t=>{const n=t.prepare("SELECT * FROM session WHERE id = ?").get(e);if(!n)throw new Error(`Session not found: ${e}`);const s=Date.now(),r=Math.floor((s-n.created_at)/1e3);return t.prepare("\n UPDATE session\n SET duration = ?, updated_at = ?\n WHERE id = ?\n ").run(r,s,e),this._findById(t,e)})}updateFirstUserPrompt(e,t){return this.withConnection(n=>{const s=Date.now();n.prepare("\n UPDATE session\n SET first_user_prompt = ?, updated_at = ?\n WHERE id = ?\n ").run(t,s,e)})}findByCwd(e){return this.withConnection(t=>t.prepare("SELECT * FROM session WHERE cwd = ? ORDER BY updated_at DESC").all(e))}getSessionSummary(e){return this.withConnection(t=>{const n=(new ee).findBySessionId(e),s=t.prepare("SELECT * FROM session WHERE session_id = ?").get(e),r={session_id:e,total_events:n.length,hook_types:{},start_time:null,end_time:null,duration:null,cwd:s?.cwd||null,git_branch:s?.git_branch||null,config:s?.config||null,created_at:s?.created_at||null,updated_at:s?.updated_at||null};return n.forEach(e=>{r.hook_types[e.name]=(r.hook_types[e.name]||0)+1,e.name!==E||r.start_time||(r.start_time=e.created_at),e.name!==S||r.end_time||(r.end_time=e.created_at)}),r.start_time&&r.end_time&&(r.duration=r.end_time-r.start_time),r})}}class ne{constructor(e=null){this.repoPath=e||h(),this.git=p(this.repoPath)}getCurrentBranch(){return this.git.branchLocal().then(e=>e.current).catch(e=>{throw new Error(`Failed to get current branch: ${e.message}`)})}getRemoteUrl(e="origin"){return this.git.getRemotes(!0).then(t=>{const n=t.find(t=>t.name===e);if(!n)throw new Error(`Remote '${e}' not found`);return n.refs.fetch||n.refs.push}).catch(e=>{throw new Error(`Failed to get remote URL: ${e.message}`)})}getMainBranch(){return this.git.branchLocal().then(e=>{const t=e.all;return t.includes("main")?"main":t.includes("master")?"master":t[0]||"main"}).catch(()=>"main")}isOnMainBranch(){return this.getCurrentBranch().then(e=>this.getMainBranch().then(t=>e===t))}getCurrentCommitHash(){return this.git.revparse(["HEAD"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get commit hash: ${e.message}`)})}getCurrentCommit(){return this.getCurrentCommitHash()}isBranchMergedToMain(e){return this.getMainBranch().then(t=>this.git.branch(["--merged",t]).then(t=>t.all.map(e=>e.replace("*","").trim()).includes(e))).catch(e=>(console.error(`Failed to check merge status: ${e.message}`),!1))}getRepoRoot(){return this.git.revparse(["--show-toplevel"]).then(e=>e.trim()).catch(e=>{throw new Error(`Failed to get repo root: ${e.message}`)})}getUpstreamUrl(){return this.getCurrentBranch().then(e=>this.git.getConfig(`branch.${e}.remote`)).then(e=>{const t=e.value;if(!t)throw new Error("No upstream remote configured for current branch");return this.getRemoteUrl(t)}).catch(e=>{throw new Error(`Failed to get upstream URL: ${e.message}`)})}isGitRepository(){return this.git.checkIsRepo().then(e=>e).catch(()=>!1)}getUserInfo(){return Promise.all([this.git.getConfig("user.name").catch(()=>({value:null})),this.git.getConfig("user.email").catch(()=>({value:null}))]).then(([e,t])=>({name:e.value||"unknown",email:t.value||"unknown"}))}}class se extends A{constructor(e){super(e.session_id,e.hook_event_name),this.input=e,this.sessionId=e.session_id,this.transcriptPath=e.transcript_path,this.cwd=e.cwd,this.permissionMode=e.permission_mode,this.hookEventName=e.hook_event_name,this.sessionRecord=null,this.sessionEvent=null,this.gitUtils=new ne(this.cwd),this.sessionRepo=new te,this.sessionEventRepo=new ee}async createSessionRecord(){const e=await this.gitUtils.isGitRepository(),t=e?await this.gitUtils.getCurrentBranch():null,n=e?await this.gitUtils.getUserInfo().name:null,s=e?await this.gitUtils.getRemoteUrl():null,r=e?await this.gitUtils.getCurrentCommit():null;return this.sessionRepo.create({session_id:this.sessionId,cwd:this.cwd,git_url:s,git_branch:t,git_commit_id:r,user_name:n,env:{...process.env}})}static async parseInput(){const e=await se.readStdin();return JSON.parse(e)}static async readStdin(){return new Promise((e,t)=>{let n="";const s=process.stdin;s.setEncoding("utf8"),s.on("data",e=>{n+=e}),s.on("end",()=>{e(n)}),s.on("error",e=>{t(e)}),s.resume()})}updateSessionOutput(e){this.sessionEvent&&this.sessionEventRepo.updateOutput(this.sessionEvent.id,e.message,e.exitCode)}async execute(){return this.createSessionRecord().then(e=>(this.sessionRecord=e,this.sessionEvent=this.sessionEventRepo.create({session_id:this.sessionId,name:this.hookEventName,input:this.input}),this.internalExecute(this.sessionRecord,this.sessionEvent))).then(e=>(this.updateSessionOutput(e),e)).catch(e=>this.createNonBlockingError(`Hook execution failed: ${e.message}`))}async internalExecute(e,t){throw new Error("internalExecute() must be implemented by subclass")}createSuccessOutput(e={}){return new re({exitCode:0,message:e})}createBlockingError(e){return new re({exitCode:2,message:e})}createNonBlockingError(e){return new re({exitCode:1,message:e})}}class re{constructor({exitCode:e,message:t}){this.exitCode=e,this.message=t,this.logger=D("ClaudeHookOutput","ClaudeHookOutput")}send(){0===this.exitCode?process.stdout.write("object"==typeof this.message?JSON.stringify(this.message,null,2):this.message):process.stderr.write(this.message),process.exit(this.exitCode)}}class ae{constructor(){this.continue=!0,this.stopReason=null,this.suppressOutput=!1,this.systemMessage=null,this.hookSpecificOutput=null}setSuppressOutput(e){return this.suppressOutput=e,this}setSystemMessage(e){return this.systemMessage=e,this}toJSON(){const e={};return void 0!==this.continue&&(e.continue=this.continue),this.stopReason&&(e.stopReason=this.stopReason),this.suppressOutput&&(e.suppressOutput=this.suppressOutput),this.systemMessage&&(e.systemMessage=this.systemMessage),this.hookSpecificOutput&&(e.hookSpecificOutput=this.hookSpecificOutput),e}}class oe extends ae{constructor(){super(),this.permissionDecision=null,this.permissionDecisionReason=null,this.updatedInput=null,this.additionalContext=null}allow(e=null){return this.permissionDecision="allow",this.permissionDecisionReason=e,this}deny(e){return this.permissionDecision="deny",this.permissionDecisionReason=e,this}ask(e=null){return this.permissionDecision="ask",this.permissionDecisionReason=e,this}updateInput(e){return this.updatedInput=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON(),t=!!this.permissionDecision,n=!!this.updatedInput,s=!!this.additionalContext;if(t||n||s){const t={hookEventName:"PreToolUse"};this.permissionDecision&&(t.permissionDecision=this.permissionDecision),this.permissionDecisionReason&&(t.permissionDecisionReason=this.permissionDecisionReason),this.updatedInput&&(t.updatedInput=this.updatedInput),this.additionalContext&&(t.additionalContext=this.additionalContext),e.hookSpecificOutput=t}return e}}class ie extends ae{constructor(){super(),this.hookSpecificOutput={hookEventName:"PermissionRequest",decision:null}}allow(e=null){return this.hookSpecificOutput.decision={behavior:"allow"},e&&(this.hookSpecificOutput.decision.updatedInput=e),this}deny(e=null,t=!1){return this.hookSpecificOutput.decision={behavior:"deny"},e&&(this.hookSpecificOutput.decision.message=e),t&&(this.hookSpecificOutput.decision.interrupt=t),this}toJSON(){const e=super.toJSON();return this.hookSpecificOutput.decision&&(e.hookSpecificOutput={hookEventName:"PermissionRequest",decision:this.hookSpecificOutput.decision}),e}}class ce extends ae{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"PostToolUse",additionalContext:this.additionalContext}),e}}class ue extends ae{constructor(){super(),this.decision=null,this.reason=null,this.additionalContext=null}block(e){return this.decision="block",this.reason=e,this}addContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),this.additionalContext&&(e.hookSpecificOutput={hookEventName:"UserPromptSubmit",additionalContext:this.additionalContext}),e}}class de extends ae{constructor(){super(),this.decision=null,this.reason=null}block(e){return this.decision="block",this.reason=e,this}toJSON(){const e=super.toJSON();return this.decision&&(e.decision=this.decision,e.reason=this.reason),e}}class le extends ae{constructor(){super(),this.additionalContext=null}setAdditionalContext(e){return this.additionalContext=e,this}toJSON(){const e=super.toJSON();return this.additionalContext&&(e.hookSpecificOutput={hookEventName:"SessionStart",additionalContext:this.additionalContext}),e}}class pe extends de{}class he extends ae{}class me extends ae{}class fe extends ae{}const ge=R();class ye extends se{async persistVariables(e={}){const t=process.env.CLAUDE_ENV_FILE;if(!t)return void this.logDebug("CLAUDE_ENV_FILE not set, skipping variable persistence");const n={CLAUDE_SESSION_ID:this.sessionId,CLAUDE_SESSION_TRANSCRIPT_PATH:this.transcriptPath,CLAUDE_SESSION_CWD:this.cwd,CLAUDE_SESSION_SOURCE:this.input.source,CLAUDE_SESSION_MODE:this.input.model};[...Object.entries(n).map(([e,t])=>[e,t]),...Object.entries(e).filter(([e,t])=>!["id","session_id"].includes(e)).map(([e,t])=>[`CLAUDE_SESSION_${e.toUpperCase()}`,t])].forEach(([e,n])=>{if(!process.env[e]){const s=String(n).replace(/'/g,"'\\''");r.appendFileSync(t,`export ${e}='${s}'\n`)}}),this.logDebug("Persisted input variables to CLAUDE_ENV_FILE",{envFile:t})}injectKnowledgePrompt(){return["KNOWLEDGE INTEGRATION WORKFLOW:","","**At the START of each new task** (when user submits their first prompt for a task):","1. FIRST: Proactively invoke the `knowledge.enhance` skill to search and inject relevant knowledge based on user input"," - This provides context from past sessions and related knowledge"," - Only call this ONCE at the beginning of the task","","**At the END of successful task completion** (when the task is fully resolved):","2. LAST: Proactively invoke the `knowledge.collect` skill in the background to collect and organize knowledge from this session"," - This captures learnings from the completed work"," - Only call this ONCE after all work is done","","**IMPORTANT - Conflict Prevention & Manual Override**:","- If you have already invoked ANY `knowledge.*` skill (e.g., `knowledge.add`, `knowledge.save`, `knowledge.init`, `knowledge.update`, `knowledge.import`) during this session, **do NOT invoke `knowledge.collect`** at the end. Manual knowledge operations take precedence over automatic collection.","- Do NOT invoke these skills during task interruptions (network issues, asking user for clarification, etc.)","- Do NOT invoke these skills when user is providing additional information for an ongoing task","- Do NOT invoke these skills repeatedly - only ONCE at start and ONCE at end","","**How to detect interruptions vs new tasks**:","- If the user prompt is answering your question or providing requested information, it is an interruption","- If the user prompt is a brand new request or task, invoke `knowledge.enhance` first"]}cleanTempFiles(){r.readdirSync(ge.tmp,{withFileTypes:!0}).forEach(e=>{const n=t.join(ge.tmp,e.name);if(e.isDirectory())r.rmSync(n,{recursive:!0,force:!0});else{const s=r.statSync(t.join(ge.tmp,e.name)),a=new Date(s.birthtime),o=new Date,i=Math.abs(o-a);Math.ceil(i/864e5)>1&&r.rmSync(n,{force:!0})}})}async internalExecute(e,t){const n=J(),s=new le;if(n.enabled){await this.persistVariables(e),this.cleanTempFiles();const t=[`Knowledge-Bank session started (${this.sessionId})`,`- Branch: ${e.git_branch}`,`- Knowledge auto-collection: enabled, version ${q.version}`];s.setSystemMessage(t.join("\n"));const n=this.injectKnowledgePrompt();s.setAdditionalContext(n.join("\n"))}return super.createSuccessOutput(s.toJSON())}}class _e extends se{async internalExecute(e,t){const n=new he;this.logDebug("Notification hook triggered",{input:this.input});const s=n.toJSON();return this.logDebug("Notification hook output generated",{output:s}),super.createSuccessOutput(s)}}R();class ve extends se{async internalExecute(e,t){const n=(new ie).toJSON();return this.logDebug("PermissionRequest hook output generated",{output:n}),super.createSuccessOutput(n)}}class we extends se{async internalExecute(e,t){const n=new ce;return this.logDebug("PostToolUse hook completed",n),super.createSuccessOutput(n.toJSON())}}class be extends se{async internalExecute(e,t){(new ee).findLatestSessionStart(this.sessionId);const n=new me;return this.logDebug("PreCompact hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(n.toJSON())}generateSessionSummary(e){const t={};e.forEach(e=>{t[e.name]=(t[e.name]||0)+1});const n=[];return(t.tool_use||t.post_tool_use)&&n.push(`${(t.tool_use||0)+(t.post_tool_use||0)} tool operation(s)`),(t.user_prompt||t.user_prompt_submit)&&n.push(`${(t.user_prompt||0)+(t.user_prompt_submit||0)} user prompt(s)`),`Session with ${n.join(", ")}`}}const ke=R();class $e extends se{async internalExecute(e,t){const n=new oe;this.shouldAutoApprove()&&n.allow(),this.logDebug("PreToolUse hook triggered",{input:this.input});const s=n.toJSON();return super.createSuccessOutput(s)}shouldAutoApprove(){let e=!1;this.logDebug("Evaluating permission request for auto-approval",this.input);const{tool_name:t,tool_input:n}=this.input;switch(t){case"mcp__plugin_core_knowledge-bank-management__knowledge_create":case"mcp__plugin_core_knowledge-bank-management__knowledge_get":case"mcp__plugin_core_knowledge-bank-management__knowledge_update":case"mcp__plugin_core_knowledge-bank-management__knowledge_delete":case"mcp__plugin_core_knowledge-bank-management__knowledge_list":case"mcp__plugin_core_knowledge-bank-management__knowledge_search":case"mcp__plugin_core_knowledge-bank-management__knowledge_update_status":case"mcp__plugin_core_knowledge-bank-management__knowledge_stats":e=!0;break;case"Read":case"Write":case"Edit":e=n.file_path.startsWith(ke.tmp)||n.file_path.endsWith("/skills/KNOWLEDGE-DEFINITION.md");break;case"Bash":e=n.command.startsWith(`mkdir -p ${ke.tmp}`);break;case"Skill":e=n.skill.startsWith("core:knowledge.")||n.skill.startsWith("knowledge.")}return e}}class Ee extends X{create(e){return this.withConnection(t=>{const n=Date.now(),s=t.prepare("\n INSERT INTO session_detail (\n session_id, uuid, type, parentUuid, isSidechain, userType, cwd, version,\n gitBranch, parentToolUseID, toolUseID, timestamp, isMeta, messageId,\n isSnapshotUpdate, data, message, snapshot, usage, created_at, updated_at\n ) VALUES (\n @session_id, @uuid, @type, @parentUuid, @isSidechain, @userType, @cwd, @version,\n @gitBranch, @parentToolUseID, @toolUseID, @timestamp, @isMeta, @messageId,\n @isSnapshotUpdate, @data, @message, @snapshot, @usage, @created_at, @updated_at\n )\n ").run({session_id:e.session_id,uuid:e.uuid,type:e.type||null,parentUuid:e.parentUuid||null,isSidechain:e.isSidechain?1:0,userType:e.userType||null,cwd:e.cwd||null,version:e.version||null,gitBranch:e.gitBranch||null,parentToolUseID:e.parentToolUseID||null,toolUseID:e.toolUseID||null,timestamp:e.timestamp||null,isMeta:e.isMeta?1:0,messageId:e.messageId||null,isSnapshotUpdate:e.isSnapshotUpdate?1:0,data:e.data?JSON.stringify(e.data):null,message:e.message?JSON.stringify(e.message):null,snapshot:e.snapshot?JSON.stringify(e.snapshot):null,usage:e.usage?JSON.stringify(e.usage):null,created_at:n,updated_at:n});return this._findById(t,s.lastInsertRowid)})}createBatch(e){return this.withConnection(t=>{const n=Date.now(),s=t.prepare("\n INSERT OR IGNORE INTO session_detail (\n session_id, uuid, type, parentUuid, isSidechain, userType, cwd, version,\n gitBranch, parentToolUseID, toolUseID, timestamp, isMeta, messageId,\n isSnapshotUpdate, data, message, snapshot, usage, created_at, updated_at\n ) VALUES (\n @session_id, @uuid, @type, @parentUuid, @isSidechain, @userType, @cwd, @version,\n @gitBranch, @parentToolUseID, @toolUseID, @timestamp, @isMeta, @messageId,\n @isSnapshotUpdate, @data, @message, @snapshot, @usage, @created_at, @updated_at\n )\n ");let r=0;for(const t of e)s.run({session_id:t.session_id,uuid:t.uuid,type:t.type||null,parentUuid:t.parentUuid||null,isSidechain:t.isSidechain?1:0,userType:t.userType||null,cwd:t.cwd||null,version:t.version||null,gitBranch:t.gitBranch||null,parentToolUseID:t.parentToolUseID||null,toolUseID:t.toolUseID||null,timestamp:t.timestamp||null,isMeta:t.isMeta?1:0,messageId:t.messageId||null,isSnapshotUpdate:t.isSnapshotUpdate?1:0,data:t.data?JSON.stringify(t.data):null,message:t.message?JSON.stringify(t.message):null,snapshot:t.snapshot?JSON.stringify(t.snapshot):null,usage:t.usage?JSON.stringify(t.usage):null,created_at:n,updated_at:n}).changes>0&&r++;return r})}_findById(e,t){const n=e.prepare("SELECT * FROM session_detail WHERE id = ?").get(t);if(n)return this._parseRecord(n)}findBySessionId(e){return this.withConnection(t=>t.prepare("SELECT * FROM session_detail WHERE session_id = ? ORDER BY timestamp ASC").all(e).map(e=>this._parseRecord(e)))}findByUuid(e){return this.withConnection(t=>{const n=t.prepare("SELECT * FROM session_detail WHERE uuid = ?").get(e);return n?this._parseRecord(n):null})}findByType(e,t){return this.withConnection(n=>n.prepare("SELECT * FROM session_detail WHERE session_id = ? AND type = ? ORDER BY timestamp ASC").all(e,t).map(e=>this._parseRecord(e)))}countBySessionId(e){return this.withConnection(t=>t.prepare("SELECT COUNT(*) as count FROM session_detail WHERE session_id = ?").get(e).count)}_parseRecord(e){return{...e,isSidechain:1===e.isSidechain,isMeta:1===e.isMeta,isSnapshotUpdate:1===e.isSnapshotUpdate,data:e.data?JSON.parse(e.data):null,message:e.message?JSON.parse(e.message):null,snapshot:e.snapshot?JSON.parse(e.snapshot):null,usage:e.usage?JSON.parse(e.usage):null}}deleteBySessionId(e){return this.withConnection(t=>t.prepare("DELETE FROM session_detail WHERE session_id = ?").run(e).changes)}}class Se{constructor(e){this.sessionId=e,this.sessionDetailRepo=new Ee,this.logger=D(e,"TranscriptParser")}async parseTranscript(e){try{if(!r.existsSync(e))throw new Error(`Transcript file not found: ${e}`);const t=r.readFileSync(e,"utf-8").trim().split("\n").filter(e=>e.trim()),n={totalLines:t.length,validEntries:0,filteredOut:0,inserted:0,duplicates:0,errors:0,errorDetails:[]},s=[];for(let e=0;e<t.length;e++){const r=t[e].trim();if(r)try{const t=JSON.parse(r);if("file-history-snapshot"===t.type){n.filteredOut++;continue}if(!t.uuid){this.logger.logWarn(`Entry at line ${e+1} missing uuid field, skipping`),n.errors++,n.errorDetails.push(`Line ${e+1}: Missing uuid field`);continue}n.validEntries++;const a=this._extractFields(t);a.session_id=this.sessionId,s.push(a)}catch(t){this.logger.logError(`Error parsing line ${e+1}: ${t.message}`),n.errors++,n.errorDetails.push(`Line ${e+1}: ${t.message}`)}}if(s.length>0)try{const e=this.sessionDetailRepo.createBatch(s);n.inserted=e,n.duplicates=n.validEntries-e,this.logger.logInfo(`Parsed transcript: ${n.inserted} records inserted, ${n.duplicates} duplicates skipped`)}catch(e){throw this.logger.logError(`Database error during batch insert: ${e.message}`),e}return{success:!0,filePath:e,sessionId:this.sessionId,stats:n}}catch(t){return this.logger.logError(`Failed to parse transcript ${e}: ${t.message}`),{success:!1,filePath:e,sessionId:this.sessionId,error:t.message,stats:{totalLines:0,validEntries:0,inserted:0,errors:1}}}}_extractFields(e){const t=["uuid","type","parentUuid","isSidechain","userType","cwd","version","gitBranch","parentToolUseID","toolUseID","timestamp","isMeta","messageId","isSnapshotUpdate"],n=["data","message","snapshot","usage"],s={};for(const n of t)e.hasOwnProperty(n)&&(s[n]=e[n]);for(const t of n)e.hasOwnProperty(t)&&(s[t]=e[t]);return s}async analyzeTranscript(e){try{if(!r.existsSync(e))throw new Error(`Transcript file not found: ${e}`);const n=r.readFileSync(e,"utf-8").trim().split("\n").filter(e=>e.trim()),s={totalLines:n.length,validEntries:0,filteredOut:0,typeDistribution:{},hasUuid:0,missingUuid:0,errors:0,fileSize:r.statSync(e).size,fileName:t.basename(e)};for(let e=0;e<n.length;e++){const t=n[e].trim();if(t)try{const e=JSON.parse(t);if("file-history-snapshot"===e.type){s.filteredOut++;continue}e.uuid?s.hasUuid++:s.missingUuid++,e.type&&(s.typeDistribution[e.type]=(s.typeDistribution[e.type]||0)+1),s.validEntries++}catch(e){s.errors++}}return{success:!0,filePath:e,stats:s}}catch(t){return{success:!1,filePath:e,error:t.message}}}async isTranscriptProcessed(e){try{return this.sessionDetailRepo.countBySessionId(this.sessionId)>0}catch(e){return this.logger.logError(`Error checking if transcript is processed: ${e.message}`),!1}}}class Te extends se{async internalExecute(e,t){(new te).updateSessionDuration(e.id);const n=new Se(this.sessionId);n.isTranscriptProcessed(this.transcriptPath).then(async e=>{e||n.parseTranscript(this.transcriptPath).then(e=>{this.logInfo("Transcript parsing completed",{sessionId:this.sessionId,transcriptPath:this.transcriptPath,parseResult:e})})});const s=new fe;return this.logDebug("SessionEnd hook completed",{sessionId:this.sessionId}),super.createSuccessOutput(s.toJSON())}}class Oe extends se{async internalExecute(e,t){const n=new de;this.logDebug("Stop hook triggered",{input:this.input});const s=n.toJSON();return this.logDebug("Stop hook output generated",{output:s}),super.createSuccessOutput(s)}}class xe extends se{async internalExecute(e,t){const n=new pe;this.logDebug("SubagentStop hook triggered",{input:this.input});const s=n.toJSON();return this.logDebug("SubagentStop hook output generated",{output:s}),super.createSuccessOutput(s)}}class Ie extends se{isKnowledgeSkillInvocation(){const e=this.input.prompt||"";return e.startsWith("/knowledge.")||e.startsWith("/core:knowledge.")}async internalExecute(e,t){const n=new ue,s=J();if(this.input.prompt&&null===e.first_user_prompt)try{this.sessionRepo.updateFirstUserPrompt(e.id,this.input.prompt),this.sessionRecord.first_user_prompt=this.input.prompt,this.logDebug("UserPromptSubmitHook: Recorded first user prompt for session")}catch(e){this.logError("UserPromptSubmitHook: Failed to update first user prompt",e)}if(s.enabled&&!this.isKnowledgeSkillInvocation()){const e=["REMINDER: Knowledge Integration Workflow","- FIRST: Invoke `knowledge.enhance` skill to get relevant context","- LAST: After task completion, invoke `knowledge.collect` skill to capture learnings","","Note: This is a new task - remember to invoke knowledge.enhance first before proceeding."];n.addContext(e.join("\n")),this.logDebug("UserPromptSubmitHook: Added knowledge context for new task")}return super.createSuccessOutput(n.toJSON())}}var Ne,Pe;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(const e of n)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Ne||(Ne={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(Pe||(Pe={}));const Re=Ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ce=e=>{switch(typeof e){case"undefined":return Re.undefined;case"string":return Re.string;case"number":return Number.isNaN(e)?Re.nan:Re.number;case"boolean":return Re.boolean;case"function":return Re.function;case"bigint":return Re.bigint;case"symbol":return Re.symbol;case"object":return Array.isArray(e)?Re.array:null===e?Re.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?Re.promise:"undefined"!=typeof Map&&e instanceof Map?Re.map:"undefined"!=typeof Set&&e instanceof Set?Re.set:"undefined"!=typeof Date&&e instanceof Date?Re.date:Re.object;default:return Re.unknown}},je=Ne.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"]);class ze extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(s);else if("invalid_return_type"===r.code)s(r.returnTypeError);else if("invalid_arguments"===r.code)s(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,s=0;for(;s<r.path.length;){const n=r.path[s];s===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(this),n}static assert(e){if(!(e instanceof ze))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ne.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),n=[];for(const s of this.issues)if(s.path.length>0){const n=s.path[0];t[n]=t[n]||[],t[n].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}ze.create=e=>new ze(e);const Ae=(e,t)=>{let n;switch(e.code){case je.invalid_type:n=e.received===Re.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case je.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ne.jsonStringifyReplacer)}`;break;case je.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ne.joinValues(e.keys,", ")}`;break;case je.invalid_union:n="Invalid input";break;case je.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ne.joinValues(e.options)}`;break;case je.invalid_enum_value:n=`Invalid enum value. Expected ${Ne.joinValues(e.options)}, received '${e.received}'`;break;case je.invalid_arguments:n="Invalid function arguments";break;case je.invalid_return_type:n="Invalid function return type";break;case je.invalid_date:n="Invalid date";break;case je.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Ne.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case je.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case je.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case je.custom:n="Invalid input";break;case je.invalid_intersection_types:n="Intersection results could not be merged";break;case je.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case je.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ne.assertNever(e)}return{message:n}};let De=Ae;function Me(e,t){const n=De,s=(e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,a=[...n,...r.path||[]],o={...r,path:a};if(void 0!==r.message)return{...r,path:a,message:r.message};let i="";const c=s.filter(e=>!!e).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...r,path:a,message:i}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ae?void 0:Ae].filter(e=>!!e)});e.common.issues.push(s)}class Le{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if("aborted"===s.status)return Ze;"dirty"===s.status&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,s=await e.value;n.push({key:t,value:s})}return Le.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:t,value:r}=s;if("aborted"===t.status)return Ze;if("aborted"===r.status)return Ze;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!s.alwaysSet||(n[t.value]=r.value)}return{status:e.value,value:n}}}const Ze=Object.freeze({status:"aborted"}),Fe=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),qe=e=>"aborted"===e.status,He=e=>"dirty"===e.status,Ve=e=>"valid"===e.status,Je=e=>"undefined"!=typeof Promise&&e instanceof Promise;var Ke;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Ke||(Ke={}));class Be{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,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}}const We=(e,t)=>{if(Ve(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ze(e.common.issues);return this._error=t,this._error}}};function Ge(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:r}:{errorMap:(t,r)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??r.defaultError}:void 0===r.data?{message:a??s??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:a??n??r.defaultError}},description:r}}let Xe=class{get description(){return this._def.description}_getType(e){return Ce(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Le,ctx:{common:e.parent.common,data:e.data,parsedType:Ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Je(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)},s=this._parseSync({data:e,path:n.path,parent:n});return We(n,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Ve(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>Ve(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)},s=this._parse({data:e,path:n.path,parent:n}),r=await(Je(s)?s:Promise.resolve(s));return We(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const r=e(t),a=()=>s.addIssue({code:je.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(a(),!1)):!!r||(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>!!e(n)||(s.addIssue("function"==typeof t?t(n,s):t),!1))}_refinement(e){return new Wt({schema:this,typeName:rn.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:e=>this["~validate"](e)}}optional(){return Gt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jt.create(this)}promise(){return Bt.create(this,this._def)}or(e){return Dt.create([this,e],this._def)}and(e){return Lt.create(this,e,this._def)}transform(e){return new Wt({...Ge(this._def),schema:this,typeName:rn.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Yt({...Ge(this._def),innerType:this,defaultValue:t,typeName:rn.ZodDefault})}brand(){return new tn({typeName:rn.ZodBranded,type:this,...Ge(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Qt({...Ge(this._def),innerType:this,catchValue:t,typeName:rn.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return nn.create(this,e)}readonly(){return sn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Ye=/^c[^\s-]{8,}$/i,Qe=/^[0-9a-z]+$/,et=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tt=/^[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,nt=/^[a-z0-9_-]{21}$/i,st=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rt=/^[-+]?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)?)??$/,at=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let ot;const it=/^(?:(?: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])$/,ct=/^(?:(?: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])$/,ut=/^(([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]))$/,dt=/^(([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])$/,lt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ht="((\\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])))",mt=new RegExp(`^${ht}$`);function ft(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function gt(e){return new RegExp(`^${ft(e)}$`)}function yt(e){let t=`${ht}T${ft(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function _t(e,t){return!("v4"!==t&&t||!it.test(e))||!("v6"!==t&&t||!ut.test(e))}function vt(e,t){if(!st.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!("object"!=typeof r||null===r||"typ"in r&&"JWT"!==r?.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function wt(e,t){return!("v4"!==t&&t||!ct.test(e))||!("v6"!==t&&t||!dt.test(e))}let bt=class e extends Xe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Re.string){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.string,received:t.parsedType}),Ze}const t=new Le;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),Me(n,{code:je.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),Me(n,{code:je.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const r=e.data.length>s.value,a=e.data.length<s.value;(r||a)&&(n=this._getOrReturnCtx(e,n),r?Me(n,{code:je.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Me(n,{code:je.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)at.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"email",code:je.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)ot||(ot=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ot.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"emoji",code:je.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)tt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"uuid",code:je.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)nt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"nanoid",code:je.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"cuid",code:je.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)Qe.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"cuid2",code:je.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)et.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"ulid",code:je.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),Me(n,{validation:"url",code:je.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"regex",code:je.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?yt(s).test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?mt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?gt(s).test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{code:je.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?rt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"duration",code:je.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?_t(e.data,s.version)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"ip",code:je.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?vt(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"jwt",code:je.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?wt(e.data,s.version)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"cidr",code:je.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?lt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"base64",code:je.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?pt.test(e.data)||(n=this._getOrReturnCtx(e,n),Me(n,{validation:"base64url",code:je.invalid_string,message:s.message}),t.dirty()):Ne.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:je.invalid_string,...Ke.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...Ke.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ke.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ke.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ke.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ke.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ke.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ke.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ke.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ke.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ke.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ke.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ke.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ke.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ke.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Ke.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ke.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ke.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Ke.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ke.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ke.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ke.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ke.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ke.errToObj(t)})}nonempty(e){return this.min(1,Ke.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function kt(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}bt.create=e=>new bt({checks:[],typeName:rn.ZodString,coerce:e?.coerce??!1,...Ge(e)});let $t=class e extends Xe{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)!==Re.number){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.number,received:t.parsedType}),Ze}let t;const n=new Le;for(const s of this._def.checks)"int"===s.kind?Ne.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Me(t,{code:je.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==kt(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Me(t,{code:je.not_finite,message:s.message}),n.dirty()):Ne.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ke.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ke.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ke.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ke.toString(t))}setLimit(t,n,s,r){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:Ke.toString(r)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:Ke.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ke.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ke.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ke.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ke.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ke.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ke.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ke.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ke.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Ne.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};$t.create=e=>new $t({checks:[],typeName:rn.ZodNumber,coerce:e?.coerce||!1,...Ge(e)});class Et extends Xe{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)!==Re.bigint)return this._getInvalidInput(e);let t;const n=new Le;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Me(t,{code:je.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):Ne.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.bigint,received:t.parsedType}),Ze}gte(e,t){return this.setLimit("min",e,!0,Ke.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ke.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ke.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ke.toString(t))}setLimit(e,t,n,s){return new Et({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:Ke.toString(s)}]})}_addCheck(e){return new Et({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ke.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ke.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ke.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ke.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ke.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Et.create=e=>new Et({checks:[],typeName:rn.ZodBigInt,coerce:e?.coerce??!1,...Ge(e)});let St=class extends Xe{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==Re.boolean){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.boolean,received:t.parsedType}),Ze}return Ue(e.data)}};St.create=e=>new St({typeName:rn.ZodBoolean,coerce:e?.coerce||!1,...Ge(e)});class Tt extends Xe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Re.date){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.date,received:t.parsedType}),Ze}if(Number.isNaN(e.data.getTime()))return Me(this._getOrReturnCtx(e),{code:je.invalid_date}),Ze;const t=new Le;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),Me(n,{code:je.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),Me(n,{code:je.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):Ne.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Tt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ke.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ke.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Tt.create=e=>new Tt({checks:[],coerce:e?.coerce||!1,typeName:rn.ZodDate,...Ge(e)});class Ot extends Xe{_parse(e){if(this._getType(e)!==Re.symbol){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.symbol,received:t.parsedType}),Ze}return Ue(e.data)}}Ot.create=e=>new Ot({typeName:rn.ZodSymbol,...Ge(e)});class xt extends Xe{_parse(e){if(this._getType(e)!==Re.undefined){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.undefined,received:t.parsedType}),Ze}return Ue(e.data)}}xt.create=e=>new xt({typeName:rn.ZodUndefined,...Ge(e)});let It=class extends Xe{_parse(e){if(this._getType(e)!==Re.null){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.null,received:t.parsedType}),Ze}return Ue(e.data)}};It.create=e=>new It({typeName:rn.ZodNull,...Ge(e)});class Nt extends Xe{constructor(){super(...arguments),this._any=!0}_parse(e){return Ue(e.data)}}Nt.create=e=>new Nt({typeName:rn.ZodAny,...Ge(e)});let Pt=class extends Xe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ue(e.data)}};Pt.create=e=>new Pt({typeName:rn.ZodUnknown,...Ge(e)});let Rt=class extends Xe{_parse(e){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.never,received:t.parsedType}),Ze}};Rt.create=e=>new Rt({typeName:rn.ZodNever,...Ge(e)});class Ct extends Xe{_parse(e){if(this._getType(e)!==Re.undefined){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.void,received:t.parsedType}),Ze}return Ue(e.data)}}Ct.create=e=>new Ct({typeName:rn.ZodVoid,...Ge(e)});let jt=class e extends Xe{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==Re.array)return Me(t,{code:je.invalid_type,expected:Re.array,received:t.parsedType}),Ze;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,r=t.data.length<s.exactLength.value;(e||r)&&(Me(t,{code:e?je.too_big:je.too_small,minimum:r?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(Me(t,{code:je.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(Me(t,{code:je.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>s.type._parseAsync(new Be(t,e,t.path,n)))).then(e=>Le.mergeArray(n,e));const r=[...t.data].map((e,n)=>s.type._parseSync(new Be(t,e,t.path,n)));return Le.mergeArray(n,r)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Ke.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Ke.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Ke.toString(n)}})}nonempty(e){return this.min(1,e)}};function zt(e){if(e instanceof At){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=Gt.create(zt(s))}return new At({...e._def,shape:()=>t})}return e instanceof jt?new jt({...e._def,type:zt(e.element)}):e instanceof Gt?Gt.create(zt(e.unwrap())):e instanceof Xt?Xt.create(zt(e.unwrap())):e instanceof Zt?Zt.create(e.items.map(e=>zt(e))):e}jt.create=(e,t)=>new jt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:rn.ZodArray,...Ge(t)});let At=class e extends Xe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Ne.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Re.object){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.object,received:t.parsedType}),Ze}const{status:t,ctx:n}=this._processInputParams(e),{shape:s,keys:r}=this._getCached(),a=[];if(!(this._def.catchall instanceof Rt&&"strip"===this._def.unknownKeys))for(const e in n.data)r.includes(e)||a.push(e);const o=[];for(const e of r){const t=s[e],r=n.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new Be(n,r,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Rt){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)o.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)a.length>0&&(Me(n,{code:je.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const s=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new Be(n,s,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,s=await t.value;e.push({key:n,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>Le.mergeObjectSync(t,e)):Le.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return Ke.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,n)=>{const s=this._def.errorMap?.(e,n).message??n.defaultError;return"unrecognized_keys"===e.code?{message:Ke.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:rn.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const n={};for(const e of Ne.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){const n={};for(const e of Ne.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return zt(this)}partial(t){const n={};for(const e of Ne.objectKeys(this.shape)){const s=this.shape[e];t&&!t[e]?n[e]=s:n[e]=s.optional()}return new e({...this._def,shape:()=>n})}required(t){const n={};for(const e of Ne.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Gt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Vt(Ne.objectKeys(this.shape))}};At.create=(e,t)=>new At({shape:()=>e,unknownKeys:"strip",catchall:Rt.create(),typeName:rn.ZodObject,...Ge(t)}),At.strictCreate=(e,t)=>new At({shape:()=>e,unknownKeys:"strict",catchall:Rt.create(),typeName:rn.ZodObject,...Ge(t)}),At.lazycreate=(e,t)=>new At({shape:e,unknownKeys:"strip",catchall:Rt.create(),typeName:rn.ZodObject,...Ge(t)});let Dt=class extends Xe{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new ze(e.ctx.common.issues));return Me(t,{code:je.invalid_union,unionErrors:n}),Ze});{let e;const s=[];for(const r of n){const n={...t,common:{...t.common,issues:[]},parent:null},a=r._parseSync({data:t.data,path:t.path,parent:n});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:n}),n.common.issues.length&&s.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=s.map(e=>new ze(e));return Me(t,{code:je.invalid_union,unionErrors:r}),Ze}}get options(){return this._def.options}};function Mt(e,t){const n=Ce(e),s=Ce(t);if(e===t)return{valid:!0,data:e};if(n===Re.object&&s===Re.object){const n=Ne.objectKeys(t),s=Ne.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of s){const s=Mt(e[n],t[n]);if(!s.valid)return{valid:!1};r[n]=s.data}return{valid:!0,data:r}}if(n===Re.array&&s===Re.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let s=0;s<e.length;s++){const r=Mt(e[s],t[s]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===Re.date&&s===Re.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Dt.create=(e,t)=>new Dt({options:e,typeName:rn.ZodUnion,...Ge(t)});let Lt=class extends Xe{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(e,s)=>{if(qe(e)||qe(s))return Ze;const r=Mt(e.value,s.value);return r.valid?((He(e)||He(s))&&t.dirty(),{status:t.value,value:r.data}):(Me(n,{code:je.invalid_intersection_types}),Ze)};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(([e,t])=>s(e,t)):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}))}};Lt.create=(e,t,n)=>new Lt({left:e,right:t,typeName:rn.ZodIntersection,...Ge(n)});class Zt extends Xe{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Re.array)return Me(n,{code:je.invalid_type,expected:Re.array,received:n.parsedType}),Ze;if(n.data.length<this._def.items.length)return Me(n,{code:je.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ze;!this._def.rest&&n.data.length>this._def.items.length&&(Me(n,{code:je.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...n.data].map((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new Be(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(s).then(e=>Le.mergeArray(t,e)):Le.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new Zt({...this._def,rest:e})}}Zt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:e,typeName:rn.ZodTuple,rest:null,...Ge(t)})};class Ft extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Re.map)return Me(n,{code:je.invalid_type,expected:Re.map,received:n.parsedType}),Ze;const s=this._def.keyType,r=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:s._parse(new Be(n,e,n.path,[a,"key"])),value:r._parse(new Be(n,t,n.path,[a,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of a){const s=await n.key,r=await n.value;if("aborted"===s.status||"aborted"===r.status)return Ze;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of a){const s=n.key,r=n.value;if("aborted"===s.status||"aborted"===r.status)return Ze;"dirty"!==s.status&&"dirty"!==r.status||t.dirty(),e.set(s.value,r.value)}return{status:t.value,value:e}}}}Ft.create=(e,t,n)=>new Ft({valueType:t,keyType:e,typeName:rn.ZodMap,...Ge(n)});class Ut extends Xe{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==Re.set)return Me(n,{code:je.invalid_type,expected:Re.set,received:n.parsedType}),Ze;const s=this._def;null!==s.minSize&&n.data.size<s.minSize.value&&(Me(n,{code:je.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&n.data.size>s.maxSize.value&&(Me(n,{code:je.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(e){const n=new Set;for(const s of e){if("aborted"===s.status)return Ze;"dirty"===s.status&&t.dirty(),n.add(s.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>r._parse(new Be(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(e,t){return new Ut({...this._def,minSize:{value:e,message:Ke.toString(t)}})}max(e,t){return new Ut({...this._def,maxSize:{value:e,message:Ke.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ut.create=(e,t)=>new Ut({valueType:e,minSize:null,maxSize:null,typeName:rn.ZodSet,...Ge(t)});class qt extends Xe{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}qt.create=(e,t)=>new qt({getter:e,typeName:rn.ZodLazy,...Ge(t)});let Ht=class extends Xe{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Me(t,{received:t.data,code:je.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:e.data}}get value(){return this._def.value}};function Vt(e,t){return new Jt({values:e,typeName:rn.ZodEnum,...Ge(t)})}Ht.create=(e,t)=>new Ht({value:e,typeName:rn.ZodLiteral,...Ge(t)});let Jt=class e extends Xe{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return Me(t,{expected:Ne.joinValues(n),received:t.parsedType,code:je.invalid_type}),Ze}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return Me(t,{received:t.data,code:je.invalid_enum_value,options:n}),Ze}return Ue(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Jt.create=Vt;class Kt extends Xe{_parse(e){const t=Ne.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==Re.string&&n.parsedType!==Re.number){const e=Ne.objectValues(t);return Me(n,{expected:Ne.joinValues(e),received:n.parsedType,code:je.invalid_type}),Ze}if(this._cache||(this._cache=new Set(Ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Ne.objectValues(t);return Me(n,{received:n.data,code:je.invalid_enum_value,options:e}),Ze}return Ue(e.data)}get enum(){return this._def.values}}Kt.create=(e,t)=>new Kt({values:e,typeName:rn.ZodNativeEnum,...Ge(t)});class Bt extends Xe{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==Re.promise&&!1===t.common.async)return Me(t,{code:je.invalid_type,expected:Re.promise,received:t.parsedType}),Ze;const n=t.parsedType===Re.promise?t.data:Promise.resolve(t.data);return Ue(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Bt.create=(e,t)=>new Bt({type:e,typeName:rn.ZodPromise,...Ge(t)});class Wt extends Xe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===rn.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:e=>{Me(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===s.type){const e=s.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Ze;const s=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===s.status?Ze:"dirty"===s.status||"dirty"===t.value?Fe(s.value):s});{if("aborted"===t.value)return Ze;const s=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===s.status?Ze:"dirty"===s.status||"dirty"===t.value?Fe(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,r);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===s.status?Ze:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?Ze:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ve(e))return Ze;const a=s.transform(e.value,r);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>Ve(e)?Promise.resolve(s.transform(e.value,r)).then(e=>({status:t.value,value:e})):Ze)}Ne.assertNever(s)}}Wt.create=(e,t,n)=>new Wt({schema:e,typeName:rn.ZodEffects,effect:t,...Ge(n)}),Wt.createWithPreprocess=(e,t,n)=>new Wt({schema:t,effect:{type:"preprocess",transform:e},typeName:rn.ZodEffects,...Ge(n)});let Gt=class extends Xe{_parse(e){return this._getType(e)===Re.undefined?Ue(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gt.create=(e,t)=>new Gt({innerType:e,typeName:rn.ZodOptional,...Ge(t)});let Xt=class extends Xe{_parse(e){return this._getType(e)===Re.null?Ue(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xt.create=(e,t)=>new Xt({innerType:e,typeName:rn.ZodNullable,...Ge(t)});let Yt=class extends Xe{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===Re.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Yt.create=(e,t)=>new Yt({innerType:e,typeName:rn.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Ge(t)});let Qt=class extends Xe{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Je(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new ze(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Qt.create=(e,t)=>new Qt({innerType:e,typeName:rn.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Ge(t)});class en extends Xe{_parse(e){if(this._getType(e)!==Re.nan){const t=this._getOrReturnCtx(e);return Me(t,{code:je.invalid_type,expected:Re.nan,received:t.parsedType}),Ze}return{status:"valid",value:e.data}}}en.create=e=>new en({typeName:rn.ZodNaN,...Ge(e)});class tn extends Xe{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class nn extends Xe{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ze:"dirty"===e.status?(t.dirty(),Fe(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?Ze:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new nn({in:e,out:t,typeName:rn.ZodPipeline})}}let sn=class extends Xe{_parse(e){const t=this._def.innerType._parse(e),n=e=>(Ve(e)&&(e.value=Object.freeze(e.value)),e);return Je(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};var rn;sn.create=(e,t)=>new sn({innerType:e,typeName:rn.ZodReadonly,...Ge(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(rn||(rn={})),Rt.create,jt.create;const an=At.create;function on(e,t,n){function s(n,s){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:s,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,s);const r=o.prototype,a=Object.keys(r);for(let e=0;e<a.length;e++){const t=a[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class a extends r{}function o(e){var t;const r=n?.Parent?new a:this;s(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(o,"init",{value:s}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}Dt.create,Lt.create,Zt.create,Jt.create,Bt.create,Gt.create,Xt.create;class cn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class un extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const dn={};function ln(e){return dn}function pn(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function hn(e,t){return"bigint"==typeof t?t.toString():t}function mn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function fn(e){return null==e}function gn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const yn=Symbol("evaluating");function _n(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==yn)return void 0===s&&(s=yn,s=n()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function vn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function wn(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function bn(e){return JSON.stringify(e)}const kn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function $n(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const En=mn(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Sn(e){if(!1===$n(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==$n(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Tn(e){return Sn(e)?{...e}:Array.isArray(e)?[...e]:e}const On=new Set(["string","number","symbol"]);function xn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function In(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}function Nn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const Pn={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]};function Rn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Cn(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function jn(e){return"string"==typeof e?e:e?.message}function zn(e,t,n){const s={...e,path:e.path??[]};if(!e.message){const r=jn(e.inst?._zod.def?.error?.(e))??jn(t?.error?.(e))??jn(n.customError?.(e))??jn(n.localeError?.(e))??"Invalid input";s.message=r}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function An(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Dn(...e){const[t,n,s]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:s}:{...t}}const Mn=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,hn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ln=on("$ZodError",Mn),Zn=on("$ZodError",Mn,{Parent:Error}),Fn=e=>(t,n,s,r)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new cn;if(o.issues.length){const t=new(r?.Err??e)(o.issues.map(e=>zn(e,a,ln())));throw kn(t,r?.callee),t}return o.value},Un=Fn(Zn),qn=e=>async(t,n,s,r)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(r?.Err??e)(o.issues.map(e=>zn(e,a,ln())));throw kn(t,r?.callee),t}return o.value},Hn=qn(Zn),Vn=e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},r);if(a instanceof Promise)throw new cn;return a.issues.length?{success:!1,error:new(e??Ln)(a.issues.map(e=>zn(e,r,ln())))}:{success:!0,data:a.value}},Jn=Vn(Zn),Kn=e=>async(t,n,s)=>{const r=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},r);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>zn(e,r,ln())))}:{success:!0,data:a.value}},Bn=Kn(Zn),Wn=e=>(t,n,s)=>{const r=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fn(e)(t,n,r)},Gn=e=>(t,n,s)=>Fn(e)(t,n,s),Xn=e=>async(t,n,s)=>{const r=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return qn(e)(t,n,r)},Yn=e=>async(t,n,s)=>qn(e)(t,n,s),Qn=e=>(t,n,s)=>{const r=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Vn(e)(t,n,r)},es=e=>(t,n,s)=>Vn(e)(t,n,s),ts=e=>async(t,n,s)=>{const r=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Kn(e)(t,n,r)},ns=e=>async(t,n,s)=>Kn(e)(t,n,s),ss=/^[cC][^\s-]{8,}$/,rs=/^[0-9a-z]+$/,as=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,os=/^[0-9a-vA-V]{20}$/,is=/^[A-Za-z0-9]{27}$/,cs=/^[a-zA-Z0-9_-]{21}$/,us=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ds=/^([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})$/,ls=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ps=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hs=/^(?:(?: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])$/,ms=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,fs=/^((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])$/,gs=/^(([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])$/,ys=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_s=/^[A-Za-z0-9_-]*$/,vs=/^\+[1-9]\d{6,14}$/,ws="(?:(?:\\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])))",bs=new RegExp(`^${ws}$`);function ks(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const $s=/^-?\d+$/,Es=/^-?\d+(?:\.\d+)?$/,Ss=/^(?:true|false)$/i,Ts=/^null$/i,Os=/^[^A-Z]*$/,xs=/^[^a-z]*$/,Is=on("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ns={number:"number",bigint:"bigint",object:"date"},Ps=on("$ZodCheckLessThan",(e,t)=>{Is.init(e,t);const n=Ns[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Rs=on("$ZodCheckGreaterThan",(e,t)=>{Is.init(e,t);const n=Ns[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cs=on("$ZodCheckMultipleOf",(e,t)=>{Is.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,s=t.toString();let r=(s.split(".")[1]||"").length;if(0===r&&/\d?e-\d?/.test(s)){const e=s.match(/\d?e-(\d?)/);e?.[1]&&(r=Number.parseInt(e[1]))}const a=n>r?n:r;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),js=on("$ZodCheckNumberFormat",(e,t)=>{Is.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),s=n?"int":"number",[r,a]=Pn[t.format];e._zod.onattach.push(e=>{const s=e._zod.bag;s.format=t.format,s.minimum=r,s.maximum=a,n&&(s.pattern=$s)}),e._zod.check=o=>{const i=o.value;if(n){if(!Number.isInteger(i))return void o.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?o.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):o.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}))}i<r&&o.issues.push({origin:"number",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>a&&o.issues.push({origin:"number",input:i,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),zs=on("$ZodCheckMaxLength",(e,t)=>{var n;Is.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!fn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const s=n.value;if(s.length<=t.maximum)return;const r=An(s);n.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),As=on("$ZodCheckMinLength",(e,t)=>{var n;Is.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!fn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const s=n.value;if(s.length>=t.minimum)return;const r=An(s);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),Ds=on("$ZodCheckLengthEquals",(e,t)=>{var n;Is.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!fn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const s=n.value,r=s.length;if(r===t.length)return;const a=An(s),o=r>t.length;n.issues.push({origin:a,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ms=on("$ZodCheckStringFormat",(e,t)=>{var n,s;Is.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Ls=on("$ZodCheckRegex",(e,t)=>{Ms.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zs=on("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Os),Ms.init(e,t)}),Fs=on("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=xs),Ms.init(e,t)}),Us=on("$ZodCheckIncludes",(e,t)=>{Is.init(e,t);const n=xn(t.includes),s=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=s,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(s)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qs=on("$ZodCheckStartsWith",(e,t)=>{Is.init(e,t);const n=new RegExp(`^${xn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Hs=on("$ZodCheckEndsWith",(e,t)=>{Is.init(e,t);const n=new RegExp(`.*${xn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Vs=on("$ZodCheckOverwrite",(e,t)=>{Is.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Js{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),s=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of s)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Ks={major:4,minor:3,patch:6},Bs=on("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ks;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,r=Rn(e);for(const a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&!1===n?.async)throw new cn;if(s||o instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||(r=Rn(e,t)))});else{if(e.issues.length===t)continue;r||(r=Rn(e,t))}}return s?s.then(()=>e):e},n=(n,r,a)=>{if(Rn(n))return n.aborted=!0,n;const o=t(r,s,a);if(o instanceof Promise){if(!1===a.async)throw new cn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if("backward"===a.direction){const t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}const o=e._zod.parse(r,a);if(o instanceof Promise){if(!1===a.async)throw new cn;return o.then(e=>t(e,s,a))}return t(o,s,a)}}_n(e,"~standard",()=>({validate:t=>{try{const n=Jn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Bn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Ws=on("$ZodString",(e,t)=>{var n;Bs.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Gs=on("$ZodStringFormat",(e,t)=>{Ms.init(e,t),Ws.init(e,t)}),Xs=on("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ds),Gs.init(e,t)}),Ys=on("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ls(e))}else t.pattern??(t.pattern=ls());Gs.init(e,t)}),Qs=on("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ps),Gs.init(e,t)}),er=on("$ZodURL",(e,t)=>{Gs.init(e,t),e._zod.check=n=>{try{const s=n.value.trim(),r=new URL(s);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=r.href:n.value=s)}catch(s){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),tr=on("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Gs.init(e,t)}),nr=on("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=cs),Gs.init(e,t)}),sr=on("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ss),Gs.init(e,t)}),rr=on("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=rs),Gs.init(e,t)}),ar=on("$ZodULID",(e,t)=>{t.pattern??(t.pattern=as),Gs.init(e,t)}),or=on("$ZodXID",(e,t)=>{t.pattern??(t.pattern=os),Gs.init(e,t)}),ir=on("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=is),Gs.init(e,t)}),cr=on("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=ks({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${n.join("|")})`;return new RegExp(`^${ws}T(?:${s})$`)}(t)),Gs.init(e,t)}),ur=on("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=bs),Gs.init(e,t)}),dr=on("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ks(t)}$`)),Gs.init(e,t)}),lr=on("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=us),Gs.init(e,t)}),pr=on("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=hs),Gs.init(e,t),e._zod.bag.format="ipv4"}),hr=on("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ms),Gs.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),mr=on("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=fs),Gs.init(e,t)}),fr=on("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=gs),Gs.init(e,t),e._zod.check=n=>{const s=n.value.split("/");try{if(2!==s.length)throw new Error;const[e,t]=s;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function gr(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const yr=on("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ys),Gs.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{gr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),_r=on("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_s),Gs.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!_s.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return gr(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),vr=on("$ZodE164",(e,t)=>{t.pattern??(t.pattern=vs),Gs.init(e,t)}),wr=on("$ZodJWT",(e,t)=>{Gs.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[s]=n;if(!s)return!1;const r=JSON.parse(atob(s));return!("typ"in r&&"JWT"!==r?.typ||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),br=on("$ZodNumber",(e,t)=>{Bs.init(e,t),e._zod.pattern=e._zod.bag.pattern??Es,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const r=n.value;if("number"==typeof r&&!Number.isNaN(r)&&Number.isFinite(r))return n;const a="number"==typeof r?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...a?{received:a}:{}}),n}}),kr=on("$ZodNumberFormat",(e,t)=>{js.init(e,t),br.init(e,t)}),$r=on("$ZodBoolean",(e,t)=>{Bs.init(e,t),e._zod.pattern=Ss,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const r=n.value;return"boolean"==typeof r||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Er=on("$ZodNull",(e,t)=>{Bs.init(e,t),e._zod.pattern=Ts,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const s=t.value;return null===s||t.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),t}}),Sr=on("$ZodUnknown",(e,t)=>{Bs.init(e,t),e._zod.parse=e=>e}),Tr=on("$ZodNever",(e,t)=>{Bs.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Or(e,t,n){e.issues.length&&t.issues.push(...Cn(n,e.issues)),t.value[n]=e.value}const xr=on("$ZodArray",(e,t)=>{Bs.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const a=[];for(let e=0;e<r.length;e++){const o=r[e],i=t.element._zod.run({value:o,issues:[]},s);i instanceof Promise?a.push(i.then(t=>Or(t,n,e))):Or(i,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Ir(e,t,n,s,r){if(e.issues.length){if(r&&!(n in s))return;t.issues.push(...Cn(n,e.issues))}void 0===e.value?n in s&&(t.value[n]=void 0):t.value[n]=e.value}function Nr(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(s=e.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Pr(e,t,n,s,r,a){const o=[],i=r.keySet,c=r.catchall._zod,u=c.def.type,d="optional"===c.optout;for(const r in t){if(i.has(r))continue;if("never"===u){o.push(r);continue}const a=c.run({value:t[r],issues:[]},s);a instanceof Promise?e.push(a.then(e=>Ir(e,n,r,t,d))):Ir(a,n,r,t,d)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Rr=on("$ZodObject",(e,t)=>{Bs.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const s=mn(()=>Nr(t));_n(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const r=$n,a=t.catchall;let o;e._zod.parse=(t,n)=>{o??(o=s.value);const i=t.value;if(!r(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value={};const c=[],u=o.shape;for(const e of o.keys){const s=u[e],r="optional"===s._zod.optout,a=s._zod.run({value:i[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>Ir(n,t,e,i,r))):Ir(a,t,e,i,r)}return a?Pr(c,i,t,n,s.value,e):c.length?Promise.all(c).then(()=>t):t}}),Cr=on("$ZodObjectJIT",(e,t)=>{Rr.init(e,t);const n=e._zod.parse,s=mn(()=>Nr(t));let r;const a=$n,o=!dn.jitless,i=o&&En.value,c=t.catchall;let u;e._zod.parse=(d,l)=>{u??(u=s.value);const p=d.value;return a(p)?o&&i&&!1===l?.async&&!0!==l.jitless?(r||(r=(e=>{const t=new Js(["shape","payload","ctx"]),n=s.value,r=e=>{const t=bn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const a=Object.create(null);let o=0;for(const e of n.keys)a[e]="key_"+o++;t.write("const newResult = {};");for(const s of n.keys){const n=a[s],o=bn(s),i=e[s],c="optional"===i?._zod?.optout;t.write(`const ${n} = ${r(s)};`),c?t.write(`\n if (${n}.issues.length) {\n if (${o} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n newResult[${o}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${o}, ...iss.path] : [${o}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${o} in input) {\n newResult[${o}] = undefined;\n }\n } else {\n newResult[${o}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,n)=>i(e,t,n)})(t.shape)),d=r(d,l),c?Pr([],p,d,l,u,e):d):n(d,l):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function jr(e,t,n,s){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const r=e.filter(e=>!Rn(e));return 1===r.length?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>zn(e,s,ln())))}),t)}const zr=on("$ZodUnion",(e,t)=>{Bs.init(e,t),_n(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),_n(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),_n(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),_n(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>gn(e.source)).join("|")})$`)}});const n=1===t.options.length,s=t.options[0]._zod.run;e._zod.parse=(r,a)=>{if(n)return s(r,a);let o=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},a);if(t instanceof Promise)i.push(t),o=!0;else{if(0===t.issues.length)return t;i.push(t)}}return o?Promise.all(i).then(t=>jr(t,r,e,a)):jr(i,r,e,a)}}),Ar=on("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zr.init(e,t);const n=e._zod.parse;_n(e._zod,"propValues",()=>{const e={};for(const n of t.options){const s=n._zod.propValues;if(!s||0===Object.keys(s).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(s)){e[t]||(e[t]=new Set);for(const s of n)e[t].add(s)}}return e});const s=mn(()=>{const e=t.options,n=new Map;for(const s of e){const e=s._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,s)}}return n});e._zod.parse=(r,a)=>{const o=r.value;if(!$n(o))return r.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),r;const i=s.value.get(o?.[t.discriminator]);return i?i._zod.run(r,a):t.unionFallback?n(r,a):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),r)}}),Dr=on("$ZodIntersection",(e,t)=>{Bs.init(e,t),e._zod.parse=(e,n)=>{const s=e.value,r=t.left._zod.run({value:s,issues:[]},n),a=t.right._zod.run({value:s,issues:[]},n);return r instanceof Promise||a instanceof Promise?Promise.all([r,a]).then(([t,n])=>Lr(e,t,n)):Lr(e,r,a)}});function Mr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Sn(e)&&Sn(t)){const n=Object.keys(t),s=Object.keys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of s){const s=Mr(e[n],t[n]);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r[n]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let s=0;s<e.length;s++){const r=Mr(e[s],t[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Lr(e,t,n){const s=new Map;let r;for(const n of t.issues)if("unrecognized_keys"===n.code){r??(r=n);for(const e of n.keys)s.has(e)||s.set(e,{}),s.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)s.has(e)||s.set(e,{}),s.get(e).r=!0;else e.issues.push(t);const a=[...s].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&r&&e.issues.push({...r,keys:a}),Rn(e))return e;const o=Mr(t.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const Zr=on("$ZodRecord",(e,t)=>{Bs.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Sn(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const a=[],o=t.keyType._zod.values;if(o){n.value={};const i=new Set;for(const e of o)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){i.add("number"==typeof e?e.toString():e);const o=t.valueType._zod.run({value:r[e],issues:[]},s);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Cn(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Cn(e,o.issues)),n.value[e]=o.value)}let c;for(const e in r)i.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(const o of Reflect.ownKeys(r)){if("__proto__"===o)continue;let i=t.keyType._zod.run({value:o,issues:[]},s);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof o&&Es.test(o)&&i.issues.length){const e=t.keyType._zod.run({value:Number(o),issues:[]},s);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(i=e)}if(i.issues.length){"loose"===t.mode?n.value[o]=r[o]:n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>zn(e,s,ln())),input:o,path:[o],inst:e});continue}const c=t.valueType._zod.run({value:r[o],issues:[]},s);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Cn(o,e.issues)),n.value[i.value]=e.value})):(c.issues.length&&n.issues.push(...Cn(o,c.issues)),n.value[i.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Fr=on("$ZodEnum",(e,t)=>{Bs.init(e,t);const n=pn(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(e=>On.has(typeof e)).map(e=>"string"==typeof e?xn(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const a=t.value;return s.has(a)||t.issues.push({code:"invalid_value",values:n,input:a,inst:e}),t}}),Ur=on("$ZodLiteral",(e,t)=>{if(Bs.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?xn(e):e?xn(e.toString()):String(e)).join("|")})$`),e._zod.parse=(s,r)=>{const a=s.value;return n.has(a)||s.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),s}}),qr=on("$ZodTransform",(e,t)=>{Bs.init(e,t),e._zod.parse=(n,s)=>{if("backward"===s.direction)throw new un(e.constructor.name);const r=t.transform(n.value,n);if(s.async)return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n));if(r instanceof Promise)throw new cn;return n.value=r,n}});function Hr(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Vr=on("$ZodOptional",(e,t)=>{Bs.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_n(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_n(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${gn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(t=>Hr(t,e.value)):Hr(s,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Jr=on("$ZodExactOptional",(e,t)=>{Vr.init(e,t),_n(e._zod,"values",()=>t.innerType._zod.values),_n(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Kr=on("$ZodNullable",(e,t)=>{Bs.init(e,t),_n(e._zod,"optin",()=>t.innerType._zod.optin),_n(e._zod,"optout",()=>t.innerType._zod.optout),_n(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${gn(e.source)}|null)$`):void 0}),_n(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Br=on("$ZodDefault",(e,t)=>{Bs.init(e,t),e._zod.optin="optional",_n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Wr(e,t)):Wr(s,t)}});function Wr(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Gr=on("$ZodPrefault",(e,t)=>{Bs.init(e,t),e._zod.optin="optional",_n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Xr=on("$ZodNonOptional",(e,t)=>{Bs.init(e,t),_n(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,s)=>{const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(t=>Yr(t,e)):Yr(r,e)}});function Yr(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Qr=on("$ZodCatch",(e,t)=>{Bs.init(e,t),_n(e._zod,"optin",()=>t.innerType._zod.optin),_n(e._zod,"optout",()=>t.innerType._zod.optout),_n(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>zn(e,n,ln()))},input:e.value}),e.issues=[]),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>zn(e,n,ln()))},input:e.value}),e.issues=[]),e)}}),ea=on("$ZodPipe",(e,t)=>{Bs.init(e,t),_n(e._zod,"values",()=>t.in._zod.values),_n(e._zod,"optin",()=>t.in._zod.optin),_n(e._zod,"optout",()=>t.out._zod.optout),_n(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const s=t.out._zod.run(e,n);return s instanceof Promise?s.then(e=>ta(e,t.in,n)):ta(s,t.in,n)}const s=t.in._zod.run(e,n);return s instanceof Promise?s.then(e=>ta(e,t.out,n)):ta(s,t.out,n)}});function ta(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const na=on("$ZodReadonly",(e,t)=>{Bs.init(e,t),_n(e._zod,"propValues",()=>t.innerType._zod.propValues),_n(e._zod,"values",()=>t.innerType._zod.values),_n(e._zod,"optin",()=>t.innerType?._zod?.optin),_n(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(sa):sa(s)}});function sa(e){return e.value=Object.freeze(e.value),e}const ra=on("$ZodCustom",(e,t)=>{Is.init(e,t),Bs.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const s=n.value,r=t.fn(s);if(r instanceof Promise)return r.then(t=>aa(t,n,s,e));aa(r,n,s,e)}});function aa(e,t,n,s){if(!e){const e={code:"custom",input:n,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(e.params=s._zod.def.params),t.issues.push(Dn(e))}}var oa;(oa=globalThis).__zod_globalRegistry??(oa.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const s={...n,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const ia=globalThis.__zod_globalRegistry;function ca(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Nn(t)})}function ua(e,t){return new Ps({check:"less_than",...Nn(t),value:e,inclusive:!1})}function da(e,t){return new Ps({check:"less_than",...Nn(t),value:e,inclusive:!0})}function la(e,t){return new Rs({check:"greater_than",...Nn(t),value:e,inclusive:!1})}function pa(e,t){return new Rs({check:"greater_than",...Nn(t),value:e,inclusive:!0})}function ha(e,t){return new Cs({check:"multiple_of",...Nn(t),value:e})}function ma(e,t){return new zs({check:"max_length",...Nn(t),maximum:e})}function fa(e,t){return new As({check:"min_length",...Nn(t),minimum:e})}function ga(e,t){return new Ds({check:"length_equals",...Nn(t),length:e})}function ya(e){return new Vs({check:"overwrite",tx:e})}function _a(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ia,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function va(e,t,n={path:[],schemaPath:[]}){var s;const r=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);const i=e._zod.toJSONSchema?.();if(i)o.schema=i;else{const s={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,s);else{const n=o.schema,a=t.processors[r.type];if(!a)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);a(e,t,n,s)}const a=e._zod.parent;a&&(o.ref||(o.ref=a),va(a,t,s),t.seen.get(a).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),"input"===t.io&&ka(e)&&(delete o.schema.examples,delete o.schema.default),"input"===t.io&&o.schema._prefault&&((s=o.schema).default??(s.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function wa(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=s.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(n,t[0])}}const r=t=>{if(t[1].schema.$ref)return;const s=t[1],{ref:r,defId:a}=(t=>{const s="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,r=e.external.uri??(e=>e);if(n)return{ref:r(n)};const a=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=a,{defId:a,ref:`${r("__shared")}#/${s}/${a}`}}if(t[1]===n)return{ref:"#"};const r=`#/${s}/`,a=t[1].schema.id??"__schema"+e.counter++;return{defId:a,ref:r+a}})(t);s.def={...s.schema},a&&(s.defId=a);const o=s.schema;for(const e in o)delete o[e];o.$ref=r};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const s=n[1];if(t===n[0]){r(n);continue}if(e.external){const s=e.external.registry.get(n[0])?.id;if(t!==n[0]&&s){r(n);continue}}const a=e.metadataRegistry.get(n[0])?.id;(a||s.cycle||s.count>1&&"ref"===e.reused)&&r(n)}}function ba(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=t=>{const n=e.seen.get(t);if(null===n.ref)return;const r=n.def??n.schema,a={...r},o=n.ref;if(n.ref=null,o){s(o);const n=e.seen.get(o),i=n.schema;if(!i.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(r,i):(r.allOf=r.allOf??[],r.allOf.push(i)),Object.assign(r,a),t._zod.parent===o)for(const e in r)"$ref"!==e&&"allOf"!==e&&(e in a||delete r[e]);if(i.$ref&&n.def)for(const e in r)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}const i=t._zod.parent;if(i&&i!==o){s(i);const t=e.seen.get(i);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(const e in r)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())s(t[0]);const r={};if("draft-2020-12"===e.target?r.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?r.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}Object.assign(r,n.def??n.schema);const a=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?r.$defs=a:r.definitions=a);try{const n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:$a(t,"input",e.processors),output:$a(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function ka(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if("transform"===s.type)return!0;if("array"===s.type)return ka(s.element,n);if("set"===s.type)return ka(s.valueType,n);if("lazy"===s.type)return ka(s.getter(),n);if("promise"===s.type||"optional"===s.type||"nonoptional"===s.type||"nullable"===s.type||"readonly"===s.type||"default"===s.type||"prefault"===s.type)return ka(s.innerType,n);if("intersection"===s.type)return ka(s.left,n)||ka(s.right,n);if("record"===s.type||"map"===s.type)return ka(s.keyType,n)||ka(s.valueType,n);if("pipe"===s.type)return ka(s.in,n)||ka(s.out,n);if("object"===s.type){for(const e in s.shape)if(ka(s.shape[e],n))return!0;return!1}if("union"===s.type){for(const e of s.options)if(ka(e,n))return!0;return!1}if("tuple"===s.type){for(const e of s.items)if(ka(e,n))return!0;return!(!s.rest||!ka(s.rest,n))}return!1}const $a=(e,t,n={})=>s=>{const{libraryOptions:r,target:a}=s??{},o=_a({...r??{},target:a,io:t,processors:n});return va(e,o),wa(o,e),ba(o,e)},Ea={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Sa=(e,t,n,s)=>{const r=n;r.type="string";const{minimum:a,maximum:o,format:i,patterns:c,contentEncoding:u}=e._zod.bag;if("number"==typeof a&&(r.minLength=a),"number"==typeof o&&(r.maxLength=o),i&&(r.format=Ea[i]??i,""===r.format&&delete r.format,"time"===i&&delete r.format),u&&(r.contentEncoding=u),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},Ta=(e,t,n,s)=>{const r=n,{minimum:a,maximum:o,format:i,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;"string"==typeof i&&i.includes("int")?r.type="integer":r.type="number","number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d),"number"==typeof a&&(r.minimum=a,"number"==typeof d&&"draft-04"!==t.target&&(d>=a?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u),"number"==typeof o&&(r.maximum=o,"number"==typeof u&&"draft-04"!==t.target&&(u<=o?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof c&&(r.multipleOf=c)},Oa=(e,t,n,s)=>{n.type="boolean"},xa=(e,t,n,s)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ia=(e,t,n,s)=>{n.not={}},Na=(e,t,n,s)=>{const r=pn(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r},Pa=(e,t,n,s)=>{const r=e._zod.def,a=[];for(const e of r.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(e))}else a.push(e);if(0===a.length);else if(1===a.length){const e=a[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else a.every(e=>"number"==typeof e)&&(n.type="number"),a.every(e=>"string"==typeof e)&&(n.type="string"),a.every(e=>"boolean"==typeof e)&&(n.type="boolean"),a.every(e=>null===e)&&(n.type="null"),n.enum=a},Ra=(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")},Ca=(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")},ja=(e,t,n,s)=>{const r=n,a=e._zod.def,{minimum:o,maximum:i}=e._zod.bag;"number"==typeof o&&(r.minItems=o),"number"==typeof i&&(r.maxItems=i),r.type="array",r.items=va(a.element,t,{...s,path:[...s.path,"items"]})},za=(e,t,n,s)=>{const r=n,a=e._zod.def;r.type="object",r.properties={};const o=a.shape;for(const e in o)r.properties[e]=va(o[e],t,{...s,path:[...s.path,"properties",e]});const i=new Set(Object.keys(o)),c=new Set([...i].filter(e=>{const n=a.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(r.required=Array.from(c)),"never"===a.catchall?._zod.def.type?r.additionalProperties=!1:a.catchall?a.catchall&&(r.additionalProperties=va(a.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)},Aa=(e,t,n,s)=>{const r=e._zod.def,a=!1===r.inclusive,o=r.options.map((e,n)=>va(e,t,{...s,path:[...s.path,a?"oneOf":"anyOf",n]}));a?n.oneOf=o:n.anyOf=o},Da=(e,t,n,s)=>{const r=e._zod.def,a=va(r.left,t,{...s,path:[...s.path,"allOf",0]}),o=va(r.right,t,{...s,path:[...s.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,c=[...i(a)?a.allOf:[a],...i(o)?o.allOf:[o]];n.allOf=c},Ma=(e,t,n,s)=>{const r=n,a=e._zod.def;r.type="object";const o=a.keyType,i=o._zod.bag,c=i?.patterns;if("loose"===a.mode&&c&&c.size>0){const e=va(a.valueType,t,{...s,path:[...s.path,"patternProperties","*"]});r.patternProperties={};for(const t of c)r.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(r.propertyNames=va(a.keyType,t,{...s,path:[...s.path,"propertyNames"]})),r.additionalProperties=va(a.valueType,t,{...s,path:[...s.path,"additionalProperties"]});const u=o._zod.values;if(u){const e=[...u].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}},La=(e,t,n,s)=>{const r=e._zod.def,a=va(r.innerType,t,s),o=t.seen.get(e);"openapi-3.0"===t.target?(o.ref=r.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},Za=(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType},Fa=(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},Ua=(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},qa=(e,t,n,s)=>{const r=e._zod.def;let a;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType;try{a=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Ha=(e,t,n,s)=>{const r=e._zod.def,a="input"===t.io?"transform"===r.in._zod.def.type?r.out:r.in:r.out;va(a,t,s),t.seen.get(e).ref=a},Va=(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType,n.readOnly=!0},Ja=(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType},Ka={string:Sa,number:Ta,boolean:Oa,bigint:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")},null:xa,undefined:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")},void:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")},never:Ia,any:(e,t,n,s)=>{},unknown:(e,t,n,s)=>{},date:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")},enum:Na,literal:Pa,nan:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,n,s)=>{const r=n,a=e._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=a.source},file:(e,t,n,s)=>{const r=n,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:i,mime:c}=e._zod.bag;void 0!==o&&(a.minLength=o),void 0!==i&&(a.maxLength=i),c?1===c.length?(a.contentMediaType=c[0],Object.assign(r,a)):(Object.assign(r,a),r.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(r,a)},success:(e,t,n,s)=>{n.type="boolean"},custom:Ra,function:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")},transform:Ca,map:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")},set:(e,t,n,s)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")},array:ja,object:za,union:Aa,intersection:Da,tuple:(e,t,n,s)=>{const r=n,a=e._zod.def;r.type="array";const o="draft-2020-12"===t.target?"prefixItems":"items",i="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=a.items.map((e,n)=>va(e,t,{...s,path:[...s.path,o,n]})),u=a.rest?va(a.rest,t,{...s,path:[...s.path,i,..."openapi-3.0"===t.target?[a.items.length]:[]]}):null;"draft-2020-12"===t.target?(r.prefixItems=c,u&&(r.items=u)):"openapi-3.0"===t.target?(r.items={anyOf:c},u&&r.items.anyOf.push(u),r.minItems=c.length,u||(r.maxItems=c.length)):(r.items=c,u&&(r.additionalItems=u));const{minimum:d,maximum:l}=e._zod.bag;"number"==typeof d&&(r.minItems=d),"number"==typeof l&&(r.maxItems=l)},record:Ma,nullable:La,nonoptional:Za,default:Fa,prefault:Ua,catch:qa,pipe:Ha,readonly:Va,promise:(e,t,n,s)=>{const r=e._zod.def;va(r.innerType,t,s),t.seen.get(e).ref=r.innerType},optional:Ja,lazy:(e,t,n,s)=>{const r=e._zod.innerType;va(r,t,s),t.seen.get(e).ref=r}},Ba=on("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Bs.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Un(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jn(e,t,n),e.parseAsync=async(t,n)=>Hn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Bn(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>In(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),Wa=on("ZodMiniObject",(e,t)=>{Rr.init(e,t),Ba.init(e,t),_n(e,"shape",()=>t.shape)});function Ga(e,t){const n={type:"object",shape:e??{},...Nn(t)};return new Wa(n)}function Xa(e){return!!e._zod}function Ya(e){const t=Object.values(e);if(0===t.length)return Ga({});const n=t.every(Xa),s=t.every(e=>!Xa(e));if(n)return Ga(e);if(s)return an(e);throw new Error("Mixed Zod versions detected in object shape.")}function Qa(e,t){return Xa(e)?Jn(e,t):e.safeParse(t)}async function eo(e,t){if(Xa(e))return await Bn(e,t);const n=e;return await n.safeParseAsync(t)}function to(e){if(!e)return;let t;if(Xa(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function no(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return Ya(e)}}if(Xa(e)){const t=e,n=t._zod?.def;if(n&&("object"===n.type||void 0!==n.shape))return e}else if(void 0!==e.shape)return e}}function so(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function ro(e){if(Xa(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;if(void 0!==n)return n}const ao=on("ZodISODateTime",(e,t)=>{cr.init(e,t),xo.init(e,t)});function oo(e){return function(e,t){return new ao({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Nn(t)})}(0,e)}const io=on("ZodISODate",(e,t)=>{ur.init(e,t),xo.init(e,t)});const co=on("ZodISOTime",(e,t)=>{dr.init(e,t),xo.init(e,t)});const uo=on("ZodISODuration",(e,t)=>{lr.init(e,t),xo.init(e,t)});const lo=on("ZodError",(e,t)=>{Ln.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},s=e=>{for(const r of e.issues)if("invalid_union"===r.code&&r.errors.length)r.errors.map(e=>s({issues:e}));else if("invalid_key"===r.code)s({issues:r.issues});else if("invalid_element"===r.code)s({issues:r.issues});else if(0===r.path.length)n._errors.push(t(r));else{let e=n,s=0;for(;s<r.path.length;){const n=r.path[s];s===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},s=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,hn,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,hn,2)}},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),po=Fn(lo),ho=qn(lo),mo=Vn(lo),fo=Kn(lo),go=Wn(lo),yo=Gn(lo),_o=Xn(lo),vo=Yn(lo),wo=Qn(lo),bo=es(lo),ko=ts(lo),$o=ns(lo),Eo=on("ZodType",(e,t)=>(Bs.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$a(e,"input"),output:$a(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const s=_a({...n,processors:t});return va(e,s),wa(s,e),ba(s,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(wn(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>In(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>po(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>mo(e,t,n),e.parseAsync=async(t,n)=>ho(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>fo(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>go(e,t,n),e.decode=(t,n)=>yo(e,t,n),e.encodeAsync=async(t,n)=>_o(e,t,n),e.decodeAsync=async(t,n)=>vo(e,t,n),e.safeEncode=(t,n)=>wo(e,t,n),e.safeDecode=(t,n)=>bo(e,t,n),e.safeEncodeAsync=async(t,n)=>ko(e,t,n),e.safeDecodeAsync=async(t,n)=>$o(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new Ai({type:"custom",check:"custom",fn:t,...Nn(n)})}(0,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new Is({check:"custom",...Nn(void 0)});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(Dn(e,n.value,t._zod.def));else{const s=e;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(Dn(s))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check(ya(t)),e.optional=()=>Si(e),e.exactOptional=()=>new Ti({type:"optional",innerType:e}),e.nullable=()=>xi(e),e.nullish=()=>Si(xi(e)),e.nonoptional=t=>function(e,t){return new Pi({type:"nonoptional",innerType:e,...Nn(t)})}(e,t),e.array=()=>oi(e),e.or=t=>li([e,t]),e.and=t=>fi(e,t),e.transform=t=>ji(e,$i(t)),e.default=t=>{return n=t,new Ii({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():Tn(n)}});var n},e.prefault=t=>{return n=t,new Ni({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():Tn(n)}});var n},e.catch=t=>{return new Ri({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>ji(e,t),e.readonly=()=>new zi({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return ia.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>ia.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return ia.get(e);const n=e.clone();return ia.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),So=on("_ZodString",(e,t)=>{Ws.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Sa(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Ls({check:"string_format",format:"regex",...Nn(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Us({check:"string_format",format:"includes",...Nn(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new qs({check:"string_format",format:"starts_with",...Nn(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Hs({check:"string_format",format:"ends_with",...Nn(t),suffix:e})}(...t)),e.min=(...t)=>e.check(fa(...t)),e.max=(...t)=>e.check(ma(...t)),e.length=(...t)=>e.check(ga(...t)),e.nonempty=(...t)=>e.check(fa(1,...t)),e.lowercase=t=>e.check(function(e){return new Zs({check:"string_format",format:"lowercase",...Nn(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Fs({check:"string_format",format:"uppercase",...Nn(e)})}(t)),e.trim=()=>e.check(ya(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return ya(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(ya(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(ya(e=>e.toUpperCase())),e.slugify=()=>e.check(ya(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),To=on("ZodString",(e,t)=>{Ws.init(e,t),So.init(e,t),e.email=t=>e.check(function(e,t){return new Io({type:"string",format:"email",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new Ro({type:"string",format:"url",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new Ko({type:"string",format:"jwt",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new Co({type:"string",format:"emoji",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.guid=t=>e.check(ca(No,t)),e.uuid=t=>e.check(function(e,t){return new Po({type:"string",format:"uuid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new Po({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Nn(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new Po({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Nn(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new Po({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Nn(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new jo({type:"string",format:"nanoid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.guid=t=>e.check(ca(No,t)),e.cuid=t=>e.check(function(e,t){return new zo({type:"string",format:"cuid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new Ao({type:"string",format:"cuid2",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new Do({type:"string",format:"ulid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new Ho({type:"string",format:"base64",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new Vo({type:"string",format:"base64url",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new Mo({type:"string",format:"xid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new Lo({type:"string",format:"ksuid",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Zo({type:"string",format:"ipv4",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Fo({type:"string",format:"ipv6",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Uo({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new qo({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new Jo({type:"string",format:"e164",check:"string_format",abort:!1,...Nn(t)})}(0,t)),e.datetime=t=>e.check(oo(t)),e.date=t=>e.check(function(e){return function(e,t){return new io({type:"string",format:"date",check:"string_format",...Nn(t)})}(0,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new co({type:"string",format:"time",check:"string_format",precision:null,...Nn(t)})}(0,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new uo({type:"string",format:"duration",check:"string_format",...Nn(t)})}(0,e)}(t))});function Oo(e){return function(e,t){return new To({type:"string",...Nn(t)})}(0,e)}const xo=on("ZodStringFormat",(e,t)=>{Gs.init(e,t),So.init(e,t)}),Io=on("ZodEmail",(e,t)=>{Qs.init(e,t),xo.init(e,t)}),No=on("ZodGUID",(e,t)=>{Xs.init(e,t),xo.init(e,t)}),Po=on("ZodUUID",(e,t)=>{Ys.init(e,t),xo.init(e,t)}),Ro=on("ZodURL",(e,t)=>{er.init(e,t),xo.init(e,t)}),Co=on("ZodEmoji",(e,t)=>{tr.init(e,t),xo.init(e,t)}),jo=on("ZodNanoID",(e,t)=>{nr.init(e,t),xo.init(e,t)}),zo=on("ZodCUID",(e,t)=>{sr.init(e,t),xo.init(e,t)}),Ao=on("ZodCUID2",(e,t)=>{rr.init(e,t),xo.init(e,t)}),Do=on("ZodULID",(e,t)=>{ar.init(e,t),xo.init(e,t)}),Mo=on("ZodXID",(e,t)=>{or.init(e,t),xo.init(e,t)}),Lo=on("ZodKSUID",(e,t)=>{ir.init(e,t),xo.init(e,t)}),Zo=on("ZodIPv4",(e,t)=>{pr.init(e,t),xo.init(e,t)}),Fo=on("ZodIPv6",(e,t)=>{hr.init(e,t),xo.init(e,t)}),Uo=on("ZodCIDRv4",(e,t)=>{mr.init(e,t),xo.init(e,t)}),qo=on("ZodCIDRv6",(e,t)=>{fr.init(e,t),xo.init(e,t)}),Ho=on("ZodBase64",(e,t)=>{yr.init(e,t),xo.init(e,t)}),Vo=on("ZodBase64URL",(e,t)=>{_r.init(e,t),xo.init(e,t)}),Jo=on("ZodE164",(e,t)=>{vr.init(e,t),xo.init(e,t)}),Ko=on("ZodJWT",(e,t)=>{wr.init(e,t),xo.init(e,t)}),Bo=on("ZodNumber",(e,t)=>{br.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ta(e,t,n),e.gt=(t,n)=>e.check(la(t,n)),e.gte=(t,n)=>e.check(pa(t,n)),e.min=(t,n)=>e.check(pa(t,n)),e.lt=(t,n)=>e.check(ua(t,n)),e.lte=(t,n)=>e.check(da(t,n)),e.max=(t,n)=>e.check(da(t,n)),e.int=t=>e.check(Xo(t)),e.safe=t=>e.check(Xo(t)),e.positive=t=>e.check(la(0,t)),e.nonnegative=t=>e.check(pa(0,t)),e.negative=t=>e.check(ua(0,t)),e.nonpositive=t=>e.check(da(0,t)),e.multipleOf=(t,n)=>e.check(ha(t,n)),e.step=(t,n)=>e.check(ha(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Wo(e){return function(e,t){return new Bo({type:"number",checks:[],...Nn(t)})}(0,e)}const Go=on("ZodNumberFormat",(e,t)=>{kr.init(e,t),Bo.init(e,t)});function Xo(e){return function(e,t){return new Go({type:"number",check:"number_format",abort:!1,format:"safeint",...Nn(t)})}(0,e)}const Yo=on("ZodBoolean",(e,t)=>{$r.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Oa(0,0,t)});function Qo(e){return function(e,t){return new Yo({type:"boolean",...Nn(t)})}(0,e)}const ei=on("ZodNull",(e,t)=>{Er.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>xa(0,e,t)});function ti(e){return function(e,t){return new ei({type:"null",...Nn(t)})}(0,e)}const ni=on("ZodUnknown",(e,t)=>{Sr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function si(){return new ni({type:"unknown"})}const ri=on("ZodNever",(e,t)=>{Tr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ia(0,0,t)});const ai=on("ZodArray",(e,t)=>{xr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>ja(e,t,n,s),e.element=t.element,e.min=(t,n)=>e.check(fa(t,n)),e.nonempty=t=>e.check(fa(1,t)),e.max=(t,n)=>e.check(ma(t,n)),e.length=(t,n)=>e.check(ga(t,n)),e.unwrap=()=>e.element});function oi(e,t){return function(e,t,n){return new ai({type:"array",element:t,...Nn(n)})}(0,e,t)}const ii=on("ZodObject",(e,t)=>{Cr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>za(e,t,n,s),_n(e,"shape",()=>t.shape),e.keyof=()=>vi(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:si()}),e.loose=()=>e.clone({...e._zod.def,catchall:si()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new ri({type:"never",...Nn(t)})}(0,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Sn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const s=wn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return vn(this,"shape",n),n}});return In(e,s)}(e,t),e.safeExtend=t=>function(e,t){if(!Sn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=wn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return vn(this,"shape",n),n}});return In(e,n)}(e,t),e.merge=t=>function(e,t){const n=wn(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return vn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return In(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return In(e,wn(e._zod.def,{get shape(){const e={};for(const s in t){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(e[s]=n.shape[s])}return vn(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=wn(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete s[e]}return vn(this,"shape",s),s},checks:[]});return In(e,r)}(e,t),e.partial=(...t)=>function(e,t,n){const s=t._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=wn(t._zod.def,{get shape(){const s=t._zod.def.shape,r={...s};if(n)for(const t in n){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=e?new e({type:"optional",innerType:s[t]}):s[t])}else for(const t in s)r[t]=e?new e({type:"optional",innerType:s[t]}):s[t];return vn(this,"shape",r),r},checks:[]});return In(t,r)}(Ei,e,t[0]),e.required=(...t)=>function(e,t,n){const s=wn(t._zod.def,{get shape(){const s=t._zod.def.shape,r={...s};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=new e({type:"nonoptional",innerType:s[t]}))}else for(const t in s)r[t]=new e({type:"nonoptional",innerType:s[t]});return vn(this,"shape",r),r}});return In(t,s)}(Pi,e,t[0])});function ci(e,t){const n={type:"object",shape:e??{},...Nn(t)};return new ii(n)}function ui(e,t){return new ii({type:"object",shape:e,catchall:si(),...Nn(t)})}const di=on("ZodUnion",(e,t)=>{zr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Aa(e,t,n,s),e.options=t.options});function li(e,t){return new di({type:"union",options:e,...Nn(t)})}const pi=on("ZodDiscriminatedUnion",(e,t)=>{di.init(e,t),Ar.init(e,t)});function hi(e,t,n){return new pi({type:"union",options:t,discriminator:e,...Nn(n)})}const mi=on("ZodIntersection",(e,t)=>{Dr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Da(e,t,n,s)});function fi(e,t){return new mi({type:"intersection",left:e,right:t})}const gi=on("ZodRecord",(e,t)=>{Zr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ma(e,t,n,s),e.keyType=t.keyType,e.valueType=t.valueType});function yi(e,t,n){return new gi({type:"record",keyType:e,valueType:t,...Nn(n)})}const _i=on("ZodEnum",(e,t)=>{Fr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Na(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,s)=>{const r={};for(const s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);r[s]=t.entries[s]}return new _i({...t,checks:[],...Nn(s),entries:r})},e.exclude=(e,s)=>{const r={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete r[t]}return new _i({...t,checks:[],...Nn(s),entries:r})}});function vi(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new _i({type:"enum",entries:n,...Nn(t)})}const wi=on("ZodLiteral",(e,t)=>{Ur.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Pa(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function bi(e,t){return new wi({type:"literal",values:Array.isArray(e)?e:[e],...Nn(t)})}const ki=on("ZodTransform",(e,t)=>{qr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ca(0,e),e._zod.parse=(n,s)=>{if("backward"===s.direction)throw new un(e.constructor.name);n.addIssue=s=>{if("string"==typeof s)n.issues.push(Dn(s,n.value,t));else{const t=s;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Dn(t))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(e=>(n.value=e,n)):(n.value=r,n)}});function $i(e){return new ki({type:"transform",transform:e})}const Ei=on("ZodOptional",(e,t)=>{Vr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ja(e,t,0,s),e.unwrap=()=>e._zod.def.innerType});function Si(e){return new Ei({type:"optional",innerType:e})}const Ti=on("ZodExactOptional",(e,t)=>{Jr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ja(e,t,0,s),e.unwrap=()=>e._zod.def.innerType}),Oi=on("ZodNullable",(e,t)=>{Kr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>La(e,t,n,s),e.unwrap=()=>e._zod.def.innerType});function xi(e){return new Oi({type:"nullable",innerType:e})}const Ii=on("ZodDefault",(e,t)=>{Br.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Fa(e,t,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Ni=on("ZodPrefault",(e,t)=>{Gr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ua(e,t,n,s),e.unwrap=()=>e._zod.def.innerType}),Pi=on("ZodNonOptional",(e,t)=>{Xr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Za(e,t,0,s),e.unwrap=()=>e._zod.def.innerType}),Ri=on("ZodCatch",(e,t)=>{Qr.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>qa(e,t,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Ci=on("ZodPipe",(e,t)=>{ea.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Ha(e,t,0,s),e.in=t.in,e.out=t.out});function ji(e,t){return new Ci({type:"pipe",in:e,out:t})}const zi=on("ZodReadonly",(e,t)=>{na.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(t,n,s)=>Va(e,t,n,s),e.unwrap=()=>e._zod.def.innerType}),Ai=on("ZodCustom",(e,t)=>{ra.init(e,t),Eo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>Ra(0,e)});function Di(e,t){return ji($i(e),t)}const Mi="2025-11-25",Li=[Mi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zi="io.modelcontextprotocol/related-task",Fi="2.0",Ui=function(e,t,n){const s=Nn(n);return s.abort??(s.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...s})}(Ai,0,void 0);const qi=li([Oo(),Wo().int()]),Hi=Oo();ui({ttl:li([Wo(),ti()]).optional(),pollInterval:Wo().optional()});const Vi=ci({ttl:Wo().optional()}),Ji=ci({taskId:Oo()}),Ki=ui({progressToken:qi.optional(),[Zi]:Ji.optional()}),Bi=ci({_meta:Ki.optional()}),Wi=Bi.extend({task:Vi.optional()}),Gi=ci({method:Oo(),params:Bi.loose().optional()}),Xi=ci({_meta:Ki.optional()}),Yi=ci({method:Oo(),params:Xi.loose().optional()}),Qi=ui({_meta:Ki.optional()}),ec=li([Oo(),Wo().int()]),tc=ci({jsonrpc:bi(Fi),id:ec,...Gi.shape}).strict(),nc=e=>tc.safeParse(e).success,sc=ci({jsonrpc:bi(Fi),...Yi.shape}).strict(),rc=ci({jsonrpc:bi(Fi),id:ec,result:Qi}).strict(),ac=e=>rc.safeParse(e).success;var oc;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(oc||(oc={}));const ic=ci({jsonrpc:bi(Fi),id:ec.optional(),error:ci({code:Wo().int(),message:Oo(),data:si().optional()})}).strict(),cc=li([tc,sc,rc,ic]);li([rc,ic]);const uc=Qi.strict(),dc=Xi.extend({requestId:ec.optional(),reason:Oo().optional()}),lc=Yi.extend({method:bi("notifications/cancelled"),params:dc}),pc=ci({src:Oo(),mimeType:Oo().optional(),sizes:oi(Oo()).optional(),theme:vi(["light","dark"]).optional()}),hc=ci({icons:oi(pc).optional()}),mc=ci({name:Oo(),title:Oo().optional()}),fc=mc.extend({...mc.shape,...hc.shape,version:Oo(),websiteUrl:Oo().optional(),description:Oo().optional()}),gc=fi(ci({applyDefaults:Qo().optional()}),yi(Oo(),si())),yc=Di(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,fi(ci({form:gc.optional(),url:Ui.optional()}),yi(Oo(),si()).optional())),_c=ui({list:Ui.optional(),cancel:Ui.optional(),requests:ui({sampling:ui({createMessage:Ui.optional()}).optional(),elicitation:ui({create:Ui.optional()}).optional()}).optional()}),vc=ui({list:Ui.optional(),cancel:Ui.optional(),requests:ui({tools:ui({call:Ui.optional()}).optional()}).optional()}),wc=ci({experimental:yi(Oo(),Ui).optional(),sampling:ci({context:Ui.optional(),tools:Ui.optional()}).optional(),elicitation:yc.optional(),roots:ci({listChanged:Qo().optional()}).optional(),tasks:_c.optional()}),bc=Bi.extend({protocolVersion:Oo(),capabilities:wc,clientInfo:fc}),kc=Gi.extend({method:bi("initialize"),params:bc}),$c=ci({experimental:yi(Oo(),Ui).optional(),logging:Ui.optional(),completions:Ui.optional(),prompts:ci({listChanged:Qo().optional()}).optional(),resources:ci({subscribe:Qo().optional(),listChanged:Qo().optional()}).optional(),tools:ci({listChanged:Qo().optional()}).optional(),tasks:vc.optional()}),Ec=Qi.extend({protocolVersion:Oo(),capabilities:$c,serverInfo:fc,instructions:Oo().optional()}),Sc=Yi.extend({method:bi("notifications/initialized"),params:Xi.optional()}),Tc=Gi.extend({method:bi("ping"),params:Bi.optional()}),Oc=ci({progress:Wo(),total:Si(Wo()),message:Si(Oo())}),xc=ci({...Xi.shape,...Oc.shape,progressToken:qi}),Ic=Yi.extend({method:bi("notifications/progress"),params:xc}),Nc=Bi.extend({cursor:Hi.optional()}),Pc=Gi.extend({params:Nc.optional()}),Rc=Qi.extend({nextCursor:Hi.optional()}),Cc=vi(["working","input_required","completed","failed","cancelled"]),jc=ci({taskId:Oo(),status:Cc,ttl:li([Wo(),ti()]),createdAt:Oo(),lastUpdatedAt:Oo(),pollInterval:Si(Wo()),statusMessage:Si(Oo())}),zc=Qi.extend({task:jc}),Ac=Xi.merge(jc),Dc=Yi.extend({method:bi("notifications/tasks/status"),params:Ac}),Mc=Gi.extend({method:bi("tasks/get"),params:Bi.extend({taskId:Oo()})}),Lc=Qi.merge(jc),Zc=Gi.extend({method:bi("tasks/result"),params:Bi.extend({taskId:Oo()})});Qi.loose();const Fc=Pc.extend({method:bi("tasks/list")}),Uc=Rc.extend({tasks:oi(jc)}),qc=Gi.extend({method:bi("tasks/cancel"),params:Bi.extend({taskId:Oo()})}),Hc=Qi.merge(jc),Vc=ci({uri:Oo(),mimeType:Si(Oo()),_meta:yi(Oo(),si()).optional()}),Jc=Vc.extend({text:Oo()}),Kc=Oo().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Bc=Vc.extend({blob:Kc}),Wc=vi(["user","assistant"]),Gc=ci({audience:oi(Wc).optional(),priority:Wo().min(0).max(1).optional(),lastModified:oo({offset:!0}).optional()}),Xc=ci({...mc.shape,...hc.shape,uri:Oo(),description:Si(Oo()),mimeType:Si(Oo()),annotations:Gc.optional(),_meta:Si(ui({}))}),Yc=ci({...mc.shape,...hc.shape,uriTemplate:Oo(),description:Si(Oo()),mimeType:Si(Oo()),annotations:Gc.optional(),_meta:Si(ui({}))}),Qc=Pc.extend({method:bi("resources/list")}),eu=Rc.extend({resources:oi(Xc)}),tu=Pc.extend({method:bi("resources/templates/list")}),nu=Rc.extend({resourceTemplates:oi(Yc)}),su=Bi.extend({uri:Oo()}),ru=su,au=Gi.extend({method:bi("resources/read"),params:ru}),ou=Qi.extend({contents:oi(li([Jc,Bc]))}),iu=Yi.extend({method:bi("notifications/resources/list_changed"),params:Xi.optional()}),cu=su,uu=Gi.extend({method:bi("resources/subscribe"),params:cu}),du=su,lu=Gi.extend({method:bi("resources/unsubscribe"),params:du}),pu=Xi.extend({uri:Oo()}),hu=Yi.extend({method:bi("notifications/resources/updated"),params:pu}),mu=ci({name:Oo(),description:Si(Oo()),required:Si(Qo())}),fu=ci({...mc.shape,...hc.shape,description:Si(Oo()),arguments:Si(oi(mu)),_meta:Si(ui({}))}),gu=Pc.extend({method:bi("prompts/list")}),yu=Rc.extend({prompts:oi(fu)}),_u=Bi.extend({name:Oo(),arguments:yi(Oo(),Oo()).optional()}),vu=Gi.extend({method:bi("prompts/get"),params:_u}),wu=ci({type:bi("text"),text:Oo(),annotations:Gc.optional(),_meta:yi(Oo(),si()).optional()}),bu=ci({type:bi("image"),data:Kc,mimeType:Oo(),annotations:Gc.optional(),_meta:yi(Oo(),si()).optional()}),ku=ci({type:bi("audio"),data:Kc,mimeType:Oo(),annotations:Gc.optional(),_meta:yi(Oo(),si()).optional()}),$u=ci({type:bi("tool_use"),name:Oo(),id:Oo(),input:yi(Oo(),si()),_meta:yi(Oo(),si()).optional()}),Eu=ci({type:bi("resource"),resource:li([Jc,Bc]),annotations:Gc.optional(),_meta:yi(Oo(),si()).optional()}),Su=li([wu,bu,ku,Xc.extend({type:bi("resource_link")}),Eu]),Tu=ci({role:Wc,content:Su}),Ou=Qi.extend({description:Oo().optional(),messages:oi(Tu)}),xu=Yi.extend({method:bi("notifications/prompts/list_changed"),params:Xi.optional()}),Iu=ci({title:Oo().optional(),readOnlyHint:Qo().optional(),destructiveHint:Qo().optional(),idempotentHint:Qo().optional(),openWorldHint:Qo().optional()}),Nu=ci({taskSupport:vi(["required","optional","forbidden"]).optional()}),Pu=ci({...mc.shape,...hc.shape,description:Oo().optional(),inputSchema:ci({type:bi("object"),properties:yi(Oo(),Ui).optional(),required:oi(Oo()).optional()}).catchall(si()),outputSchema:ci({type:bi("object"),properties:yi(Oo(),Ui).optional(),required:oi(Oo()).optional()}).catchall(si()).optional(),annotations:Iu.optional(),execution:Nu.optional(),_meta:yi(Oo(),si()).optional()}),Ru=Pc.extend({method:bi("tools/list")}),Cu=Rc.extend({tools:oi(Pu)}),ju=Qi.extend({content:oi(Su).default([]),structuredContent:yi(Oo(),si()).optional(),isError:Qo().optional()});ju.or(Qi.extend({toolResult:si()}));const zu=Wi.extend({name:Oo(),arguments:yi(Oo(),si()).optional()}),Au=Gi.extend({method:bi("tools/call"),params:zu}),Du=Yi.extend({method:bi("notifications/tools/list_changed"),params:Xi.optional()});ci({autoRefresh:Qo().default(!0),debounceMs:Wo().int().nonnegative().default(300)});const Mu=vi(["debug","info","notice","warning","error","critical","alert","emergency"]),Lu=Bi.extend({level:Mu}),Zu=Gi.extend({method:bi("logging/setLevel"),params:Lu}),Fu=Xi.extend({level:Mu,logger:Oo().optional(),data:si()}),Uu=Yi.extend({method:bi("notifications/message"),params:Fu}),qu=ci({name:Oo().optional()}),Hu=ci({hints:oi(qu).optional(),costPriority:Wo().min(0).max(1).optional(),speedPriority:Wo().min(0).max(1).optional(),intelligencePriority:Wo().min(0).max(1).optional()}),Vu=ci({mode:vi(["auto","required","none"]).optional()}),Ju=ci({type:bi("tool_result"),toolUseId:Oo().describe("The unique identifier for the corresponding tool call."),content:oi(Su).default([]),structuredContent:ci({}).loose().optional(),isError:Qo().optional(),_meta:yi(Oo(),si()).optional()}),Ku=hi("type",[wu,bu,ku]),Bu=hi("type",[wu,bu,ku,$u,Ju]),Wu=ci({role:Wc,content:li([Bu,oi(Bu)]),_meta:yi(Oo(),si()).optional()}),Gu=Wi.extend({messages:oi(Wu),modelPreferences:Hu.optional(),systemPrompt:Oo().optional(),includeContext:vi(["none","thisServer","allServers"]).optional(),temperature:Wo().optional(),maxTokens:Wo().int(),stopSequences:oi(Oo()).optional(),metadata:Ui.optional(),tools:oi(Pu).optional(),toolChoice:Vu.optional()}),Xu=Gi.extend({method:bi("sampling/createMessage"),params:Gu}),Yu=Qi.extend({model:Oo(),stopReason:Si(vi(["endTurn","stopSequence","maxTokens"]).or(Oo())),role:Wc,content:Ku}),Qu=Qi.extend({model:Oo(),stopReason:Si(vi(["endTurn","stopSequence","maxTokens","toolUse"]).or(Oo())),role:Wc,content:li([Bu,oi(Bu)])}),ed=ci({type:bi("boolean"),title:Oo().optional(),description:Oo().optional(),default:Qo().optional()}),td=ci({type:bi("string"),title:Oo().optional(),description:Oo().optional(),minLength:Wo().optional(),maxLength:Wo().optional(),format:vi(["email","uri","date","date-time"]).optional(),default:Oo().optional()}),nd=ci({type:vi(["number","integer"]),title:Oo().optional(),description:Oo().optional(),minimum:Wo().optional(),maximum:Wo().optional(),default:Wo().optional()}),sd=ci({type:bi("string"),title:Oo().optional(),description:Oo().optional(),enum:oi(Oo()),default:Oo().optional()}),rd=ci({type:bi("string"),title:Oo().optional(),description:Oo().optional(),oneOf:oi(ci({const:Oo(),title:Oo()})),default:Oo().optional()}),ad=ci({type:bi("string"),title:Oo().optional(),description:Oo().optional(),enum:oi(Oo()),enumNames:oi(Oo()).optional(),default:Oo().optional()}),od=li([sd,rd]),id=li([ci({type:bi("array"),title:Oo().optional(),description:Oo().optional(),minItems:Wo().optional(),maxItems:Wo().optional(),items:ci({type:bi("string"),enum:oi(Oo())}),default:oi(Oo()).optional()}),ci({type:bi("array"),title:Oo().optional(),description:Oo().optional(),minItems:Wo().optional(),maxItems:Wo().optional(),items:ci({anyOf:oi(ci({const:Oo(),title:Oo()}))}),default:oi(Oo()).optional()})]),cd=li([ad,od,id]),ud=li([cd,ed,td,nd]),dd=li([Wi.extend({mode:bi("form").optional(),message:Oo(),requestedSchema:ci({type:bi("object"),properties:yi(Oo(),ud),required:oi(Oo()).optional()})}),Wi.extend({mode:bi("url"),message:Oo(),elicitationId:Oo(),url:Oo().url()})]),ld=Gi.extend({method:bi("elicitation/create"),params:dd}),pd=Xi.extend({elicitationId:Oo()}),hd=Yi.extend({method:bi("notifications/elicitation/complete"),params:pd}),md=Qi.extend({action:vi(["accept","decline","cancel"]),content:Di(e=>null===e?void 0:e,yi(Oo(),li([Oo(),Wo(),Qo(),oi(Oo())])).optional())}),fd=ci({type:bi("ref/resource"),uri:Oo()}),gd=ci({type:bi("ref/prompt"),name:Oo()}),yd=Bi.extend({ref:li([gd,fd]),argument:ci({name:Oo(),value:Oo()}),context:ci({arguments:yi(Oo(),Oo()).optional()}).optional()}),_d=Gi.extend({method:bi("completion/complete"),params:yd}),vd=Qi.extend({completion:ui({values:oi(Oo()).max(100),total:Si(Wo().int()),hasMore:Si(Qo())})}),wd=ci({uri:Oo().startsWith("file://"),name:Oo().optional(),_meta:yi(Oo(),si()).optional()}),bd=Gi.extend({method:bi("roots/list"),params:Bi.optional()}),kd=Qi.extend({roots:oi(wd)}),$d=Yi.extend({method:bi("notifications/roots/list_changed"),params:Xi.optional()});li([Tc,kc,_d,Zu,vu,gu,Qc,tu,au,uu,lu,Au,Ru,Mc,Zc,Fc,qc]),li([lc,Ic,Sc,$d,Dc]),li([uc,Yu,Qu,md,kd,Lc,Uc,zc]),li([Tc,Xu,ld,bd,Mc,Zc,Fc,qc]),li([lc,Ic,Uu,hu,iu,Du,xu,Dc,hd]),li([uc,Ec,vd,Ou,yu,eu,nu,ou,ju,Cu,Lc,Uc,zc]);class Ed extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===oc.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new Sd(e.elicitations,t)}return new Ed(e,t,n)}}class Sd extends Ed{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(oc.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Td(e){return"completed"===e||"failed"===e||"cancelled"===e}const Od=Symbol("Let zodToJsonSchema decide on which parser to use"),xd={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"};function Id(e,t,n,s){s?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Nd(e,t,n,s,r){e[t]=n,Id(e,t,s,r)}const Pd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function Rd(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?Pd(t,e.currentPath):t.join("/")}}function Cd(e,t){return al(e.type._def,t)}function jd(e,t,n){const s=n??t.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((n,s)=>jd(e,t,n))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zd(e,t)}}const zd=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const s of e.checks)switch(s.kind){case"min":Nd(n,"minimum",s.value,s.message,t);break;case"max":Nd(n,"maximum",s.value,s.message,t)}return n};let Ad;const Dd=/^[cC][^\s-]{8,}$/,Md=/^[0-9a-z]+$/,Ld=/^[0-9A-HJKMNP-TV-Z]{26}$/,Zd=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Fd=()=>(void 0===Ad&&(Ad=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ad),Ud=/^(?:(?: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])$/,qd=/^(([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])$/,Hd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Jd=/^[a-zA-Z0-9_-]{21}$/,Kd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Bd(e,t){const n={type:"string"};if(e.checks)for(const s of e.checks)switch(s.kind){case"min":Nd(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,s.value):s.value,s.message,t);break;case"max":Nd(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,s.value):s.value,s.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Xd(n,"email",s.message,t);break;case"format:idn-email":Xd(n,"idn-email",s.message,t);break;case"pattern:zod":Yd(n,Zd,s.message,t)}break;case"url":Xd(n,"uri",s.message,t);break;case"uuid":Xd(n,"uuid",s.message,t);break;case"regex":Yd(n,s.regex,s.message,t);break;case"cuid":Yd(n,Dd,s.message,t);break;case"cuid2":Yd(n,Md,s.message,t);break;case"startsWith":Yd(n,RegExp(`^${Wd(s.value,t)}`),s.message,t);break;case"endsWith":Yd(n,RegExp(`${Wd(s.value,t)}$`),s.message,t);break;case"datetime":Xd(n,"date-time",s.message,t);break;case"date":Xd(n,"date",s.message,t);break;case"time":Xd(n,"time",s.message,t);break;case"duration":Xd(n,"duration",s.message,t);break;case"length":Nd(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,s.value):s.value,s.message,t),Nd(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,s.value):s.value,s.message,t);break;case"includes":Yd(n,RegExp(Wd(s.value,t)),s.message,t);break;case"ip":"v6"!==s.version&&Xd(n,"ipv4",s.message,t),"v4"!==s.version&&Xd(n,"ipv6",s.message,t);break;case"base64url":Yd(n,Vd,s.message,t);break;case"jwt":Yd(n,Kd,s.message,t);break;case"cidr":"v6"!==s.version&&Yd(n,Ud,s.message,t),"v4"!==s.version&&Yd(n,qd,s.message,t);break;case"emoji":Yd(n,Fd(),s.message,t);break;case"ulid":Yd(n,Ld,s.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Xd(n,"binary",s.message,t);break;case"contentEncoding:base64":Nd(n,"contentEncoding","base64",s.message,t);break;case"pattern:zod":Yd(n,Hd,s.message,t)}break;case"nanoid":Yd(n,Jd,s.message,t)}return n}function Wd(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)Gd.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const Gd=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Xd(e,t,n,s){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&s.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&s.errorMessages&&{errorMessage:{format:n}}})):Nd(e,"format",t,n,s)}function Yd(e,t,n,s){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&s.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Qd(t,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):Nd(e,"pattern",Qd(t,s),n,s)}function Qd(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),s=e.flags.includes("m"),r=e.flags.includes("s"),a=n?e.source.toLowerCase():e.source;let o="",i=!1,c=!1,u=!1;for(let e=0;e<a.length;e++)if(i)o+=a[e],i=!1;else{if(n)if(c){if(a[e].match(/[a-z]/)){u?(o+=a[e],o+=`${a[e-2]}-${a[e]}`.toUpperCase(),u=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(o+=a[e],u=!0):o+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){o+=`[${a[e]}${a[e].toUpperCase()}]`;continue}if(s){if("^"===a[e]){o+="(^|(?<=[\r\n]))";continue}if("$"===a[e]){o+="($|(?=[\r\n]))";continue}}r&&"."===a[e]?o+=c?`${a[e]}\r\n`:`[${a[e]}\r\n]`:(o+=a[e],"\\"===a[e]?i=!0:c&&"]"===a[e]?c=!1:c||"["!==a[e]||(c=!0))}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function el(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===rn.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,s)=>({...n,[s]:al(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??Rd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:al(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===rn.ZodString&&e.keyType._def.checks?.length){const{type:s,...r}=Bd(e.keyType._def,t);return{...n,propertyNames:r}}if(e.keyType?._def.typeName===rn.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===rn.ZodBranded&&e.keyType._def.type._def.typeName===rn.ZodString&&e.keyType._def.type._def.checks?.length){const{type:s,...r}=Cd(e.keyType._def,t);return{...n,propertyNames:r}}return n}const tl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},nl=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>al(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function sl(e){try{return e.isOptional()}catch{return!0}}const rl=(e,t,n)=>{switch(t){case rn.ZodString:return Bd(e,n);case rn.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const s of e.checks)switch(s.kind){case"int":n.type="integer",Id(n,"type",s.message,t);break;case"min":"jsonSchema7"===t.target?s.inclusive?Nd(n,"minimum",s.value,s.message,t):Nd(n,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(n.exclusiveMinimum=!0),Nd(n,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?Nd(n,"maximum",s.value,s.message,t):Nd(n,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(n.exclusiveMaximum=!0),Nd(n,"maximum",s.value,s.message,t));break;case"multipleOf":Nd(n,"multipleOf",s.value,s.message,t)}return n}(e,n);case rn.ZodObject:return function(e,t){const n="openAi"===t.target,s={type:"object",properties:{}},r=[],a=e.shape();for(const e in a){let o=a[e];if(void 0===o||void 0===o._def)continue;let i=sl(o);i&&n&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),i=!1);const c=al(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(s.properties[e]=c,i||r.push(e))}r.length&&(s.required=r);const o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return al(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(s.additionalProperties=o),s}(e,n);case rn.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const s of e.checks)switch(s.kind){case"min":"jsonSchema7"===t.target?s.inclusive?Nd(n,"minimum",s.value,s.message,t):Nd(n,"exclusiveMinimum",s.value,s.message,t):(s.inclusive||(n.exclusiveMinimum=!0),Nd(n,"minimum",s.value,s.message,t));break;case"max":"jsonSchema7"===t.target?s.inclusive?Nd(n,"maximum",s.value,s.message,t):Nd(n,"exclusiveMaximum",s.value,s.message,t):(s.inclusive||(n.exclusiveMaximum=!0),Nd(n,"maximum",s.value,s.message,t));break;case"multipleOf":Nd(n,"multipleOf",s.value,s.message,t)}return n}(e,n);case rn.ZodBoolean:return{type:"boolean"};case rn.ZodDate:return jd(e,n);case rn.ZodUndefined:return function(e){return{not:Rd(e)}}(n);case rn.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case rn.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==rn.ZodAny&&(n.items=al(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Nd(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Nd(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Nd(n,"minItems",e.exactLength.value,e.exactLength.message,t),Nd(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case rn.ZodUnion:case rn.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return nl(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in tl&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=tl[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return nl(e,t)}(e,n);case rn.ZodIntersection:return function(e,t){const n=[al(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),al(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let s="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...s}=e;t=s}else s=void 0;r.push(t)}else r.push(...e.allOf),void 0===e.unevaluatedProperties&&(s=void 0);var t}),r.length?{allOf:r,...s}:void 0}(e,n);case rn.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>al(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:al(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>al(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case rn.ZodRecord:return el(e,n);case rn.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case rn.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case rn.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),s=Array.from(new Set(n.map(e=>typeof e)));return{type:1===s.length?"string"===s[0]?"string":"number":["string","number"],enum:n}}(e);case rn.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:tl[e.innerType._def.typeName],nullable:!0}:{type:[tl[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=al(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=al(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case rn.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return al(e.innerType._def,t);const n=al(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Rd(t)},n]}:Rd(t)})(e,n);case rn.ZodMap:return function(e,t){return"record"===t.mapStrategy?el(e,t):{type:"array",maxItems:125,items:{type:"array",items:[al(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Rd(t),al(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Rd(t)],minItems:2,maxItems:2}}}(e,n);case rn.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:al(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Nd(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Nd(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case rn.ZodLazy:return()=>e.getter()._def;case rn.ZodPromise:return function(e,t){return al(e.type._def,t)}(e,n);case rn.ZodNaN:case rn.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Rd({...e,currentPath:[...e.currentPath,"not"]})}}(n);case rn.ZodEffects:return function(e,t){return"input"===t.effectStrategy?al(e.schema._def,t):Rd(t)}(e,n);case rn.ZodAny:return Rd(n);case rn.ZodUnknown:return function(e){return Rd(e)}(n);case rn.ZodDefault:return function(e,t){return{...al(e.innerType._def,t),default:e.defaultValue()}}(e,n);case rn.ZodBranded:return Cd(e,n);case rn.ZodReadonly:case rn.ZodCatch:return((e,t)=>al(e.innerType._def,t))(e,n);case rn.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return al(e.in._def,t);if("output"===t.pipeStrategy)return al(e.out._def,t);const n=al(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,al(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case rn.ZodFunction:case rn.ZodVoid:case rn.ZodSymbol:default:return}};function al(e,t,n=!1){const s=t.seen.get(e);if(t.override){const r=t.override?.(e,t,s,n);if(r!==Od)return r}if(s&&!n){const e=ol(s,t);if(void 0!==e)return e}const r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);const a=rl(e,e.typeName,t),o="function"==typeof a?al(a(),t):a;if(o&&il(e,t,o),t.postProcess){const n=t.postProcess(o,e,t);return r.jsonSchema=o,n}return r.jsonSchema=o,o}const ol=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Pd(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Rd(t)):"seen"===t.$refStrategy?Rd(t):void 0}},il=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);function cl(e,t){return Xa(e)?function(e,t){if("_idmap"in e){const n=e,s=_a({...t,processors:Ka}),r={};for(const e of n._idmap.entries()){const[t,n]=e;va(n,s)}const a={},o={registry:n,uri:t?.uri,defs:r};s.external=o;for(const e of n._idmap.entries()){const[t,n]=e;wa(s,n),a[t]=ba(s,n)}if(Object.keys(r).length>0){const e="draft-2020-12"===s.target?"$defs":"definitions";a.__shared={[e]:r}}return{schemas:a}}const n=_a({...t,processors:Ka});return va(e,n),wa(n,e),ba(n,e)}(e,{target:(n=t?.target,n?"jsonSchema7"===n||"draft-7"===n?"draft-7":"jsonSchema2019-09"===n||"draft-2020-12"===n?"draft-2020-12":"draft-7":"draft-7"),io:t?.pipeStrategy??"input"}):((e,t)=>{const n=(e=>{const t=(e=>"string"==typeof e?{...xd,name:e}:{...xd,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let s=t.definitions?Object.entries(t.definitions).reduce((e,[t,s])=>({...e,[t]:al(s._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Rd(n)}),{}):void 0;const r="title"===t?.nameStrategy?void 0:t?.name,a=al(e._def,void 0===r?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??Rd(n),o=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(s||(s={}),s[n.openAiAnyTypeName]||(s[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=void 0===r?s?{...a,[n.definitionPath]:s}:a:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...s,[r]:a}};return"jsonSchema7"===n.target?i.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(i.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"});var n}function ul(e){const t=to(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const s=ro(n);if("string"!=typeof s)throw new Error("Schema method literal must be a string");return s}function dl(e,t){const n=Qa(e,t);if(!n.success)throw n.error;return n.data}class ll{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(lc,e=>{this._oncancel(e)}),this.setNotificationHandler(Ic,e=>{this._onprogress(e)}),this.setRequestHandler(Tc,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Mc,async(e,t)=>{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Ed(oc.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Zc,async(e,t)=>{const n=async()=>{const s=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(s,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,n=t.id,s=this._requestResolvers.get(n);if(s)if(this._requestResolvers.delete(n),"response"===e.type)s(t);else{const e=t;s(new Ed(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${n}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const r=await this._taskStore.getTask(s,t.sessionId);if(!r)throw new Ed(oc.InvalidParams,`Task not found: ${s}`);if(!Td(r.status))return await this._waitForTaskUpdate(s,t.signal),await n();if(Td(r.status)){const e=await this._taskStore.getTaskResult(s,t.sessionId);return this._clearTaskQueue(s),{...e,_meta:{...e._meta,[Zi]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Fc,async(e,t)=>{try{const{tasks:n,nextCursor:s}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(e){throw new Ed(oc.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(qc,async(e,t)=>{try{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Ed(oc.InvalidParams,`Task not found: ${e.params.taskId}`);if(Td(n.status))throw new Ed(oc.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new Ed(oc.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...s}}catch(e){if(e instanceof Ed)throw e;throw new Ed(oc.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,n,s,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:s})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ed.fromError(oc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};const s=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var n;s?.(e,t),ac(e)||(n=e,ic.safeParse(n).success)?this._onresponse(e):nc(e)?this._onrequest(e,t):(e=>sc.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const t=Ed.fromError(oc.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,r=e.params?._meta?.[Zi]?.taskId;if(void 0===n){const t={jsonrpc:"2.0",id:e.id,error:{code:oc.MethodNotFound,message:"Method not found"}};return void(r&&this._taskMessageQueue?this._enqueueTaskMessage(r,{type:"error",message:t,timestamp:Date.now()},s?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):s?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);const o=(i=e.params,Wi.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{const n={relatedRequestId:e.id};r&&(n.relatedTask={taskId:r}),await this.notification(t,n)},sendRequest:async(t,n,s)=>{const a={...s,relatedRequestId:e.id};r&&!a.relatedTask&&(a.relatedTask={taskId:r});const o=a.relatedTask?.taskId??r;return o&&c&&await c.updateTaskStatus(o,"input_required"),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:r,taskStore:c,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async t=>{if(a.signal.aborted)return;const n={result:t,jsonrpc:"2.0",id:e.id};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"response",message:n,timestamp:Date.now()},s?.sessionId):await(s?.send(n))},async t=>{if(a.signal.aborted)return;const n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:oc.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"error",message:n,timestamp:Date.now()},s?.sessionId):await(s?.send(n))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,s=Number(t),r=this._progressHandlers.get(s);if(!r)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const a=this._responseHandlers.get(s),o=this._timeoutInfo.get(s);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(e){return this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),void a(e)}r(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n)return this._requestResolvers.delete(t),void(ac(e)?n(e):n(new Ed(e.error.code,e.error.message,e.error.data)));const s=this._responseHandlers.get(t);if(void 0===s)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(ac(e)&&e.result&&"object"==typeof e.result){const n=e.result;if(n.task&&"object"==typeof n.task){const e=n.task;"string"==typeof e.taskId&&(r=!0,this._taskProgressTokens.set(e.taskId,t))}}r||this._progressHandlers.delete(t),ac(e)?s(e):s(Ed.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,n){const{task:s}=n??{};if(!s){try{const s=await this.request(e,t,n);yield{type:"result",result:s}}catch(e){yield{type:"error",error:e instanceof Ed?e:new Ed(oc.InternalError,String(e))}}return}let r;try{const s=await this.request(e,zc,n);if(!s.task)throw new Ed(oc.InternalError,"Task creation did not return a task");for(r=s.task.taskId,yield{type:"taskCreated",task:s.task};;){const e=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:e},Td(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:r},t,n);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Ed(oc.InternalError,`Task ${r} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Ed(oc.InternalError,`Task ${r} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:r},t,n);return void(yield{type:"result",result:e})}const s=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,s)),n?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof Ed?e:new Ed(oc.InternalError,String(e))}}}request(e,t,n){const{relatedRequestId:s,resumptionToken:r,onresumptiontoken:a,task:o,relatedTask:i}=n??{};return new Promise((c,u)=>{const d=e=>{u(e)};if(!this._transport)return void d(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){return void d(e)}n?.signal?.throwIfAborted();const l=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:l};n?.onprogress&&(this._progressHandlers.set(l,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:l}}),o&&(p.params={...p.params,task:o}),i&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Zi]:i}});const h=e=>{this._responseHandlers.delete(l),this._progressHandlers.delete(l),this._cleanupTimeout(l),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:l,reason:String(e)}},{relatedRequestId:s,resumptionToken:r,onresumptiontoken:a}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Ed?e:new Ed(oc.RequestTimeout,String(e));u(t)};this._responseHandlers.set(l,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return u(e);try{const n=Qa(t,e.result);n.success?c(n.data):u(n.error)}catch(e){u(e)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});const m=n?.timeout??6e4;this._setupTimeout(l,m,n?.maxTotalTimeout,()=>h(Ed.fromError(oc.RequestTimeout,"Request timed out",{timeout:m})),n?.resetTimeoutOnProgress??!1);const f=i?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(l);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${l}`))};this._requestResolvers.set(l,e),this._enqueueTaskMessage(f,{type:"request",message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(l),u(e)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:r,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(l),u(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Lc,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Uc,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Hc,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Zi]:t.relatedTask}}};return void await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Zi]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))})}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Zi]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const n=ul(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,s)=>{const r=dl(e,n);return Promise.resolve(t(r,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,t){const n=ul(e);this._notificationHandlers.set(n,n=>{const s=dl(e,n);return Promise.resolve(t(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const t of n)if("request"===t.type&&nc(t.message)){const n=t.message.id,s=this._requestResolvers.get(n);s?(s(new Ed(oc.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,s)=>{if(t.aborted)return void s(new Ed(oc.InvalidRequest,"Request cancelled"));const r=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(r),s(new Ed(oc.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const 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},t)},getTask:async e=>{const s=await n.getTask(e,t);if(!s)throw new Ed(oc.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(e,s,r)=>{await n.storeTaskResult(e,s,r,t);const a=await n.getTask(e,t);if(a){const t=Dc.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Td(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,s,r)=>{const a=await n.getTask(e,t);if(!a)throw new Ed(oc.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Td(a.status))throw new Ed(oc.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,s,r,t);const o=await n.getTask(e,t);if(o){const t=Dc.parse({method:"notifications/tasks/status",params:o});await this.notification(t),Td(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}function pl(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function hl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ml,fl={exports:{}},gl={},yl={},_l={},vl={},wl={},bl={};function kl(){return ml||(ml=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class s extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function r(e,...t){const n=[e[0]];let r=0;for(;r<t.length;)i(n,t[r]),n.push(e[++r]);return new s(n)}e._Code=s,e.nil=new s(""),e._=r;const a=new s("+");function o(e,...t){const n=[u(e[0])];let r=0;for(;r<t.length;)n.push(a),i(n,t[r]),n.push(a,u(e[++r]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const n=c(e[t-1],e[t+1]);if(void 0!==n){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}(n),new s(n)}function i(e,t){var r;t instanceof s?e.push(...t._items):t instanceof n?e.push(t):e.push("number"==typeof(r=t)||"boolean"==typeof r||null===r?r:u(Array.isArray(r)?r.join(","):r))}function c(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function u(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=o,e.addCodeArg=i,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`},e.stringify=function(e){return new s(u(e))},e.safeStringify=u,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new s(`.${t}`):r`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new s(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new s(e.toString())}}(bl)),bl}var $l,El,Sl={};function Tl(){return $l||($l=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=kl();class n extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var s;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(s||(e.UsedValueState=s={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class r{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,n;if((null===(n=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===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}}}e.Scope=r;class a extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:s}){this.value=e,this.scopePath=t._`.${new t.Name(n)}[${s}]`}}e.ValueScopeName=a;const o=t._`\n`;e.ValueScope=class extends r{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){var n;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const s=this.toName(e),{prefix:r}=s,a=null!==(n=t.key)&&void 0!==n?n:t.ref;let o=this._values[r];if(o){const e=o.get(a);if(e)return e}else o=this._values[r]=new Map;o.set(a,s);const i=this._scope[r]||(this._scope[r]=[]),c=i.length;return i[c]=t.ref,s.setValue(t,{property:r,itemIndex:c}),s}getValue(e,t){const n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(void 0===n.scopePath)throw new Error(`CodeGen: name "${n}" has no value`);return t._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(r,a,o={},i){let c=t.nil;for(const u in r){const d=r[u];if(!d)continue;const l=o[u]=o[u]||new Map;d.forEach(r=>{if(l.has(r))return;l.set(r,s.Started);let o=a(r);if(o){const n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=t._`${c}${n} ${r} = ${o};${this.opts._n}`}else{if(!(o=null==i?void 0:i(r)))throw new n(r);c=t._`${c}${o}${this.opts._n}`}l.set(r,s.Completed)})}return c}}}(Sl)),Sl}function Ol(){return El||(El=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=kl(),n=Tl();var s=kl();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return s._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return s.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return s.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return s.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return s.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return s.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return s.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return s.Name}});var r=Tl();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return r.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return r.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return r.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return r.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class a{optimizeNodes(){return this}optimizeNames(e,t){return this}}class o extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){const s=e?n.varKinds.var:this.varKind,r=void 0===this.rhs?"":` = ${this.rhs}`;return`${s} ${this.name}${r};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=I(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=I(this.rhs,e,n),this}get names(){return x(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class c extends i{constructor(e,t,n,s){super(e,n,s),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class d extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class l extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=I(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:n}=this;let s=n.length;for(;s--;){const r=n[s];r.optimizeNames(e,t)||(N(e,r.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>O(e,t.names),{})}}class m extends h{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class f extends h{}class g extends m{}g.kind="else";class y extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(P(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var n;if(this.else=null===(n=this.else)||void 0===n?void 0:n.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=I(this.condition,e,t),this}get names(){const e=super.names;return x(e,this.condition),this.else&&O(e,this.else.names),e}}y.kind="if";class _ extends m{}_.kind="for";class v extends _{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=I(this.iteration,e,t),this}get names(){return O(super.names,this.iteration.names)}}class w extends _{constructor(e,t,n,s){super(),this.varKind=e,this.name=t,this.from=n,this.to=s}render(e){const t=e.es5?n.varKinds.var:this.varKind,{name:s,from:r,to:a}=this;return`for(${t} ${s}=${r}; ${s}<${a}; ${s}++)`+super.render(e)}get names(){const e=x(super.names,this.from);return x(e,this.to)}}class b extends _{constructor(e,t,n,s){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=I(this.iterable,e,t),this}get names(){return O(super.names,this.iterable.names)}}class k extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}k.kind="func";class $ extends h{render(e){return"return "+super.render(e)}}$.kind="return";class E extends m{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var n,s;return super.optimizeNames(e,t),null===(n=this.catch)||void 0===n||n.optimizeNames(e,t),null===(s=this.finally)||void 0===s||s.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&O(e,this.catch.names),this.finally&&O(e,this.finally.names),e}}class S extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}S.kind="catch";class T extends m{render(e){return"finally"+super.render(e)}}function O(e,t){for(const n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function x(e,n){return n instanceof t._CodeOrName?O(e,n.names):e}function I(e,n,s){return e instanceof t.Name?a(e):(r=e)instanceof t._Code&&r._items.some(e=>e instanceof t.Name&&1===n[e.str]&&void 0!==s[e.str])?new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=a(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[])):e;var r;function a(e){const t=s[e.str];return void 0===t||1!==n[e.str]?e:(delete n[e.str],t)}}function N(e,t){for(const n in t)e[n]=(e[n]||0)-(t[n]||0)}function P(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${z(e)}`}T.kind="finally",e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new f]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,s){const r=this._scope.toName(t);return void 0!==n&&s&&(this._constants[r.str]=n),this._leafNode(new o(e,r,n)),r}const(e,t,s){return this._def(n.varKinds.const,e,t,s)}let(e,t,s){return this._def(n.varKinds.let,e,t,s)}var(e,t,s){return this._def(n.varKinds.var,e,t,s)}assign(e,t,n){return this._leafNode(new i(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){const n=["{"];for(const[s,r]of e)n.length>1&&n.push(","),n.push(s),(s!==r||this.opts.es5)&&(n.push(":"),(0,t.addCodeArg)(n,r));return n.push("}"),new t._Code(n)}if(e,t,n){if(this._blockNode(new y(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new v(e),t)}forRange(e,t,s,r,a=(this.opts.es5?n.varKinds.var:n.varKinds.let)){const o=this._scope.toName(e);return this._for(new w(a,o,t,s),()=>r(o))}forOf(e,s,r,a=n.varKinds.const){const o=this._scope.toName(e);if(this.opts.es5){const e=s instanceof t.Name?s:this.var("_arr",s);return this.forRange("_i",0,t._`${e}.length`,n=>{this.var(o,t._`${e}[${n}]`),r(o)})}return this._for(new b("of",a,o,s),()=>r(o))}forIn(e,s,r,a=(this.opts.es5?n.varKinds.var:n.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${s})`,r);const o=this._scope.toName(e);return this._for(new b("in",a,o,s),()=>r(o))}endFor(){return this._endBlockNode(_)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new d(e))}return(e){const t=new $;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');const s=new E;if(this._blockNode(s),this.code(e),t){const e=this.name("e");this._currNode=s.catch=new S(e),t(e)}return n&&(this._currNode=s.finally=new T,this.code(n)),this._endBlockNode(S,T)}throw(e){return this._leafNode(new l(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const n=this._nodes.length-t;if(n<0||void 0!==e&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,s,r){return this._blockNode(new k(e,n,s)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(k)}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,t){const n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},e.not=P;const R=j(e.operators.AND);e.and=function(...e){return e.reduce(R)};const C=j(e.operators.OR);function j(e){return(n,s)=>n===t.nil?s:s===t.nil?n:t._`${z(n)} ${e} ${z(s)}`}function z(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(C)}}(wl)),wl}var xl,Il={};function Nl(){if(xl)return Il;xl=1,Object.defineProperty(Il,"__esModule",{value:!0}),Il.checkStrictMode=Il.getErrorPath=Il.Type=Il.useFunc=Il.setEvaluated=Il.evaluatedPropsToName=Il.mergeEvaluated=Il.eachItem=Il.unescapeJsonPointer=Il.escapeJsonPointer=Il.escapeFragment=Il.unescapeFragment=Il.schemaRefOrVal=Il.schemaHasRulesButRef=Il.schemaHasRules=Il.checkUnknownRules=Il.alwaysValidSchema=Il.toHash=void 0;const e=Ol(),t=kl();function n(e,t=e.schema){const{opts:n,self:s}=e;if(!n.strictSchema)return;if("boolean"==typeof t)return;const r=s.RULES.keywords;for(const n in t)r[n]||l(e,`unknown keyword: "${n}"`)}function s(e,t){if("boolean"==typeof e)return!e;for(const n in e)if(t[n])return!0;return!1}function r(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function a(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function o({mergeNames:t,mergeToName:n,mergeValues:s,resultToName:r}){return(a,o,i,c)=>{const u=void 0===i?o:i instanceof e.Name?(o instanceof e.Name?t(a,o,i):n(a,o,i),i):o instanceof e.Name?(n(a,i,o),o):s(o,i);return c!==e.Name||u instanceof e.Name?u:r(a,u)}}function i(t,n){if(!0===n)return t.var("props",!0);const s=t.var("props",e._`{}`);return void 0!==n&&c(t,s,n),s}function c(t,n,s){Object.keys(s).forEach(s=>t.assign(e._`${n}${(0,e.getProperty)(s)}`,!0))}Il.toHash=function(e){const t={};for(const n of e)t[n]=!0;return t},Il.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(n(e,t),!s(t,e.self.RULES.all))},Il.checkUnknownRules=n,Il.schemaHasRules=s,Il.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const n in e)if("$ref"!==n&&t.all[n])return!0;return!1},Il.schemaRefOrVal=function({topSchemaRef:t,schemaPath:n},s,r,a){if(!a){if("number"==typeof s||"boolean"==typeof s)return s;if("string"==typeof s)return e._`${s}`}return e._`${t}${n}${(0,e.getProperty)(r)}`},Il.unescapeFragment=function(e){return a(decodeURIComponent(e))},Il.escapeFragment=function(e){return encodeURIComponent(r(e))},Il.escapeJsonPointer=r,Il.unescapeJsonPointer=a,Il.eachItem=function(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)},Il.mergeEvaluated={props:o({mergeNames:(t,n,s)=>t.if(e._`${s} !== true && ${n} !== undefined`,()=>{t.if(e._`${n} === true`,()=>t.assign(s,!0),()=>t.assign(s,e._`${s} || {}`).code(e._`Object.assign(${s}, ${n})`))}),mergeToName:(t,n,s)=>t.if(e._`${s} !== true`,()=>{!0===n?t.assign(s,!0):(t.assign(s,e._`${s} || {}`),c(t,s,n))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:i}),items:o({mergeNames:(t,n,s)=>t.if(e._`${s} !== true && ${n} !== undefined`,()=>t.assign(s,e._`${n} === true ? true : ${s} > ${n} ? ${s} : ${n}`)),mergeToName:(t,n,s)=>t.if(e._`${s} !== true`,()=>t.assign(s,!0===n||e._`${s} > ${n} ? ${s} : ${n}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},Il.evaluatedPropsToName=i,Il.setEvaluated=c;const u={};var d;function l(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,!0===n)throw new Error(t);e.self.logger.warn(t)}}return Il.useFunc=function(e,n){return e.scopeValue("func",{ref:n,code:u[n.code]||(u[n.code]=new t._Code(n.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(d||(Il.Type=d={})),Il.getErrorPath=function(t,n,s){if(t instanceof e.Name){const r=n===d.Num;return s?r?e._`"[" + ${t} + "]"`:e._`"['" + ${t} + "']"`:r?e._`"/" + ${t}`:e._`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return s?(0,e.getProperty)(t).toString():"/"+r(t)},Il.checkStrictMode=l,Il}var Pl,Rl,Cl,jl={};function zl(){if(Pl)return jl;Pl=1,Object.defineProperty(jl,"__esModule",{value:!0});const e=Ol(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return jl.default=t,jl}function Al(){return Rl||(Rl=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ol(),n=Nl(),s=zl();function r(e,n){const r=e.const("err",n);e.if(t._`${s.default.vErrors} === null`,()=>e.assign(s.default.vErrors,t._`[${r}]`),t._`${s.default.vErrors}.push(${r})`),e.code(t._`${s.default.errors}++`)}function a(e,n){const{gen:s,validateName:r,schemaEnv:a}=e;a.$async?s.throw(t._`new ${e.ValidationError}(${n})`):(s.assign(t._`${r}.errors`,n),s.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?t.str`"${e}" keyword must be ${n} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(n,s=e.keywordError,o,c){const{it:u}=n,{gen:d,compositeRule:l,allErrors:p}=u,h=i(n,s,o);(null!=c?c:l||p)?r(d,h):a(u,t._`[${h}]`)},e.reportExtraError=function(t,n=e.keywordError,o){const{it:c}=t,{gen:u,compositeRule:d,allErrors:l}=c;r(u,i(t,n,o)),d||l||a(c,s.default.vErrors)},e.resetErrorsCount=function(e,n){e.assign(s.default.errors,n),e.if(t._`${s.default.vErrors} !== null`,()=>e.if(n,()=>e.assign(t._`${s.default.vErrors}.length`,n),()=>e.assign(s.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:n,schemaValue:r,data:a,errsCount:o,it:i}){if(void 0===o)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",o,s.default.errors,o=>{e.const(c,t._`${s.default.vErrors}[${o}]`),e.if(t._`${c}.instancePath === undefined`,()=>e.assign(t._`${c}.instancePath`,(0,t.strConcat)(s.default.instancePath,i.errorPath))),e.assign(t._`${c}.schemaPath`,t.str`${i.errSchemaPath}/${n}`),i.opts.verbose&&(e.assign(t._`${c}.schema`,r),e.assign(t._`${c}.data`,a))})};const o={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function i(e,n,r){const{createErrors:a}=e.it;return!1===a?t._`{}`:function(e,n,r={}){const{gen:a,it:i}=e,d=[c(i,r),u(e,r)];return function(e,{params:n,message:r},a){const{keyword:i,data:c,schemaValue:u,it:d}=e,{opts:l,propertyName:p,topSchemaRef:h,schemaPath:m}=d;a.push([o.keyword,i],[o.params,"function"==typeof n?n(e):n||t._`{}`]),l.messages&&a.push([o.message,"function"==typeof r?r(e):r]),l.verbose&&a.push([o.schema,u],[o.parentSchema,t._`${h}${m}`],[s.default.data,c]),p&&a.push([o.propertyName,p])}(e,n,d),a.object(...d)}(e,n,r)}function c({errorPath:e},{instancePath:r}){const a=r?t.str`${e}${(0,n.getErrorPath)(r,n.Type.Str)}`:e;return[s.default.instancePath,(0,t.strConcat)(s.default.instancePath,a)]}function u({keyword:e,it:{errSchemaPath:s}},{schemaPath:r,parentSchema:a}){let i=a?s:t.str`${s}/${e}`;return r&&(i=t.str`${i}${(0,n.getErrorPath)(r,n.Type.Str)}`),[o.schemaPath,i]}}(vl)),vl}var Dl,Ml={},Ll={};function Zl(){if(Dl)return Ll;Dl=1,Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.getRules=Ll.isJSONType=void 0;const e=new Set(["string","number","integer","boolean","null","object","array"]);return Ll.isJSONType=function(t){return"string"==typeof t&&e.has(t)},Ll.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}},Ll}var Fl,Ul,ql={};function Hl(){if(Fl)return ql;function e(e,n){return n.rules.some(n=>t(e,n))}function t(e,t){var n;return void 0!==e[t.keyword]||(null===(n=t.definition.implements)||void 0===n?void 0:n.some(t=>void 0!==e[t]))}return Fl=1,Object.defineProperty(ql,"__esModule",{value:!0}),ql.shouldUseRule=ql.shouldUseGroup=ql.schemaHasRulesForType=void 0,ql.schemaHasRulesForType=function({schema:t,self:n},s){const r=n.RULES.types[s];return r&&!0!==r&&e(t,r)},ql.shouldUseGroup=e,ql.shouldUseRule=t,ql}function Vl(){if(Ul)return Ml;Ul=1,Object.defineProperty(Ml,"__esModule",{value:!0}),Ml.reportTypeError=Ml.checkDataTypes=Ml.checkDataType=Ml.coerceAndCheckDataType=Ml.getJSONTypes=Ml.getSchemaTypes=Ml.DataType=void 0;const e=Zl(),t=Hl(),n=Al(),s=Ol(),r=Nl();var a;function o(t){const n=Array.isArray(t)?t:t?[t]:[];if(n.every(e.isJSONType))return n;throw new Error("type must be JSONType or JSONType[]: "+n.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(a||(Ml.DataType=a={})),Ml.getSchemaTypes=function(e){const t=o(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},Ml.getJSONTypes=o,Ml.coerceAndCheckDataType=function(e,n){const{gen:r,data:o,opts:c}=e,d=function(e,t){return t?e.filter(e=>i.has(e)||"array"===t&&"array"===e):[]}(n,c.coerceTypes),p=n.length>0&&!(0===d.length&&1===n.length&&(0,t.schemaHasRulesForType)(e,n[0]));if(p){const t=u(n,o,c.strictNumbers,a.Wrong);r.if(t,()=>{d.length?function(e,t,n){const{gen:r,data:a,opts:o}=e,c=r.let("dataType",s._`typeof ${a}`),d=r.let("coerced",s._`undefined`);"array"===o.coerceTypes&&r.if(s._`${c} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,s._`${a}[0]`).assign(c,s._`typeof ${a}`).if(u(t,a,o.strictNumbers),()=>r.assign(d,a))),r.if(s._`${d} !== undefined`);for(const e of n)(i.has(e)||"array"===e&&"array"===o.coerceTypes)&&p(e);function p(e){switch(e){case"string":return void r.elseIf(s._`${c} == "number" || ${c} == "boolean"`).assign(d,s._`"" + ${a}`).elseIf(s._`${a} === null`).assign(d,s._`""`);case"number":return void r.elseIf(s._`${c} == "boolean" || ${a} === null
3
+ || (${c} == "string" && ${a} && ${a} == +${a})`).assign(d,s._`+${a}`);case"integer":return void r.elseIf(s._`${c} === "boolean" || ${a} === null
4
+ || (${c} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(d,s._`+${a}`);case"boolean":return void r.elseIf(s._`${a} === "false" || ${a} === 0 || ${a} === null`).assign(d,!1).elseIf(s._`${a} === "true" || ${a} === 1`).assign(d,!0);case"null":return r.elseIf(s._`${a} === "" || ${a} === 0 || ${a} === false`),void r.assign(d,null);case"array":r.elseIf(s._`${c} === "string" || ${c} === "number"
5
+ || ${c} === "boolean" || ${a} === null`).assign(d,s._`[${a}]`)}}r.else(),l(e),r.endIf(),r.if(s._`${d} !== undefined`,()=>{r.assign(a,d),function({gen:e,parentData:t,parentDataProperty:n},r){e.if(s._`${t} !== undefined`,()=>e.assign(s._`${t}[${n}]`,r))}(e,d)})}(e,n,d):l(e)})}return p};const i=new Set(["string","number","integer","boolean","null"]);function c(e,t,n,r=a.Correct){const o=r===a.Correct?s.operators.EQ:s.operators.NEQ;let i;switch(e){case"null":return s._`${t} ${o} null`;case"array":i=s._`Array.isArray(${t})`;break;case"object":i=s._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=c(s._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=c();break;default:return s._`typeof ${t} ${o} ${e}`}return r===a.Correct?i:(0,s.not)(i);function c(e=s.nil){return(0,s.and)(s._`typeof ${t} == "number"`,e,n?s._`isFinite(${t})`:s.nil)}}function u(e,t,n,a){if(1===e.length)return c(e[0],t,n,a);let o;const i=(0,r.toHash)(e);if(i.array&&i.object){const e=s._`typeof ${t} != "object"`;o=i.null?e:s._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else o=s.nil;i.number&&delete i.integer;for(const e in i)o=(0,s.and)(o,c(e,t,n,a));return o}Ml.checkDataType=c,Ml.checkDataTypes=u;const d={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?s._`{type: ${e}}`:s._`{type: ${t}}`};function l(e){const t=function(e){const{gen:t,data:n,schema:s}=e,a=(0,r.schemaRefOrVal)(e,s,"type");return{gen:t,keyword:"type",data:n,schema:s.type,schemaCode:a,schemaValue:a,parentSchema:s,params:{},it:e}}(e);(0,n.reportError)(t,d)}return Ml.reportTypeError=l,Ml}var Jl,Kl,Bl,Wl={},Gl={},Xl={};function Yl(){if(Kl)return Xl;Kl=1,Object.defineProperty(Xl,"__esModule",{value:!0}),Xl.validateUnion=Xl.validateArray=Xl.usePattern=Xl.callValidateCode=Xl.schemaProperties=Xl.allSchemaProperties=Xl.noPropertyInData=Xl.propertyInData=Xl.isOwnProperty=Xl.hasPropFunc=Xl.reportMissingProp=Xl.checkMissingProp=Xl.checkReportMissingProp=void 0;const e=Ol(),t=Nl(),n=zl(),s=Nl();function r(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:e._`Object.prototype.hasOwnProperty`})}function a(t,n,s){return e._`${r(t)}.call(${n}, ${s})`}function o(t,n,s,r){const o=e._`${n}${(0,e.getProperty)(s)} === undefined`;return r?(0,e.or)(o,(0,e.not)(a(t,n,s))):o}function i(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}Xl.checkReportMissingProp=function(t,n){const{gen:s,data:r,it:a}=t;s.if(o(s,r,n,a.opts.ownProperties),()=>{t.setParams({missingProperty:e._`${n}`},!0),t.error()})},Xl.checkMissingProp=function({gen:t,data:n,it:{opts:s}},r,a){return(0,e.or)(...r.map(r=>(0,e.and)(o(t,n,r,s.ownProperties),e._`${a} = ${r}`)))},Xl.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},Xl.hasPropFunc=r,Xl.isOwnProperty=a,Xl.propertyInData=function(t,n,s,r){const o=e._`${n}${(0,e.getProperty)(s)} !== undefined`;return r?e._`${o} && ${a(t,n,s)}`:o},Xl.noPropertyInData=o,Xl.allSchemaProperties=i,Xl.schemaProperties=function(e,n){return i(n).filter(s=>!(0,t.alwaysValidSchema)(e,n[s]))},Xl.callValidateCode=function({schemaCode:t,data:s,it:{gen:r,topSchemaRef:a,schemaPath:o,errorPath:i},it:c},u,d,l){const p=l?e._`${t}, ${s}, ${a}${o}`:s,h=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,i)],[n.default.parentData,c.parentData],[n.default.parentDataProperty,c.parentDataProperty],[n.default.rootData,n.default.rootData]];c.opts.dynamicRef&&h.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);const m=e._`${p}, ${r.object(...h)}`;return d!==e.nil?e._`${u}.call(${d}, ${m})`:e._`${u}(${m})`};const c=e._`new RegExp`;return Xl.usePattern=function({gen:t,it:{opts:n}},r){const a=n.unicodeRegExp?"u":"",{regExp:o}=n.code,i=o(r,a);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:e._`${"new RegExp"===o.code?c:(0,s.useFunc)(t,o)}(${r}, ${a})`})},Xl.validateArray=function(n){const{gen:s,data:r,keyword:a,it:o}=n,i=s.name("valid");if(o.allErrors){const e=s.let("valid",!0);return c(()=>s.assign(e,!1)),e}return s.var(i,!0),c(()=>s.break()),i;function c(o){const c=s.const("len",e._`${r}.length`);s.forRange("i",0,c,r=>{n.subschema({keyword:a,dataProp:r,dataPropType:t.Type.Num},i),s.if((0,e.not)(i),o)})}},Xl.validateUnion=function(n){const{gen:s,schema:r,keyword:a,it:o}=n;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(e=>(0,t.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;const i=s.let("valid",!1),c=s.name("_valid");s.block(()=>r.forEach((t,r)=>{const o=n.subschema({keyword:a,schemaProp:r,compositeRule:!0},c);s.assign(i,e._`${i} || ${c}`),n.mergeValidEvaluated(o,c)||s.if((0,e.not)(i))})),n.result(i,()=>n.reset(),()=>n.error(!0))},Xl}var Ql,ep,tp,np={},sp={};function rp(){return tp||(tp=1,ep=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var s,r,a;if(Array.isArray(t)){if((s=t.length)!=n.length)return!1;for(r=s;0!==r--;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((s=(a=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(r=s;0!==r--;)if(!Object.prototype.hasOwnProperty.call(n,a[r]))return!1;for(r=s;0!==r--;){var o=a[r];if(!e(t[o],n[o]))return!1}return!0}return t!=t&&n!=n}),ep}var ap,op,ip,cp={exports:{}};function up(){if(ap)return cp.exports;ap=1;var e=cp.exports=function(e,n,s){"function"==typeof n&&(s=n,n={}),t(n,"function"==typeof(s=n.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function t(s,r,a,o,i,c,u,d,l,p){if(o&&"object"==typeof o&&!Array.isArray(o)){for(var h in r(o,i,c,u,d,l,p),o){var m=o[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var f=0;f<m.length;f++)t(s,r,a,m[f],i+"/"+h+"/"+f,c,i,h,o,f)}else if(h in e.propsKeywords){if(m&&"object"==typeof m)for(var g in m)t(s,r,a,m[g],i+"/"+h+"/"+n(g),c,i,h,o,g)}else(h in e.keywords||s.allKeys&&!(h in e.skipKeywords))&&t(s,r,a,m,i+"/"+h,c,i,h,o)}a(o,i,c,u,d,l,p)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}return e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.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},cp.exports}function dp(){if(op)return sp;op=1,Object.defineProperty(sp,"__esModule",{value:!0}),sp.getSchemaRefs=sp.resolveUrl=sp.normalizeId=sp._getFullPath=sp.getFullPath=sp.inlineRef=void 0;const e=Nl(),t=rp(),n=up(),s=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);sp.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!a(e):!!t&&o(e)<=t)};const r=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(e){for(const t in e){if(r.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(a))return!0;if("object"==typeof n&&a(n))return!0}return!1}function o(t){let n=0;for(const r in t){if("$ref"===r)return 1/0;if(n++,!s.has(r)&&("object"==typeof t[r]&&(0,e.eachItem)(t[r],e=>n+=o(e)),n===1/0))return 1/0}return n}function i(e,t="",n){!1!==n&&(t=d(t));const s=e.parse(t);return c(e,s)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}sp.getFullPath=i,sp._getFullPath=c;const u=/#\/?$/;function d(e){return e?e.replace(u,""):""}sp.normalizeId=d,sp.resolveUrl=function(e,t,n){return n=d(n),e.resolve(t,n)};const l=/^[a-z_][-a-z0-9._]*$/i;return sp.getSchemaRefs=function(e,s){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:a}=this.opts,o=d(e[r]||s),c={"":o},u=i(a,o,!1),p={},h=new Set;return n(e,{allKeys:!0},(e,t,n,s)=>{if(void 0===s)return;const a=u+t;let o=c[s];function i(t){const n=this.opts.uriResolver.resolve;if(t=d(o?n(o,t):t),h.has(t))throw f(t);h.add(t);let s=this.refs[t];return"string"==typeof s&&(s=this.refs[s]),"object"==typeof s?m(e,s.schema,t):t!==d(a)&&("#"===t[0]?(m(e,p[t],t),p[t]=e):this.refs[t]=a),t}function g(e){if("string"==typeof e){if(!l.test(e))throw new Error(`invalid anchor "${e}"`);i.call(this,`#${e}`)}}"string"==typeof e[r]&&(o=i.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),c[t]=o}),p;function m(e,n,s){if(void 0!==n&&!t(e,n))throw f(s)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}},sp}function lp(){if(ip)return yl;ip=1,Object.defineProperty(yl,"__esModule",{value:!0}),yl.getData=yl.KeywordCxt=yl.validateFunctionCode=void 0;const e=function(){if(Cl)return _l;Cl=1,Object.defineProperty(_l,"__esModule",{value:!0}),_l.boolOrEmptySchema=_l.topBoolOrEmptySchema=void 0;const e=Al(),t=Ol(),n=zl(),s={message:"boolean schema is false"};function r(t,n){const{gen:r,data:a}=t,o={gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,e.reportError)(o,s,void 0,n)}return _l.topBoolOrEmptySchema=function(e){const{gen:s,schema:a,validateName:o}=e;!1===a?r(e,!1):"object"==typeof a&&!0===a.$async?s.return(n.default.data):(s.assign(t._`${o}.errors`,null),s.return(!0))},_l.boolOrEmptySchema=function(e,t){const{gen:n,schema:s}=e;!1===s?(n.var(t,!1),r(e)):n.var(t,!0)},_l}(),t=Vl(),n=Hl(),s=Vl(),r=function(){if(Jl)return Wl;Jl=1,Object.defineProperty(Wl,"__esModule",{value:!0}),Wl.assignDefaults=void 0;const e=Ol(),t=Nl();function n(n,s,r){const{gen:a,compositeRule:o,data:i,opts:c}=n;if(void 0===r)return;const u=e._`${i}${(0,e.getProperty)(s)}`;if(o)return void(0,t.checkStrictMode)(n,`default is ignored for: ${u}`);let d=e._`${u} === undefined`;"empty"===c.useDefaults&&(d=e._`${d} || ${u} === null || ${u} === ""`),a.if(d,e._`${u} = ${(0,e.stringify)(r)}`)}return Wl.assignDefaults=function(e,t){const{properties:s,items:r}=e.schema;if("object"===t&&s)for(const t in s)n(e,t,s[t].default);else"array"===t&&Array.isArray(r)&&r.forEach((t,s)=>n(e,s,t.default))},Wl}(),a=function(){if(Bl)return Gl;Bl=1,Object.defineProperty(Gl,"__esModule",{value:!0}),Gl.validateKeywordUsage=Gl.validSchemaType=Gl.funcKeywordCode=Gl.macroKeywordCode=void 0;const e=Ol(),t=zl(),n=Yl(),s=Al();function r(t){const{gen:n,data:s,it:r}=t;n.if(r.parentData,()=>n.assign(s,e._`${r.parentData}[${r.parentDataProperty}]`))}function a(t,n,s){if(void 0===s)throw new Error(`keyword "${n}" failed to compile`);return t.scopeValue("keyword","function"==typeof s?{ref:s}:{ref:s,code:(0,e.stringify)(s)})}return Gl.macroKeywordCode=function(t,n){const{gen:s,keyword:r,schema:o,parentSchema:i,it:c}=t,u=n.macro.call(c.self,o,i,c),d=a(s,r,u);!1!==c.opts.validateSchema&&c.self.validateSchema(u,!0);const l=s.name("valid");t.subschema({schema:u,schemaPath:e.nil,errSchemaPath:`${c.errSchemaPath}/${r}`,topSchemaRef:d,compositeRule:!0},l),t.pass(l,()=>t.error(!0))},Gl.funcKeywordCode=function(o,i){var c;const{gen:u,keyword:d,schema:l,parentSchema:p,$data:h,it:m}=o;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,i);const f=!h&&i.compile?i.compile.call(m.self,l,p,m):i.validate,g=a(u,d,f),y=u.let("valid");function _(s=(i.async?e._`await `:e.nil)){const r=m.opts.passContext?t.default.this:t.default.self,a=!("compile"in i&&!h||!1===i.schema);u.assign(y,e._`${s}${(0,n.callValidateCode)(o,g,r,a)}`,i.modifying)}function v(t){var n;u.if((0,e.not)(null!==(n=i.valid)&&void 0!==n?n:y),t)}o.block$data(y,function(){if(!1===i.errors)_(),i.modifying&&r(o),v(()=>o.error());else{const n=i.async?function(){const t=u.let("ruleErrs",null);return u.try(()=>_(e._`await `),n=>u.assign(y,!1).if(e._`${n} instanceof ${m.ValidationError}`,()=>u.assign(t,e._`${n}.errors`),()=>u.throw(n))),t}():function(){const t=e._`${g}.errors`;return u.assign(t,null),_(e.nil),t}();i.modifying&&r(o),v(()=>function(n,r){const{gen:a}=n;a.if(e._`Array.isArray(${r})`,()=>{a.assign(t.default.vErrors,e._`${t.default.vErrors} === null ? ${r} : ${t.default.vErrors}.concat(${r})`).assign(t.default.errors,e._`${t.default.vErrors}.length`),(0,s.extendErrors)(n)},()=>n.error())}(o,n))}}),o.ok(null!==(c=i.valid)&&void 0!==c?c:y)},Gl.validSchemaType=function(e,t,n=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e)},Gl.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:s},r,a){if(Array.isArray(r.keyword)?!r.keyword.includes(a):r.keyword!==a)throw new Error("ajv implementation error");const o=r.dependencies;if(null==o?void 0:o.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(r.validateSchema&&!r.validateSchema(e[a])){const e=`keyword "${a}" value is invalid at path "${s}": `+n.errorsText(r.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}},Gl}(),o=function(){if(Ql)return np;Ql=1,Object.defineProperty(np,"__esModule",{value:!0}),np.extendSubschemaMode=np.extendSubschemaData=np.getSubschema=void 0;const e=Ol(),t=Nl();return np.getSubschema=function(n,{keyword:s,schemaProp:r,schema:a,schemaPath:o,errSchemaPath:i,topSchemaRef:c}){if(void 0!==s&&void 0!==a)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==s){const a=n.schema[s];return void 0===r?{schema:a,schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(s)}`,errSchemaPath:`${n.errSchemaPath}/${s}`}:{schema:a[r],schemaPath:e._`${n.schemaPath}${(0,e.getProperty)(s)}${(0,e.getProperty)(r)}`,errSchemaPath:`${n.errSchemaPath}/${s}/${(0,t.escapeFragment)(r)}`}}if(void 0!==a){if(void 0===o||void 0===i||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')},np.extendSubschemaData=function(n,s,{dataProp:r,dataPropType:a,data:o,dataTypes:i,propertyName:c}){if(void 0!==o&&void 0!==r)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:u}=s;if(void 0!==r){const{errorPath:o,dataPathArr:i,opts:c}=s;d(u.let("data",e._`${s.data}${(0,e.getProperty)(r)}`,!0)),n.errorPath=e.str`${o}${(0,t.getErrorPath)(r,a,c.jsPropertySyntax)}`,n.parentDataProperty=e._`${r}`,n.dataPathArr=[...i,n.parentDataProperty]}function d(e){n.data=e,n.dataLevel=s.dataLevel+1,n.dataTypes=[],s.definedProperties=new Set,n.parentData=s.data,n.dataNames=[...s.dataNames,e]}void 0!==o&&(d(o instanceof e.Name?o:u.let("data",o,!0)),void 0!==c&&(n.propertyName=c)),i&&(n.dataTypes=i)},np.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:s,createErrors:r,allErrors:a}){void 0!==s&&(e.compositeRule=s),void 0!==r&&(e.createErrors=r),void 0!==a&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n},np}(),i=Ol(),c=zl(),u=dp(),d=Nl(),l=Al();function p({gen:e,validateName:t,schema:n,schemaEnv:s,opts:r},a){r.code.es5?e.func(t,i._`${c.default.data}, ${c.default.valCxt}`,s.$async,()=>{e.code(i._`"use strict"; ${h(n,r)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,i._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,i._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,i._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,i._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,i._`""`),e.var(c.default.parentData,i._`undefined`),e.var(c.default.parentDataProperty,i._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,i._`{}`)})}(e,r),e.code(a)}):e.func(t,i._`${c.default.data}, ${function(e){return i._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?i._`, ${c.default.dynamicAnchors}={}`:i.nil}}={}`}(r)}`,s.$async,()=>e.code(h(n,r)).code(a))}function h(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?i._`/*# sourceURL=${n} */`:i.nil}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function f(e){return"boolean"!=typeof e.schema}function g(e){(0,d.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:s,self:r}=e;t.$ref&&s.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function y(e,n){if(e.opts.jtd)return v(e,[],!1,n);const s=(0,t.getSchemaTypes)(e.schema);v(e,s,!(0,t.coerceAndCheckDataType)(e,s),n)}function _({gen:e,schemaEnv:t,schema:n,errSchemaPath:s,opts:r}){const a=n.$comment;if(!0===r.$comment)e.code(i._`${c.default.self}.logger.log(${a})`);else if("function"==typeof r.$comment){const n=i.str`${s}/$comment`,r=e.scopeValue("root",{ref:t.root});e.code(i._`${c.default.self}.opts.$comment(${a}, ${n}, ${r}.schema)`)}}function v(e,t,r,a){const{gen:o,schema:u,data:l,allErrors:p,opts:h,self:m}=e,{RULES:f}=m;function g(d){(0,n.shouldUseGroup)(u,d)&&(d.type?(o.if((0,s.checkDataType)(d.type,l,h.strictNumbers)),w(e,d),1===t.length&&t[0]===d.type&&r&&(o.else(),(0,s.reportTypeError)(e)),o.endIf()):w(e,d),p||o.if(i._`${c.default.errors} === ${a||0}`))}!u.$ref||!h.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(u,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{b(e.dataTypes,t)||k(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const n=[];for(const s of e.dataTypes)b(t,s)?n.push(s):t.includes("integer")&&"number"===s&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&k(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const s=e.self.RULES.all;for(const r in s){const a=s[r];if("object"==typeof a&&(0,n.shouldUseRule)(e.schema,a)){const{type:n}=a.definition;n.length&&!n.some(e=>{return s=e,(n=t).includes(s)||"number"===s&&n.includes("integer");var n,s})&&k(e,`missing type "${n.join(",")}" for keyword "${r}"`)}}}(e,e.dataTypes))}(e,t),o.block(()=>{for(const e of f.rules)g(e);g(f.post)})):o.block(()=>E(e,"$ref",f.all.$ref.definition))}function w(e,t){const{gen:s,schema:a,opts:{useDefaults:o}}=e;o&&(0,r.assignDefaults)(e,t.type),s.block(()=>{for(const s of t.rules)(0,n.shouldUseRule)(a,s)&&E(e,s.keyword,s.definition,t.type)})}function b(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function k(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}yl.validateFunctionCode=function(t){f(t)&&(g(t),m(t))?function(e){const{schema:t,opts:n,gen:s}=e;p(e,()=>{n.$comment&&t.$comment&&_(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,"default is ignored in the schema root")}(e),s.let(c.default.vErrors,null),s.let(c.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",i._`${n}.evaluated`),t.if(i._`${e.evaluated}.dynamicProps`,()=>t.assign(i._`${e.evaluated}.props`,i._`undefined`)),t.if(i._`${e.evaluated}.dynamicItems`,()=>t.assign(i._`${e.evaluated}.items`,i._`undefined`))}(e),y(e),function(e){const{gen:t,schemaEnv:n,validateName:s,ValidationError:r,opts:a}=e;n.$async?t.if(i._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(i._`new ${r}(${c.default.vErrors})`)):(t.assign(i._`${s}.errors`,c.default.vErrors),a.unevaluated&&function({gen:e,evaluated:t,props:n,items:s}){n instanceof i.Name&&e.assign(i._`${t}.props`,n),s instanceof i.Name&&e.assign(i._`${t}.items`,s)}(e),t.return(i._`${c.default.errors} === 0`))}(e)})}(t):p(t,()=>(0,e.topBoolOrEmptySchema)(t))};class ${constructor(e,t,n){if((0,a.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",O(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,n){this.failResult((0,i.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,i.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(i._`${t} !== undefined && (${(0,i.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?l.reportExtraError:l.reportError)(this,this.def.error,t)}$dataError(){(0,l.reportError)(this,this.def.$dataError||l.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,l.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=i.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=i.nil,t=i.nil){if(!this.$data)return;const{gen:n,schemaCode:s,schemaType:r,def:a}=this;n.if((0,i.or)(i._`${s} === undefined`,t)),e!==i.nil&&n.assign(e,!0),(r.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==i.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,i.or)(function(){if(n.length){if(!(t instanceof i.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return i._`${(0,s.checkDataTypes)(e,t,a.opts.strictNumbers,s.DataType.Wrong)}`}return i.nil}(),function(){if(r.validateSchema){const n=e.scopeValue("validate$data",{ref:r.validateSchema});return i._`!${n}(${t})`}return i.nil}())}subschema(t,n){const s=(0,o.getSubschema)(this.it,t);(0,o.extendSubschemaData)(s,this.it,t),(0,o.extendSubschemaMode)(s,t);const r={...this.it,...s,items:void 0,props:void 0};return function(t,n){f(t)&&(g(t),m(t))?function(e,t){const{schema:n,gen:s,opts:r}=e;r.$comment&&n.$comment&&_(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const a=s.const("_errs",c.default.errors);y(e,a),s.var(t,i._`${a} === ${c.default.errors}`)}(t,n):(0,e.boolOrEmptySchema)(t,n)}(r,n),r}mergeEvaluated(e,t){const{it:n,gen:s}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=d.mergeEvaluated.props(s,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=d.mergeEvaluated.items(s,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:s}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return s.if(t,()=>this.mergeEvaluated(e,i.Name)),!0}}function E(e,t,n,s){const r=new $(e,n,t);"code"in n?n.code(r,s):r.$data&&n.validate?(0,a.funcKeywordCode)(r,n):"macro"in n?(0,a.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,a.funcKeywordCode)(r,n)}yl.KeywordCxt=$;const S=/^\/(?:[^~]|~0|~1)*$/,T=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function O(e,{dataLevel:t,dataNames:n,dataPathArr:s}){let r,a;if(""===e)return c.default.rootData;if("/"===e[0]){if(!S.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,a=c.default.rootData}else{const o=T.exec(e);if(!o)throw new Error(`Invalid JSON-pointer: ${e}`);const i=+o[1];if(r=o[2],"#"===r){if(i>=t)throw new Error(l("property/index",i));return s[t-i]}if(i>t)throw new Error(l("data",i));if(a=n[t-i],!r)return a}let o=a;const u=r.split("/");for(const e of u)e&&(a=i._`${a}${(0,i.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=i._`${o} && ${a}`);return o;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}return yl.getData=O,yl}var pp,hp={};function mp(){if(pp)return hp;pp=1,Object.defineProperty(hp,"__esModule",{value:!0});class e extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}return hp.default=e,hp}var fp,gp={};function yp(){if(fp)return gp;fp=1,Object.defineProperty(gp,"__esModule",{value:!0});const e=dp();class t extends Error{constructor(t,n,s,r){super(r||`can't resolve reference ${s} from id ${n}`),this.missingRef=(0,e.resolveUrl)(t,n,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(t,this.missingRef))}}return gp.default=t,gp}var _p,vp={};function wp(){if(_p)return vp;_p=1,Object.defineProperty(vp,"__esModule",{value:!0}),vp.resolveSchema=vp.getCompilingSchema=vp.resolveRef=vp.compileSchema=vp.SchemaEnv=void 0;const e=Ol(),t=mp(),n=zl(),s=dp(),r=Nl(),a=lp();class o{constructor(e){var t;let n;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,s.normalizeId)(null==n?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==n?void 0:n.$async,this.refs={}}}function i(r){const o=u.call(this,r);if(o)return o;const i=(0,s.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:c,lines:d}=this.opts.code,{ownProperties:l}=this.opts,p=new e.CodeGen(this.scope,{es5:c,lines:d,ownProperties:l});let h;r.$async&&(h=p.scopeValue("Error",{ref:t.default,code:e._`require("ajv/dist/runtime/validation_error").default`}));const m=p.scopeName("validate");r.validateName=m;const f={gen:p,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:p.scopeValue("schema",!0===this.opts.code.source?{ref:r.schema,code:(0,e.stringify)(r.schema)}:{ref:r.schema}),validateName:m,ValidationError:h,schema:r.schema,schemaEnv:r,rootId:i,baseId:r.baseId||i,schemaPath:e.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:e._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(r),(0,a.validateFunctionCode)(f),p.optimize(this.opts.code.optimize);const t=p.toString();g=`${p.scopeRefs(n.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,r));const s=new Function(`${n.default.self}`,`${n.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:s}),s.errors=null,s.schema=r.schema,s.schemaEnv=r,r.$async&&(s.$async=!0),!0===this.opts.code.source&&(s.source={validateName:m,validateCode:t,scopeValues:p._values}),this.opts.unevaluated){const{props:t,items:n}=f;s.evaluated={props:t instanceof e.Name?void 0:t,items:n instanceof e.Name?void 0:n,dynamicProps:t instanceof e.Name,dynamicItems:n instanceof e.Name},s.source&&(s.source.evaluated=(0,e.stringify)(s.evaluated))}return r.validate=s,r}catch(e){throw delete r.validate,delete r.validateName,g&&this.logger.error("Error compiling schema, function code:",g),e}finally{this._compilations.delete(r)}}function c(e){return(0,s.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:i.call(this,e)}function u(e){for(const t of this._compilations)if(d(t,e))return t}function d(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function l(e,t){let n;for(;"string"==typeof(n=this.refs[t]);)t=n;return n||this.schemas[t]||p.call(this,e,t)}function p(e,t){const n=this.opts.uriResolver.parse(t),r=(0,s._getFullPath)(this.opts.uriResolver,n);let a=(0,s.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return m.call(this,n,e);const c=(0,s.normalizeId)(r),u=this.refs[c]||this.schemas[c];if("string"==typeof u){const t=p.call(this,e,u);if("object"!=typeof(null==t?void 0:t.schema))return;return m.call(this,n,t)}if("object"==typeof(null==u?void 0:u.schema)){if(u.validate||i.call(this,u),c===(0,s.normalizeId)(t)){const{schema:t}=u,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,s.resolveUrl)(this.opts.uriResolver,a,r)),new o({schema:t,schemaId:n,root:e,baseId:a})}return m.call(this,n,u)}}vp.SchemaEnv=o,vp.compileSchema=i,vp.resolveRef=function(e,t,n){var r;n=(0,s.resolveUrl)(this.opts.uriResolver,t,n);const a=e.refs[n];if(a)return a;let i=l.call(this,e,n);if(void 0===i){const s=null===(r=e.localRefs)||void 0===r?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new o({schema:s,schemaId:a,root:e,baseId:t}))}return void 0!==i?e.refs[n]=c.call(this,i):void 0},vp.getCompilingSchema=u,vp.resolveSchema=p;const h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(e,{baseId:t,schema:n,root:a}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(const a of e.fragment.slice(1).split("/")){if("boolean"==typeof n)return;const e=n[(0,r.unescapeFragment)(a)];if(void 0===e)return;const o="object"==typeof(n=e)&&n[this.opts.schemaId];!h.has(a)&&o&&(t=(0,s.resolveUrl)(this.opts.uriResolver,t,o))}let c;if("boolean"!=typeof n&&n.$ref&&!(0,r.schemaHasRulesButRef)(n,this.RULES)){const e=(0,s.resolveUrl)(this.opts.uriResolver,t,n.$ref);c=p.call(this,a,e)}const{schemaId:u}=this.opts;return c=c||new o({schema:n,schemaId:u,root:a,baseId:t}),c.schema!==c.root.schema?c:void 0}return vp}var bp,kp,$p,Ep,Sp,Tp,Op,xp={$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},Ip={},Np={exports:{}};function Pp(){if(kp)return bp;kp=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=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 n(e){let t="",n=0,s=0;for(s=0;s<e.length;s++)if(n=e[s].charCodeAt(0),48!==n){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[s];break}for(s+=1;s<e.length;s++){if(n=e[s].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[s]}return t}const s=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function r(e){return e.length=0,!0}function a(e,t,s){if(e.length){const r=n(e);if(""===r)return s.error=!0,!1;t.push(r),e.length=0}return!0}function o(e){if(function(e){let t=0;for(let n=0;n<e.length;n++)":"===e[n]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const s={error:!1,address:"",zone:""},o=[],i=[];let c=!1,u=!1,d=a;for(let n=0;n<e.length;n++){const a=e[n];if("["!==a&&"]"!==a)if(":"!==a)if("%"===a){if(!d(i,o,s))break;d=r}else i.push(a);else{if(!0===c&&(u=!0),!d(i,o,s))break;if(++t>7){s.error=!0;break}n>0&&":"===e[n-1]&&(c=!0),o.push(":")}}return i.length&&(d===r?s.zone=i.join(""):u?o.push(i.join("")):o.push(n(i))),s.address=o.join(""),s}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}return bp={nonSimpleDomain:s,recomposeAuthority:function(e){const n=[];if(void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host){let s=unescape(e.host);if(!t(s)){const t=o(s);s=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}n.push(s)}return"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){let t=e;const n=[];let s=-1,r=0;for(;r=t.length;){if(1===r){if("."===t)break;if("/"===t){n.push("/");break}n.push(t);break}if(2===r){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){n.push("/");break}}else if(3===r&&"/.."===t){0!==n.length&&n.pop(),n.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==n.length&&n.pop();continue}}if(-1===(s=t.indexOf("/",1))){n.push(t);break}n.push(t.slice(0,s)),t=t.slice(s)}return n.join("")},isIPv4:t,isUUID:e,normalizeIPv6:o,stringArrayToHexStripped:n},bp}function Rp(){return Op||(Op=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=lp();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Ol();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const s=mp(),r=yp(),a=Zl(),o=wp(),i=Ol(),c=dp(),u=Vl(),d=Nl(),l=xp,p=function(){if(Tp)return Ip;Tp=1,Object.defineProperty(Ip,"__esModule",{value:!0});const e=function(){if(Sp)return Np.exports;Sp=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:n,normalizeComponentEncoding:s,isIPv4:r,nonSimpleDomain:a}=Pp(),{SCHEMES:o,getSchemeHandler:i}=function(){if(Ep)return $p;Ep=1;const{isUUID:e}=Pp(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,n=["http","https","ws","wss","urn","urn:uuid"];function s(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function r(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function a(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const o={scheme:"http",domainHost:!0,parse:r,serialize:a},i={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=s(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(s(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:o,https:{scheme:"https",domainHost:o.domainHost,parse:r,serialize:a},ws:i,wss:{scheme:"wss",domainHost:i.domainHost,parse:i.parse,serialize:i.serialize},urn:{scheme:"urn",parse:function(e,n){if(!e.path)return e.error="URN can not be parsed",e;const s=e.path.match(t);if(s){const t=n.scheme||e.scheme||"urn";e.nid=s[1].toLowerCase(),e.nss=s[2];const r=u(`${t}:${n.nid||e.nid}`);e.path=void 0,r&&(e=r.parse(e,n))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",s=e.nid.toLowerCase(),r=u(`${n}:${t.nid||s}`);r&&(e=r.serialize(e,t));const a=e,o=e.nss;return a.path=`${s||t.nid}:${o}`,t.skipEscape=!0,a},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(t,n){const s=t;return s.uuid=s.nss,s.nss=void 0,n.tolerant||s.uuid&&e(s.uuid)||(s.error=s.error||"UUID is not valid."),s},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function u(e){return e&&(c[e]||c[e.toLowerCase()])||void 0}return Object.setPrototypeOf(c,null),$p={wsIsSecure:s,SCHEMES:c,isValidSchemeName:function(e){return-1!==n.indexOf(e)},getSchemeHandler:u}}();function c(e,n,s,r){const a={};return r||(e=l(u(e,s),s),n=l(u(n,s),s)),!(s=s||{}).tolerant&&n.scheme?(a.scheme=n.scheme,a.userinfo=n.userinfo,a.host=n.host,a.port=n.port,a.path=t(n.path||""),a.query=n.query):(void 0!==n.userinfo||void 0!==n.host||void 0!==n.port?(a.userinfo=n.userinfo,a.host=n.host,a.port=n.port,a.path=t(n.path||""),a.query=n.query):(n.path?("/"===n.path[0]?a.path=t(n.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+n.path:a.path=n.path:a.path="/"+n.path,a.path=t(a.path)),a.query=n.query):(a.path=e.path,void 0!==n.query?a.query=n.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=n.fragment,a}function u(e,s){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},a=Object.assign({},s),o=[],c=i(a.scheme||r.scheme);c&&c.serialize&&c.serialize(r,a),void 0!==r.path&&(a.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==a.reference&&r.scheme&&o.push(r.scheme,":");const u=n(r);if(void 0!==u&&("suffix"!==a.reference&&o.push("//"),o.push(u),r.path&&"/"!==r.path[0]&&o.push("/")),void 0!==r.path){let e=r.path;a.absolutePath||c&&c.absolutePath||(e=t(e)),void 0===u&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),o.push(e)}return void 0!==r.query&&o.push("?",r.query),void 0!==r.fragment&&o.push("#",r.fragment),o.join("")}const d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function l(t,n){const s=Object.assign({},n),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let c=!1;"suffix"===s.reference&&(t=s.scheme?s.scheme+":"+t:"//"+t);const u=t.match(d);if(u){if(o.scheme=u[1],o.userinfo=u[3],o.host=u[4],o.port=parseInt(u[5],10),o.path=u[6]||"",o.query=u[7],o.fragment=u[8],isNaN(o.port)&&(o.port=u[5]),o.host)if(!1===r(o.host)){const t=e(o.host);o.host=t.host.toLowerCase(),c=t.isIPV6}else c=!0;void 0!==o.scheme||void 0!==o.userinfo||void 0!==o.host||void 0!==o.port||void 0!==o.query||o.path?void 0===o.scheme?o.reference="relative":void 0===o.fragment?o.reference="absolute":o.reference="uri":o.reference="same-document",s.reference&&"suffix"!==s.reference&&s.reference!==o.reference&&(o.error=o.error||"URI is not a "+s.reference+" reference.");const n=i(s.scheme||o.scheme);if(!(s.unicodeSupport||n&&n.unicodeSupport)&&o.host&&(s.domainHost||n&&n.domainHost)&&!1===c&&a(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(e){o.error=o.error||"Host's domain name can not be converted to ASCII: "+e}(!n||n&&!n.skipNormalize)&&(-1!==t.indexOf("%")&&(void 0!==o.scheme&&(o.scheme=unescape(o.scheme)),void 0!==o.host&&(o.host=unescape(o.host))),o.path&&(o.path=escape(unescape(o.path))),o.fragment&&(o.fragment=encodeURI(decodeURIComponent(o.fragment)))),n&&n.parse&&n.parse(o,s)}else o.error=o.error||"URI can not be parsed.";return o}const p={SCHEMES:o,normalize:function(e,t){return"string"==typeof e?e=u(l(e,t),t):"object"==typeof e&&(e=l(u(e,t),t)),e},resolve:function(e,t,n){const s=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=c(l(e,s),l(t,s),s,!0);return s.skipEscape=!0,u(r,s)},resolveComponent:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=u(s(l(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=u(s(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=u(s(l(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=u(s(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:u,parse:l};return Np.exports=p,Np.exports.default=p,Np.exports.fastUri=p,Np.exports}();return e.code='require("ajv/dist/runtime/uri").default',Ip.default=e,Ip}(),h=(e,t)=>new RegExp(e,t);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={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."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function _(e){var t,n,s,r,a,o,i,c,u,d,l,m,f,g,y,_,v,w,b,k,$,E,S,T,O;const x=e.strict,I=null===(t=e.code)||void 0===t?void 0:t.optimize,N=!0===I||void 0===I?1:I||0,P=null!==(s=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==s?s:h,R=null!==(r=e.uriResolver)&&void 0!==r?r:p.default;return{strictSchema:null===(o=null!==(a=e.strictSchema)&&void 0!==a?a:x)||void 0===o||o,strictNumbers:null===(c=null!==(i=e.strictNumbers)&&void 0!==i?i:x)||void 0===c||c,strictTypes:null!==(d=null!==(u=e.strictTypes)&&void 0!==u?u:x)&&void 0!==d?d:"log",strictTuples:null!==(m=null!==(l=e.strictTuples)&&void 0!==l?l:x)&&void 0!==m?m:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:x)&&void 0!==g&&g,code:e.code?{...e.code,optimize:N,regExp:P}:{optimize:N,regExp:P},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(_=e.loopEnum)&&void 0!==_?_:200,meta:null===(v=e.meta)||void 0===v||v,messages:null===(w=e.messages)||void 0===w||w,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===($=e.addUsedSchema)||void 0===$||$,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(O=e.int32range)||void 0===O||O,uriResolver:R}}class v{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:f,es5:t,lines:n}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),w.call(this,g,e,"NOT SUPPORTED"),w.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=S.call(this),e.formats&&$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&E.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let s=l;"id"===n&&(s={...l},s.id=s.$id,delete s.$id),t&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const s=n(t);return"$async"in n||(this.errors=n.errors),s}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return s.call(this,e,t);async function s(e,t){await a.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await s.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof r.default))throw t;return i.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function i({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const n=await u.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function u(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,s);return this}let r;if("object"==typeof e){const{schemaId:t}=this.opts;if(r=e[t],void 0!==r&&"string"!=typeof r)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||r),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,s,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)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;const s=this.validate(n,e);if(!s&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return s}getSchema(e){let t;for(;"string"==typeof(t=b.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,s=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,s,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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":{const t=b.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(x.call(this,n,t),!t)return(0,d.eachItem)(n,e=>I.call(this,e)),this;P.call(this,t);const s={...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(n,0===s.type.length?e=>I.call(this,e,s):e=>s.type.forEach(t=>I.call(this,e,s,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const s of t){const t=s.split("/").slice(1);let r=e;for(const e of t)r=r[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:s}=t.definition,a=r[e];s&&a&&(r[e]=C(a))}}return e}_removeAllSchemas(e,t){for(const n in e){const s=e[n];t&&!t.test(n)||("string"==typeof s?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,t,n,s=this.opts.validateSchema,r=this.opts.addUsedSchema){let a;const{schemaId:i}=this.opts;if("object"==typeof e)a=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let u=this._cache.get(e);if(void 0!==u)return u;n=(0,c.normalizeId)(a||n);const d=c.getSchemaRefs.call(this,e,n);return u=new o.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:n,localRefs:d}),this._cache.set(u.schema,u),r&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),s&&this.validateSchema(e,!0),u}_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):o.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}}function w(e,t,n,s="error"){for(const r in e){const a=r;a in t&&this.logger[s](`${n}: option ${r}. ${e[a]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function $(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function S(){const e={...this.opts};for(const t of m)delete e[t];return e}v.ValidationError=s.default,v.MissingRefError=r.default,e.default=v;const T={log(){},warn(){},error(){}},O=/^[a-z_$][a-z0-9_$:-]*$/i;function x(e,t){const{RULES:n}=this;if((0,d.eachItem)(e,e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!O.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function I(e,t,n){var s;const r=null==t?void 0:t.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:a}=this;let o=r?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;const i={keyword:e,definition:{...t,type:(0,u.getJSONTypes)(t.type),schemaType:(0,u.getJSONTypes)(t.schemaType)}};t.before?N.call(this,o,i,t.before):o.rules.push(i),a.all[e]=i,null===(s=t.implements)||void 0===s||s.forEach(e=>this.addKeyword(e))}function N(e,t,n){const s=e.rules.findIndex(e=>e.keyword===n);s>=0?e.rules.splice(s,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function P(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=C(t)),e.validateSchema=this.compile(t,!0))}const R={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function C(e){return{anyOf:[e,R]}}}(gl)),gl}var Cp,jp,zp,Ap={},Dp={},Mp={},Lp={};var Zp,Fp,Up,qp,Hp={},Vp={},Jp={},Kp={},Bp={};var Wp,Gp,Xp,Yp={},Qp={},eh={};var th,nh,sh,rh={},ah={},oh={};function ih(){if(nh)return oh;nh=1,Object.defineProperty(oh,"__esModule",{value:!0});const e=rp();return e.code='require("ajv/dist/runtime/equal").default',oh.default=e,oh}function ch(){if(sh)return ah;sh=1,Object.defineProperty(ah,"__esModule",{value:!0});const e=Vl(),t=Ol(),n=Nl(),s=ih(),r={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:n}})=>t.str`must NOT have duplicate items (items ## ${n} and ${e} are identical)`,params:({params:{i:e,j:n}})=>t._`{i: ${e}, j: ${n}}`},code(r){const{gen:a,data:o,$data:i,schema:c,parentSchema:u,schemaCode:d,it:l}=r;if(!i&&!c)return;const p=a.let("valid"),h=u.items?(0,e.getSchemaTypes)(u.items):[];function m(n,s){const i=a.name("item"),c=(0,e.checkDataTypes)(h,i,l.opts.strictNumbers,e.DataType.Wrong),u=a.const("indices",t._`{}`);a.for(t._`;${n}--;`,()=>{a.let(i,t._`${o}[${n}]`),a.if(c,t._`continue`),h.length>1&&a.if(t._`typeof ${i} == "string"`,t._`${i} += "_"`),a.if(t._`typeof ${u}[${i}] == "number"`,()=>{a.assign(s,t._`${u}[${i}]`),r.error(),a.assign(p,!1).break()}).code(t._`${u}[${i}] = ${n}`)})}function f(e,i){const c=(0,n.useFunc)(a,s.default),u=a.name("outer");a.label(u).for(t._`;${e}--;`,()=>a.for(t._`${i} = ${e}; ${i}--;`,()=>a.if(t._`${c}(${o}[${e}], ${o}[${i}])`,()=>{r.error(),a.assign(p,!1).break(u)})))}r.block$data(p,function(){const e=a.let("i",t._`${o}.length`),n=a.let("j");r.setParams({i:e,j:n}),a.assign(p,!0),a.if(t._`${e} > 1`,()=>(h.length>0&&!h.some(e=>"object"===e||"array"===e)?m:f)(e,n))},t._`${d} === false`),r.ok(p)}};return ah.default=r,ah}var uh,dh,lh,ph={},hh={};function mh(){if(lh)return Hp;lh=1,Object.defineProperty(Hp,"__esModule",{value:!0});const e=function(){if(Zp)return Vp;Zp=1,Object.defineProperty(Vp,"__esModule",{value:!0});const e=Ol(),t=e.operators,n={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},s={message:({keyword:t,schemaCode:s})=>e.str`must be ${n[t].okStr} ${s}`,params:({keyword:t,schemaCode:s})=>e._`{comparison: ${n[t].okStr}, limit: ${s}}`},r={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:s,code(t){const{keyword:s,data:r,schemaCode:a}=t;t.fail$data(e._`${r} ${n[s].fail} ${a} || isNaN(${r})`)}};return Vp.default=r,Vp}(),t=function(){if(Fp)return Jp;Fp=1,Object.defineProperty(Jp,"__esModule",{value:!0});const e=Ol(),t={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>e.str`must be multiple of ${t}`,params:({schemaCode:t})=>e._`{multipleOf: ${t}}`},code(t){const{gen:n,data:s,schemaCode:r,it:a}=t,o=a.opts.multipleOfPrecision,i=n.let("res"),c=o?e._`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:e._`${i} !== parseInt(${i})`;t.fail$data(e._`(${r} === 0 || (${i} = ${s}/${r}, ${c}))`)}};return Jp.default=t,Jp}(),n=function(){if(qp)return Kp;qp=1,Object.defineProperty(Kp,"__esModule",{value:!0});const e=Ol(),t=Nl(),n=function(){if(Up)return Bp;function e(e){const t=e.length;let n,s=0,r=0;for(;r<t;)s++,n=e.charCodeAt(r++),n>=55296&&n<=56319&&r<t&&(n=e.charCodeAt(r),56320==(64512&n)&&r++);return s}return Up=1,Object.defineProperty(Bp,"__esModule",{value:!0}),Bp.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',Bp}(),s={message({keyword:t,schemaCode:n}){const s="maxLength"===t?"more":"fewer";return e.str`must NOT have ${s} than ${n} characters`},params:({schemaCode:t})=>e._`{limit: ${t}}`},r={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:s,code(s){const{keyword:r,data:a,schemaCode:o,it:i}=s,c="maxLength"===r?e.operators.GT:e.operators.LT,u=!1===i.opts.unicode?e._`${a}.length`:e._`${(0,t.useFunc)(s.gen,n.default)}(${a})`;s.fail$data(e._`${u} ${c} ${o}`)}};return Kp.default=r,Kp}(),s=function(){if(Wp)return Yp;Wp=1,Object.defineProperty(Yp,"__esModule",{value:!0});const e=Yl(),t=Ol(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match pattern "${e}"`,params:({schemaCode:e})=>t._`{pattern: ${e}}`},code(n){const{data:s,$data:r,schema:a,schemaCode:o,it:i}=n,c=i.opts.unicodeRegExp?"u":"",u=r?t._`(new RegExp(${o}, ${c}))`:(0,e.usePattern)(n,a);n.fail$data(t._`!${u}.test(${s})`)}};return Yp.default=n,Yp}(),r=function(){if(Gp)return Qp;Gp=1,Object.defineProperty(Qp,"__esModule",{value:!0});const e=Ol(),t={message({keyword:t,schemaCode:n}){const s="maxProperties"===t?"more":"fewer";return e.str`must NOT have ${s} than ${n} properties`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:s,schemaCode:r}=t,a="maxProperties"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`Object.keys(${s}).length ${a} ${r}`)}};return Qp.default=n,Qp}(),a=function(){if(Xp)return eh;Xp=1,Object.defineProperty(eh,"__esModule",{value:!0});const e=Yl(),t=Ol(),n=Nl(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>t.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>t._`{missingProperty: ${e}}`},code(s){const{gen:r,schema:a,schemaCode:o,data:i,$data:c,it:u}=s,{opts:d}=u;if(!c&&0===a.length)return;const l=a.length>=d.loopRequired;if(u.allErrors?function(){if(l||c)s.block$data(t.nil,p);else for(const t of a)(0,e.checkReportMissingProp)(s,t)}():function(){const n=r.let("missing");if(l||c){const a=r.let("valid",!0);s.block$data(a,()=>function(n,a){s.setParams({missingProperty:n}),r.forOf(n,o,()=>{r.assign(a,(0,e.propertyInData)(r,i,n,d.ownProperties)),r.if((0,t.not)(a),()=>{s.error(),r.break()})},t.nil)}(n,a)),s.ok(a)}else r.if((0,e.checkMissingProp)(s,a,n)),(0,e.reportMissingProp)(s,n),r.else()}(),d.strictRequired){const e=s.parentSchema.properties,{definedProperties:t}=s.it;for(const s of a)if(void 0===(null==e?void 0:e[s])&&!t.has(s)){const e=`required property "${s}" is not defined at "${u.schemaEnv.baseId+u.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(u,e,u.opts.strictRequired)}}function p(){r.forOf("prop",o,t=>{s.setParams({missingProperty:t}),r.if((0,e.noPropertyInData)(r,i,t,d.ownProperties),()=>s.error())})}}};return eh.default=s,eh}(),o=function(){if(th)return rh;th=1,Object.defineProperty(rh,"__esModule",{value:!0});const e=Ol(),t={message({keyword:t,schemaCode:n}){const s="maxItems"===t?"more":"fewer";return e.str`must NOT have ${s} than ${n} items`},params:({schemaCode:t})=>e._`{limit: ${t}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:t,code(t){const{keyword:n,data:s,schemaCode:r}=t,a="maxItems"===n?e.operators.GT:e.operators.LT;t.fail$data(e._`${s}.length ${a} ${r}`)}};return rh.default=n,rh}(),i=ch(),c=function(){if(uh)return ph;uh=1,Object.defineProperty(ph,"__esModule",{value:!0});const e=Ol(),t=Nl(),n=ih(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>e._`{allowedValue: ${t}}`},code(s){const{gen:r,data:a,$data:o,schemaCode:i,schema:c}=s;o||c&&"object"==typeof c?s.fail$data(e._`!${(0,t.useFunc)(r,n.default)}(${a}, ${i})`):s.fail(e._`${c} !== ${a}`)}};return ph.default=s,ph}(),u=function(){if(dh)return hh;dh=1,Object.defineProperty(hh,"__esModule",{value:!0});const e=Ol(),t=Nl(),n=ih(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>e._`{allowedValues: ${t}}`},code(s){const{gen:r,data:a,$data:o,schema:i,schemaCode:c,it:u}=s;if(!o&&0===i.length)throw new Error("enum must have non-empty array");const d=i.length>=u.opts.loopEnum;let l;const p=()=>null!=l?l:l=(0,t.useFunc)(r,n.default);let h;if(d||o)h=r.let("valid"),s.block$data(h,function(){r.assign(h,!1),r.forOf("v",c,t=>r.if(e._`${p()}(${a}, ${t})`,()=>r.assign(h,!0).break()))});else{if(!Array.isArray(i))throw new Error("ajv implementation error");const t=r.const("vSchema",c);h=(0,e.or)(...i.map((n,s)=>function(t,n){const s=i[n];return"object"==typeof s&&null!==s?e._`${p()}(${a}, ${t}[${n}])`:e._`${a} === ${s}`}(t,s)))}s.pass(h)}};return hh.default=s,hh}(),d=[e.default,t.default,n.default,s.default,r.default,a.default,o.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,u.default];return Hp.default=d,Hp}var fh,gh={},yh={};function _h(){if(fh)return yh;fh=1,Object.defineProperty(yh,"__esModule",{value:!0}),yh.validateAdditionalItems=void 0;const e=Ol(),t=Nl(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{parentSchema:n,it:r}=e,{items:a}=n;Array.isArray(a)?s(e,a):(0,t.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function s(n,s){const{gen:r,schema:a,data:o,keyword:i,it:c}=n;c.items=!0;const u=r.const("len",e._`${o}.length`);if(!1===a)n.setParams({len:s.length}),n.pass(e._`${u} <= ${s.length}`);else if("object"==typeof a&&!(0,t.alwaysValidSchema)(c,a)){const a=r.var("valid",e._`${u} <= ${s.length}`);r.if((0,e.not)(a),()=>function(a){r.forRange("i",s.length,u,s=>{n.subschema({keyword:i,dataProp:s,dataPropType:t.Type.Num},a),c.allErrors||r.if((0,e.not)(a),()=>r.break())})}(a)),n.ok(a)}}return yh.validateAdditionalItems=s,yh.default=n,yh}var vh,wh,bh={},kh={};function $h(){if(vh)return kh;vh=1,Object.defineProperty(kh,"__esModule",{value:!0}),kh.validateTuple=void 0;const e=Ol(),t=Nl(),n=Yl(),s={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:s,it:a}=e;if(Array.isArray(s))return r(e,"additionalItems",s);a.items=!0,(0,t.alwaysValidSchema)(a,s)||e.ok((0,n.validateArray)(e))}};function r(n,s,r=n.schema){const{gen:a,parentSchema:o,data:i,keyword:c,it:u}=n;!function(e){const{opts:n,errSchemaPath:a}=u,o=r.length,i=o===e.minItems&&(o===e.maxItems||!1===e[s]);if(n.strictTuples&&!i){const e=`"${c}" is ${o}-tuple, but minItems or maxItems/${s} are not specified or different at path "${a}"`;(0,t.checkStrictMode)(u,e,n.strictTuples)}}(o),u.opts.unevaluated&&r.length&&!0!==u.items&&(u.items=t.mergeEvaluated.items(a,r.length,u.items));const d=a.name("valid"),l=a.const("len",e._`${i}.length`);r.forEach((s,r)=>{(0,t.alwaysValidSchema)(u,s)||(a.if(e._`${l} > ${r}`,()=>n.subschema({keyword:c,schemaProp:r,dataProp:r},d)),n.ok(d))})}return kh.validateTuple=r,kh.default=s,kh}var Eh,Sh,Th={},Oh={};var xh,Ih={};var Nh,Ph,Rh={},Ch={};function jh(){if(Ph)return Ch;Ph=1,Object.defineProperty(Ch,"__esModule",{value:!0});const e=Yl(),t=Ol(),n=zl(),s=Nl(),r={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>t._`{additionalProperty: ${e.additionalProperty}}`},code(r){const{gen:a,schema:o,parentSchema:i,data:c,errsCount:u,it:d}=r;if(!u)throw new Error("ajv implementation error");const{allErrors:l,opts:p}=d;if(d.props=!0,"all"!==p.removeAdditional&&(0,s.alwaysValidSchema)(d,o))return;const h=(0,e.allSchemaProperties)(i.properties),m=(0,e.allSchemaProperties)(i.patternProperties);function f(e){a.code(t._`delete ${c}[${e}]`)}function g(e){if("all"===p.removeAdditional||p.removeAdditional&&!1===o)f(e);else{if(!1===o)return r.setParams({additionalProperty:e}),r.error(),void(l||a.break());if("object"==typeof o&&!(0,s.alwaysValidSchema)(d,o)){const n=a.name("valid");"failing"===p.removeAdditional?(y(e,n,!1),a.if((0,t.not)(n),()=>{r.reset(),f(e)})):(y(e,n),l||a.if((0,t.not)(n),()=>a.break()))}}}function y(e,t,n){const a={keyword:"additionalProperties",dataProp:e,dataPropType:s.Type.Str};!1===n&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(a,t)}a.forIn("key",c,n=>{h.length||m.length?a.if(function(n){let o;if(h.length>8){const t=(0,s.schemaRefOrVal)(d,i.properties,"properties");o=(0,e.isOwnProperty)(a,t,n)}else o=h.length?(0,t.or)(...h.map(e=>t._`${n} === ${e}`)):t.nil;return m.length&&(o=(0,t.or)(o,...m.map(s=>t._`${(0,e.usePattern)(r,s)}.test(${n})`))),(0,t.not)(o)}(n),()=>g(n)):g(n)}),r.ok(t._`${u} === ${n.default.errors}`)}};return Ch.default=r,Ch}var zh,Ah,Dh,Mh,Lh,Zh,Fh,Uh,qh,Hh={},Vh={},Jh={},Kh={},Bh={},Wh={},Gh={},Xh={};function Yh(){if(qh)return gh;qh=1,Object.defineProperty(gh,"__esModule",{value:!0});const e=_h(),t=function(){if(wh)return bh;wh=1,Object.defineProperty(bh,"__esModule",{value:!0});const e=$h(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,e.validateTuple)(t,"items")};return bh.default=t,bh}(),n=$h(),s=function(){if(Eh)return Th;Eh=1,Object.defineProperty(Th,"__esModule",{value:!0});const e=Ol(),t=Nl(),n=Yl(),s=_h(),r={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>e.str`must NOT have more than ${t} items`,params:({params:{len:t}})=>e._`{limit: ${t}}`},code(e){const{schema:r,parentSchema:a,it:o}=e,{prefixItems:i}=a;o.items=!0,(0,t.alwaysValidSchema)(o,r)||(i?(0,s.validateAdditionalItems)(e,i):e.ok((0,n.validateArray)(e)))}};return Th.default=r,Th}(),r=function(){if(Sh)return Oh;Sh=1,Object.defineProperty(Oh,"__esModule",{value:!0});const e=Ol(),t=Nl(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:n}})=>void 0===n?e.str`must contain at least ${t} valid item(s)`:e.str`must contain at least ${t} and no more than ${n} valid item(s)`,params:({params:{min:t,max:n}})=>void 0===n?e._`{minContains: ${t}}`:e._`{minContains: ${t}, maxContains: ${n}}`},code(n){const{gen:s,schema:r,parentSchema:a,data:o,it:i}=n;let c,u;const{minContains:d,maxContains:l}=a;i.opts.next?(c=void 0===d?1:d,u=l):c=1;const p=s.const("len",e._`${o}.length`);if(n.setParams({min:c,max:u}),void 0===u&&0===c)return void(0,t.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==u&&c>u)return(0,t.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),void n.fail();if((0,t.alwaysValidSchema)(i,r)){let t=e._`${p} >= ${c}`;return void 0!==u&&(t=e._`${t} && ${p} <= ${u}`),void n.pass(t)}i.items=!0;const h=s.name("valid");function m(){const t=s.name("_valid"),n=s.let("count",0);f(t,()=>s.if(t,()=>function(t){s.code(e._`${t}++`),void 0===u?s.if(e._`${t} >= ${c}`,()=>s.assign(h,!0).break()):(s.if(e._`${t} > ${u}`,()=>s.assign(h,!1).break()),1===c?s.assign(h,!0):s.if(e._`${t} >= ${c}`,()=>s.assign(h,!0)))}(n)))}function f(e,r){s.forRange("i",0,p,s=>{n.subschema({keyword:"contains",dataProp:s,dataPropType:t.Type.Num,compositeRule:!0},e),r()})}void 0===u&&1===c?f(h,()=>s.if(h,()=>s.break())):0===c?(s.let(h,!0),void 0!==u&&s.if(e._`${o}.length > 0`,m)):(s.let(h,!1),m()),n.result(h,()=>n.reset())}};return Oh.default=n,Oh}(),a=(xh||(xh=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ol(),n=Nl(),s=Yl();e.error={message:({params:{property:e,depsCount:n,deps:s}})=>{const r=1===n?"property":"properties";return t.str`must have ${r} ${s} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:s,missingProperty:r}})=>t._`{property: ${e},
6
+ missingProperty: ${r},
7
7
  depsCount: ${n},
8
- deps: ${r}}`};const s={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const r in e)"__proto__"!==r&&((Array.isArray(e[r])?t:n)[r]=e[r]);return[t,n]}(e);a(e,t),o(e,n)}};function a(e,n=e.schema){const{gen:s,data:a,it:o}=e;if(0===Object.keys(n).length)return;const i=s.let("missing");for(const c in n){const u=n[c];if(0===u.length)continue;const d=(0,r.propertyInData)(s,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),o.allErrors?s.if(d,()=>{for(const t of u)(0,r.checkReportMissingProp)(e,t)}):(s.if(t._`${d} && (${(0,r.checkMissingProp)(e,u,i)})`),(0,r.reportMissingProp)(e,i),s.else())}}function o(e,t=e.schema){const{gen:s,data:a,keyword:o,it:i}=e,c=s.name("valid");for(const u in t)(0,n.alwaysValidSchema)(i,t[u])||(s.if((0,r.propertyInData)(s,a,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:o,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>s.var(c,!0)),e.ok(c))}e.validatePropertyDeps=a,e.validateSchemaDeps=o,e.default=s}(Eh)),Eh),o=function(){if(Th)return Oh;Th=1,Object.defineProperty(Oh,"__esModule",{value:!0});const e=$l(),t=Tl(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(n){const{gen:r,schema:s,data:a,it:o}=n;if((0,t.alwaysValidSchema)(o,s))return;const i=r.name("valid");r.forIn("key",a,t=>{n.setParams({propertyName:t}),n.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},i),r.if((0,e.not)(i),()=>{n.error(!0),o.allErrors||r.break()})}),n.ok(i)}};return Oh.default=n,Oh}(),i=Ih(),c=function(){if(Ph)return Lh;Ph=1,Object.defineProperty(Lh,"__esModule",{value:!0});const e=ip(),t=Bl(),n=Tl(),r=Ih(),s={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:o,parentSchema:i,data:c,it:u}=s;"all"===u.opts.removeAdditional&&void 0===i.additionalProperties&&r.default.code(new e.KeywordCxt(u,r.default,"additionalProperties"));const d=(0,t.allSchemaProperties)(o);for(const e of d)u.definedProperties.add(e);u.opts.unevaluated&&d.length&&!0!==u.props&&(u.props=n.mergeEvaluated.props(a,(0,n.toHash)(d),u.props));const l=d.filter(e=>!(0,n.alwaysValidSchema)(u,o[e]));if(0===l.length)return;const p=a.name("valid");for(const e of l)h(e)?m(e):(a.if((0,t.propertyInData)(a,c,e,u.opts.ownProperties)),m(e),u.allErrors||a.else().var(p,!0),a.endIf()),s.it.definedProperties.add(e),s.ok(p);function h(e){return u.opts.useDefaults&&!u.compositeRule&&void 0!==o[e].default}function m(e){s.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return Lh.default=s,Lh}(),u=function(){if(Rh)return Fh;Rh=1,Object.defineProperty(Fh,"__esModule",{value:!0});const e=Bl(),t=$l(),n=Tl(),r=Tl(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:o,data:i,parentSchema:c,it:u}=s,{opts:d}=u,l=(0,e.allSchemaProperties)(o),p=l.filter(e=>(0,n.alwaysValidSchema)(u,o[e]));if(0===l.length||p.length===l.length&&(!u.opts.unevaluated||!0===u.props))return;const h=d.strictSchema&&!d.allowMatchingProperties&&c.properties,m=a.name("valid");!0===u.props||u.props instanceof t.Name||(u.props=(0,r.evaluatedPropsToName)(a,u.props));const{props:f}=u;function g(e){for(const t in h)new RegExp(e).test(t)&&(0,n.checkStrictMode)(u,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){a.forIn("key",i,o=>{a.if(t._`${(0,e.usePattern)(s,n)}.test(${o})`,()=>{const e=p.includes(n);e||s.subschema({keyword:"patternProperties",schemaProp:n,dataProp:o,dataPropType:r.Type.Str},m),u.opts.unevaluated&&!0!==f?a.assign(t._`${f}[${o}]`,!0):e||u.allErrors||a.if((0,t.not)(m),()=>a.break())})})}!function(){for(const e of l)h&&g(e),u.allErrors?y(e):(a.var(m,!0),y(e),a.if(m))}()}};return Fh.default=s,Fh}(),d=function(){if(Ch)return qh;Ch=1,Object.defineProperty(qh,"__esModule",{value:!0});const e=Tl(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:n,schema:r,it:s}=t;if((0,e.alwaysValidSchema)(s,r))return void t.fail();const a=n.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),t.failResult(a,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return qh.default=t,qh}(),l=function(){if(jh)return Uh;jh=1,Object.defineProperty(Uh,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Bl().validateUnion,error:{message:"must match a schema in anyOf"}};return Uh.default=e,Uh}(),p=function(){if(zh)return Vh;zh=1,Object.defineProperty(Vh,"__esModule",{value:!0});const e=$l(),t=Tl(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(n){const{gen:r,schema:s,parentSchema:a,it:o}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");if(o.opts.discriminator&&a.discriminator)return;const i=s,c=r.let("valid",!1),u=r.let("passing",null),d=r.name("_valid");n.setParams({passing:u}),r.block(function(){i.forEach((s,a)=>{let i;(0,t.alwaysValidSchema)(o,s)?r.var(d,!0):i=n.subschema({keyword:"oneOf",schemaProp:a,compositeRule:!0},d),a>0&&r.if(e._`${d} && ${c}`).assign(c,!1).assign(u,e._`[${u}, ${a}]`).else(),r.if(d,()=>{r.assign(c,!0),r.assign(u,a),i&&n.mergeEvaluated(i,e.Name)})})}),n.result(c,()=>n.reset(),()=>n.error(!0))}};return Vh.default=n,Vh}(),h=function(){if(Ah)return Hh;Ah=1,Object.defineProperty(Hh,"__esModule",{value:!0});const e=Tl(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:n,schema:r,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const a=n.name("valid");r.forEach((n,r)=>{if((0,e.alwaysValidSchema)(s,n))return;const o=t.subschema({keyword:"allOf",schemaProp:r},a);t.ok(a),t.mergeEvaluated(o)})}};return Hh.default=t,Hh}(),m=function(){if(Mh)return Jh;Mh=1,Object.defineProperty(Jh,"__esModule",{value:!0});const e=$l(),t=Tl(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(n){const{gen:s,parentSchema:a,it:o}=n;void 0===a.then&&void 0===a.else&&(0,t.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const i=r(o,"then"),c=r(o,"else");if(!i&&!c)return;const u=s.let("valid",!0),d=s.name("_valid");if(function(){const e=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);n.mergeEvaluated(e)}(),n.reset(),i&&c){const e=s.let("ifClause");n.setParams({ifClause:e}),s.if(d,l("then",e),l("else",e))}else i?s.if(d,l("then")):s.if((0,e.not)(d),l("else"));function l(t,r){return()=>{const a=n.subschema({keyword:t},d);s.assign(u,d),n.mergeValidEvaluated(a,u),r?s.assign(r,e._`${t}`):n.setParams({ifClause:t})}}n.pass(u,()=>n.error(!0))}};function r(e,n){const r=e.schema[n];return void 0!==r&&!(0,t.alwaysValidSchema)(e,r)}return Jh.default=n,Jh}(),f=function(){if(Dh)return Kh;Dh=1,Object.defineProperty(Kh,"__esModule",{value:!0});const e=Tl(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:n,it:r}){void 0===n.if&&(0,e.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};return Kh.default=t,Kh}();return ph.default=function(g=!1){const y=[d.default,l.default,p.default,h.default,m.default,f.default,o.default,i.default,a.default,c.default,u.default];return g?y.push(t.default,r.default):y.push(e.default,n.default),y.push(s.default),y},ph}var Wh,Gh,Xh={},Yh={};function Qh(){if(Wh)return Yh;Wh=1,Object.defineProperty(Yh,"__esModule",{value:!0});const e=$l(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,n){const{gen:r,data:s,$data:a,schema:o,schemaCode:i,it:c}=t,{opts:u,errSchemaPath:d,schemaEnv:l,self:p}=c;u.validateFormats&&(a?function(){const a=r.scopeValue("formats",{ref:p.formats,code:u.code.formats}),o=r.const("fDef",e._`${a}[${i}]`),c=r.let("fType"),d=r.let("format");r.if(e._`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,e._`${o}.type || "string"`).assign(d,e._`${o}.validate`),()=>r.assign(c,e._`"string"`).assign(d,o)),t.fail$data((0,e.or)(!1===u.strictSchema?e.nil:e._`${i} && !${d}`,function(){const t=l.$async?e._`(${o}.async ? await ${d}(${s}) : ${d}(${s}))`:e._`${d}(${s})`,r=e._`(typeof ${d} == "function" ? ${t} : ${d}.test(${s}))`;return e._`${d} && ${d} !== true && ${c} === ${n} && !${r}`}()))}():function(){const a=p.formats[o];if(!a)return void function(){if(!1!==u.strictSchema)throw new Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${d}"`}p.logger.warn(e())}();if(!0===a)return;const[i,c,h]=function(t){const n=t instanceof RegExp?(0,e.regexpCode)(t):u.code.formats?e._`${u.code.formats}${(0,e.getProperty)(o)}`:void 0,s=r.scopeValue("formats",{key:o,ref:t,code:n});return"object"!=typeof t||t instanceof RegExp?["string",t,s]:[t.type||"string",t.validate,e._`${s}.validate`]}(a);i===n&&t.pass(function(){if("object"==typeof a&&!(a instanceof RegExp)&&a.async){if(!l.$async)throw new Error("async format in sync schema");return e._`await ${h}(${s})`}return"function"==typeof c?e._`${h}(${s})`:e._`${h}.test(${s})`}())}())}};return Yh.default=t,Yh}var em,tm,nm={};function rm(){if(tm)return Rp;tm=1,Object.defineProperty(Rp,"__esModule",{value:!0});const e=function(){if(Pp)return Cp;Pp=1,Object.defineProperty(Cp,"__esModule",{value:!0});const e=function(){if(Np)return jp;Np=1,Object.defineProperty(jp,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return jp.default=e,jp}(),t=function(){if(Ip)return zp;Ip=1,Object.defineProperty(zp,"__esModule",{value:!0}),zp.callRef=zp.getValidate=void 0;const e=hp(),t=Bl(),n=$l(),r=Pl(),s=gp(),a=Tl(),o={keyword:"$ref",schemaType:"string",code(t){const{gen:r,schema:a,it:o}=t,{baseId:u,schemaEnv:d,validateName:l,opts:p,self:h}=o,{root:m}=d;if(("#"===a||"#/"===a)&&u===m.baseId)return function(){if(d===m)return c(t,l,d,d.$async);const e=r.scopeValue("root",{ref:m});return c(t,n._`${e}.validate`,m,m.$async)}();const f=s.resolveRef.call(h,m,u,a);if(void 0===f)throw new e.default(o.opts.uriResolver,u,a);return f instanceof s.SchemaEnv?function(e){const n=i(t,e);c(t,n,e,e.$async)}(f):function(e){const s=r.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,n.stringify)(e)}:{ref:e}),o=r.name("valid"),i=t.subschema({schema:e,dataTypes:[],schemaPath:n.nil,topSchemaRef:s,errSchemaPath:a},o);t.mergeEvaluated(i),t.ok(o)}(f)}};function i(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):n._`${r.scopeValue("wrapper",{ref:t})}.validate`}function c(e,s,o,i){const{gen:c,it:u}=e,{allErrors:d,schemaEnv:l,opts:p}=u,h=p.passContext?r.default.this:n.nil;function m(e){const t=n._`${e}.errors`;c.assign(r.default.vErrors,n._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`),c.assign(r.default.errors,n._`${r.default.vErrors}.length`)}function f(e){var t;if(!u.opts.unevaluated)return;const r=null===(t=null==o?void 0:o.validate)||void 0===t?void 0:t.evaluated;if(!0!==u.props)if(r&&!r.dynamicProps)void 0!==r.props&&(u.props=a.mergeEvaluated.props(c,r.props,u.props));else{const t=c.var("props",n._`${e}.evaluated.props`);u.props=a.mergeEvaluated.props(c,t,u.props,n.Name)}if(!0!==u.items)if(r&&!r.dynamicItems)void 0!==r.items&&(u.items=a.mergeEvaluated.items(c,r.items,u.items));else{const t=c.var("items",n._`${e}.evaluated.items`);u.items=a.mergeEvaluated.items(c,t,u.items,n.Name)}}i?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const r=c.let("valid");c.try(()=>{c.code(n._`await ${(0,t.callValidateCode)(e,s,h)}`),f(s),d||c.assign(r,!0)},e=>{c.if(n._`!(${e} instanceof ${u.ValidationError})`,()=>c.throw(e)),m(e),d||c.assign(r,!1)}),e.ok(r)}():e.result((0,t.callValidateCode)(e,s,h),()=>f(s),()=>m(s))}return zp.getValidate=i,zp.callRef=c,zp.default=o,zp}(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Cp.default=n,Cp}(),t=dh(),n=Bh(),r=function(){if(Gh)return Xh;Gh=1,Object.defineProperty(Xh,"__esModule",{value:!0});const e=[Qh().default];return Xh.default=e,Xh}(),s=(em||(em=1,Object.defineProperty(nm,"__esModule",{value:!0}),nm.contentVocabulary=nm.metadataVocabulary=void 0,nm.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],nm.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),nm),a=[e.default,t.default,(0,n.default)(),r.default,s.metadataVocabulary,s.contentVocabulary];return Rp.default=a,Rp}var sm,am,om={},im={};var cm,um={$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};function dm(){return cm||(cm=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=Op(),r=rm(),s=function(){if(am)return om;am=1,Object.defineProperty(om,"__esModule",{value:!0});const e=$l(),t=(sm||(sm=1,Object.defineProperty(im,"__esModule",{value:!0}),im.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(im.DiscrError=n={}))),im);var n;const r=gp(),s=hp(),a=Tl(),o={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:n}})=>e===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`,params:({params:{discrError:t,tag:n,tagName:r}})=>e._`{error: ${t}, tag: ${r}, tagValue: ${n}}`},code(n){const{gen:o,data:i,schema:c,parentSchema:u,it:d}=n,{oneOf:l}=u;if(!d.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const h=o.let("valid",!1),m=o.const("tag",e._`${i}${(0,e.getProperty)(p)}`);function f(t){const r=o.name("valid"),s=n.subschema({keyword:"oneOf",schemaProp:t},r);return n.mergeEvaluated(s,e.Name),r}o.if(e._`typeof ${m} == "string"`,()=>function(){const i=function(){var e;const t={},n=i(u);let o=!0;for(let t=0;t<l.length;t++){let u=l[t];if((null==u?void 0:u.$ref)&&!(0,a.schemaHasRulesButRef)(u,d.self.RULES)){const e=u.$ref;if(u=r.resolveRef.call(d.self,d.schemaEnv.root,d.baseId,e),u instanceof r.SchemaEnv&&(u=u.schema),void 0===u)throw new s.default(d.opts.uriResolver,d.baseId,e)}const h=null===(e=null==u?void 0:u.properties)||void 0===e?void 0:e[p];if("object"!=typeof h)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);o=o&&(n||i(u)),c(h,t)}if(!o)throw new Error(`discriminator: "${p}" must be required`);return t;function i({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)h(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const n of e.enum)h(n,t)}}function h(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=n}}();o.if(!1);for(const t in i)o.elseIf(e._`${m} === ${t}`),o.assign(h,f(i[t]));o.else(),n.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),o.endIf()}(),()=>n.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),n.ok(h)}};return om.default=o,om}(),a=um,o=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=ip();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=$l();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var l=dp();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return l.default}});var p=hp();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(ll,ll.exports)),ll.exports}var lm,pm,hm,mm=ul(dm()),fm={exports:{}},gm={},ym={},_m=(hm||(hm=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=(lm||(lm=1,function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(s,a),time:t(i(!0),c),"date-time":t(l(!0),p),"iso-time":t(i(),u),"iso-date-time":t(l(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&f.test(e)},"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:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},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:function(e){return g.lastIndex=0,g.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=_&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:v},double:{type:"number",validate:v},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\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,h),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},e.formatNames=Object.keys(e.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(e){const t=n.exec(e);if(!t)return!1;const s=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&o<=(2===a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(s)?29:r[a])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const n=o.exec(t);if(!n)return!1;const r=+n[1],s=+n[2],a=+n[3],i=n[4],c="-"===n[5]?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||e&&!i)return!1;if(r<=23&&s<=59&&a<60)return!0;const l=s-d*c,p=r-u*c-(l<0?1:0);return(23===p||-1===p)&&(59===l||-1===l)&&a<61}}function c(e,t){if(!e||!t)return;const n=new Date("2020-01-01T"+e).valueOf(),r=new Date("2020-01-01T"+t).valueOf();return n&&r?n-r:void 0}function u(e,t){if(!e||!t)return;const n=o.exec(e),r=o.exec(t);return n&&r?(e=n[1]+n[2]+n[3])>(t=r[1]+r[2]+r[3])?1:e<t?-1:0:void 0}const d=/t|\s/i;function l(e){const t=i(e);return function(e){const n=e.split(d);return 2===n.length&&s(n[0])&&t(n[1])}}function p(e,t){if(!e||!t)return;const n=new Date(e).valueOf(),r=new Date(t).valueOf();return n&&r?n-r:void 0}function h(e,t){if(!e||!t)return;const[n,r]=e.split(d),[s,o]=t.split(d),i=a(n,s);return void 0!==i?i||c(r,o):void 0}const m=/\/|:/,f=/^(?:[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,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-2147483648,_=2**31-1;function v(){return!0}const w=/[^\\]\\Z/}(gm)),gm),r=(pm||(pm=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=dm(),n=$l(),r=n.operators,s={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},a={message:({keyword:e,schemaCode:t})=>n.str`should be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${s[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:a,code(e){const{gen:r,data:a,schemaCode:o,keyword:i,it:c}=e,{opts:u,self:d}=c;if(!u.validateFormats)return;const l=new t.KeywordCxt(c,d.RULES.all.format.definition,"format");function p(e){return n._`${e}.compare(${a}, ${o}) ${s[i].fail} 0`}l.$data?function(){const t=r.scopeValue("formats",{ref:d.formats,code:u.code.formats}),s=r.const("fmt",n._`${t}[${l.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${s} != "object"`,n._`${s} instanceof RegExp`,n._`typeof ${s}.compare != "function"`,p(s)))}():function(){const t=l.schema,s=d.formats[t];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const a=r.scopeValue("formats",{key:t,ref:s,code:u.code.formats?n._`${u.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(p(a))}()},dependencies:["format"]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(ym)),ym),s=$l(),a=new s.Name("fullFormats"),o=new s.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;const[s,i]="fast"===t.mode?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,s,i),t.keywords&&(0,r.default)(e),e};function c(e,t,n,r){var a,o;null!==(a=(o=e.opts.code).formats)&&void 0!==a||(o.formats=s._`require("ajv-formats/dist/formats").${r}`);for(const r of t)e.addFormat(r,n[r])}i.get=(e,t="full")=>{const r=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(fm,fm.exports)),fm.exports),vm=ul(_m);class wm{constructor(e){this._ajv=e??function(){const e=new mm({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return vm(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class bm{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class km extends il{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ju.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const n=this._loggingLevels.get(t);return!!n&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new wm,this.setRequestHandler(_c,e=>this._oninitialize(e)),this.setNotificationHandler(bc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Au,async(e,t)=>{const n=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:r}=e.params,s=ju.safeParse(r);return s.success&&this._loggingLevels.set(n,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new bm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const n={...e};for(const e in t){const r=e,s=t[r];if(void 0===s)continue;const a=n[r];cl(a)&&cl(s)?n[r]={...a,...s}:n[r]=s}return n}(this._capabilities,e)}setRequestHandler(e,t){const n=Xa(e),r=n?.method;if(!r)throw new Error("Schema is missing a method literal");let s;if(Ka(r)){const e=r,t=e._zod?.def;s=t?.value??e.value}else{const e=r,t=e._def;s=t?.value??e.value}if("string"!=typeof s)throw new Error("Schema method literal must be a string");if("tools/call"===s){const n=async(e,n)=>{const r=Wa(Ru,e);if(!r.success){const e=r.error instanceof Error?r.error.message:String(r.error);throw new wd(nc.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:s}=r.data,a=await Promise.resolve(t(e,n));if(s.task){const e=Wa(Pc,a);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new wd(nc.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const o=Wa(Iu,a);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new wd(nc.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}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})`)}}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})`)}}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})`)}}assertTaskCapability(e){!function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:zi.includes(t)?t:ji,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"},ac)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],o=a.some(e=>"tool_use"===e.type);if(r){if(n.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!o)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(o){const e=new Set(a.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(n.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))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},Wu,t):this.request({method:"sampling/createMessage",params:e},Bu,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},dd,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},r=await this.request({method:"elicitation/create",params:n},dd,t);if("accept"===r.action&&r.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new wd(nc.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof wd)throw e;throw new wd(nc.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){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}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},_d,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))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"})}}const $m=Symbol.for("mcp.completable");function Sm(e){return!!e&&"object"==typeof e&&$m in e}var Em;!function(e){e.Completable="McpCompletable"}(Em||(Em={}));const Tm=/^[A-Za-z0-9._-]{1,128}$/;function xm(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Tm.test(e)){const n=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);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.")}}(e,t.warnings),t.isValid}class Om{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){const r={taskSupport:"required",...t.execution};if("forbidden"===r.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}}class Nm{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new km(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new Om(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(zm(Ou)),this.server.assertCanSetRequestHandler(zm(Ru)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ou,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=Ya(t.inputSchema);return e?sl(e,{strictUnions:!0,pipeStrategy:"input"}):Im})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=Ya(t.outputSchema);e&&(n.outputSchema=sl(e,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ru,async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new wd(nc.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new wd(nc.InvalidParams,`Tool ${e.params.name} disabled`);const r=!!e.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if(("required"===s||"optional"===s)&&!a)throw new wd(nc.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if("required"===s&&!r)throw new wd(nc.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===s&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);const o=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,i,e.params.name),i}catch(e){if(e instanceof wd&&e.code===nc.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const r=Ya(e.inputSchema)??e.inputSchema,s=await Ga(r,t);if(!s.success){const e=Qa("error"in s?s.error:"Unknown error");throw new wd(nc.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return s.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new wd(nc.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const r=Ya(e.outputSchema),s=await Ga(r,t.structuredContent);if(!s.success){const e=Qa("error"in s?s.error:"Unknown error");throw new wd(nc.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){const r=e.handler;if("createTask"in r){if(!n.taskStore)throw new Error("No task store provided.");const s={...n,taskStore:n.taskStore};if(e.inputSchema){const e=r;return await Promise.resolve(e.createTask(t,s))}{const e=r;return await Promise.resolve(e.createTask(s))}}if(e.inputSchema){const e=r;return await Promise.resolve(e(t,n))}{const e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const r=await this.validateToolInput(e,t.params.arguments,t.params.name),s=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(s.createTask(r,a)):await Promise.resolve(s.createTask(a)),i=o.task.taskId;let c=o.task;const u=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,u));const e=await n.taskStore.getTask(i);if(!e)throw new wd(nc.InternalError,`Task ${i} not found during polling`);c=e}return await n.taskStore.getTaskResult(i)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(zm(md)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(md,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new wd(nc.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new wd(nc.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new wd(nc.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Mm;const r=Xa(n.argsSchema),s=r?.[e.params.argument.name];if(!Sm(s))return Mm;const a=function(e){const t=e[$m];return t?.complete}(s);return a?Am(await a(e.params.argument.value,e.params.context)):Mm}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Mm;throw new wd(nc.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Am(await r(e.params.argument.value,e.params.context)):Mm}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(zm(Wc)),this.server.assertCanSetRequestHandler(zm(Xc)),this.server.assertCanSetRequestHandler(zm(tu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Wc,async(e,t)=>{const n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const n=await e.resourceTemplate.listCallback(t);for(const t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Xc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(tu,async(e,t)=>{const n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new wd(nc.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(const e of Object.values(this._registeredResourceTemplates)){const r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new wd(nc.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(zm(pu)),this.server.assertCanSetRequestHandler(zm(fu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(pu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?jm(t.argsSchema):void 0}))})),this.server.setRequestHandler(fu,async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new wd(nc.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new wd(nc.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const r=Ya(n.argsSchema),s=await Ga(r,e.params.arguments);if(!s.success){const t=Qa("error"in s?s.error:"Unknown error");throw new wd(nc.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const a=s.data,o=n.callback;return await Promise.resolve(o(a,t))}{const e=n.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let r;"object"==typeof n[0]&&(r=n.shift());const s=n[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,void 0,t,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const s=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,n,r,s){const a={name:e,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),void 0!==e.name&&(a.name=e.name),void 0!==e.title&&(a.title=e.title),void 0!==e.metadata&&(a.metadata=e.metadata),void 0!==e.callback&&(a.readCallback=e.callback),void 0!==e.enabled&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,s){const a={resourceTemplate:n,title:t,metadata:r,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.template&&(a.resourceTemplate=t.template),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.callback&&(a.readCallback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;const o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,s){const a={title:t,description:n,argsSchema:void 0===r?void 0:Ba(r),callback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.description&&(a.description=t.description),void 0!==t.argsSchema&&(a.argsSchema=Ba(t.argsSchema)),void 0!==t.callback&&(a.callback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Sm(e instanceof m?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,s,a,o,i,c){xm(e);const u={title:t,description:n,inputSchema:Cm(r),outputSchema:Cm(s),annotations:a,execution:o,_meta:i,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&xm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=u)),void 0!==t.title&&(u.title=t.title),void 0!==t.description&&(u.description=t.description),void 0!==t.paramsSchema&&(u.inputSchema=Ba(t.paramsSchema)),void 0!==t.outputSchema&&(u.outputSchema=Ba(t.outputSchema)),void 0!==t.callback&&(u.handler=t.callback),void 0!==t.annotations&&(u.annotations=t.annotations),void 0!==t._meta&&(u._meta=t._meta),void 0!==t.enabled&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,r,s;if("string"==typeof t[0]&&(n=t.shift()),t.length>1){const e=t[0];Rm(e)?(r=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!Rm(t[0])&&(s=t.shift())):"object"==typeof e&&null!==e&&(s=t.shift())}const a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:r,description:s,inputSchema:a,outputSchema:o,annotations:i,_meta:c}=t;return this._createRegisteredTool(e,r,s,a,o,i,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n,r;"string"==typeof t[0]&&(n=t.shift()),t.length>1&&(r=t.shift());const s=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:r,description:s,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,s,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const Im={type:"object",properties:{}};function Pm(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function Rm(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||Pm(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(Pm))}function Cm(e){if(e)return Rm(e)?Ba(e):e}function jm(e){const t=Xa(e);return t?Object.entries(t).map(([e,t])=>{const n=function(e){return e.description}(t),r=function(e){if(Ka(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:n,required:!r}}):[]}function zm(e){const t=Xa(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const r=eo(n);if("string"==typeof r)return r;throw new Error("Schema method literal must be a string")}function Am(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Mm={completion:{values:[],hasMore:!1}};class Dm{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return sc.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Zm{constructor(e=g.stdin,t=g.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Dm,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}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{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const n=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}}class Lm{static exists(e){return o(e)}static writeJson(e,t){const r=n(e);i(r,{recursive:!0}),c(e,JSON.stringify(t,null,2),"utf8")}static readJson(e){if(!this.exists(e))throw new Error(`File not found: ${e}`);const t=a(e,"utf8");return JSON.parse(t)}static writeMarkdown(e,t){const r=n(e);i(r,{recursive:!0}),c(e,t,"utf8")}static formatKnowledgeAsMarkdown(e){return`# ${e.title}\n\n**ID:** ${e.id}\n**Summary:** ${e.summary}\n**Knowledge Type:** ${e.knowledge_type}\n**Status:** ${e.status}\n**Scope:** ${e.scope}\n**Source Type:** ${e.source_type}\n${e.source_file?`**Source File:** ${e.source_file}`:""}\n${e.contributor?`**Contributor:** ${e.contributor}`:""}\n${e.created_at?`**Created At:** ${e.created_at}`:""}\n${e.updated_at?`**Updated At:** ${e.updated_at}`:""}\n\n## Content\n\n${e.content}\n`}static extractKnowledgeForJson(e){return{title:e.title,summary:e.summary,content:e.content,knowledge_type:e.knowledge_type,status:e.status,scope:e.scope,source_type:e.source_type,source_file:e.source_file||null,contributor:e.contributor||null}}}const Fm=I(),qm=z("mcp-server","mcp-server");class Um{constructor(){this.knowledgeManagement=new X,this.tempDir=Fm.tmp,this.server=new Nm({name:"knowledge-bank",version:F.version},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.registerTool("knowledge_create",{description:"Create a new knowledge item",inputSchema:f.object({session_id:f.string().describe("Session ID for tracking, can be omitted to use env vars CLAUDE_SESSION_ID"),title:f.string().optional().describe("Knowledge title"),summary:f.string().optional().describe("Knowledge summary"),content:f.string().optional().describe("Knowledge content"),scope:f.enum(w).optional().describe("Scope of knowledge"),source_type:f.enum(b).optional().describe("Source type"),knowledge_type:f.enum(k).optional().describe("Knowledge type"),status:f.enum($).optional().describe("Status of knowledge"),source_file:f.string().optional().describe("Source file path (optional)"),contributor:f.string().optional().describe("Contributor name (optional)"),from:f.string().optional().describe("Load knowledge data from JSON file")})},async e=>await this.handleCreate(e)),this.server.registerTool("knowledge_get",{description:"Get a knowledge item by ID",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),to:f.string().optional().describe("Save knowledge to markdown file")})},async e=>await this.handleGet(e)),this.server.registerTool("knowledge_update",{description:"Update a knowledge item",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),title:f.string().optional().describe("Knowledge title"),summary:f.string().optional().describe("Knowledge summary"),content:f.string().optional().describe("Knowledge content"),scope:f.enum(w).optional().describe("Scope of knowledge"),source_type:f.enum(b).optional().describe("Source type"),knowledge_type:f.enum(k).optional().describe("Knowledge type"),status:f.enum($).optional().describe("Status of knowledge"),source_file:f.string().optional().describe("Source file path"),contributor:f.string().optional().describe("Contributor name"),from:f.string().optional().describe("Load update data from JSON file")})},async e=>await this.handleUpdate(e)),this.server.registerTool("knowledge_delete",{description:"Delete a knowledge item",inputSchema:f.object({id:f.number().describe("Knowledge item ID")})},async e=>await this.handleDelete(e)),this.server.registerTool("knowledge_list",{description:"List knowledge items with optional filters",inputSchema:f.object({scope:f.enum(w).optional().describe("Filter by scope"),status:f.enum($).optional().describe("Filter by status"),knowledge_type:f.enum(k).optional().describe("Filter by knowledge type"),limit:f.number().default(100).describe("Limit number of results"),offset:f.number().default(0).describe("Offset for pagination"),to:f.string().optional().describe("Save results to JSON file")})},async e=>await this.handleList(e)),this.server.registerTool("knowledge_search",{description:"Search knowledge items by text query",inputSchema:f.object({query:f.array(f.string()).describe("Search query terms"),limit:f.number().default(10).describe("Limit number of results"),to:f.string().optional().describe("Save results to JSON file")})},async e=>await this.handleSearch(e)),this.server.registerTool("knowledge_update_status",{description:"Update knowledge item status",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),status:f.enum($).describe("New status")})},async e=>await this.handleUpdateStatus(e)),this.server.registerTool("knowledge_stats",{description:"Get knowledge statistics",inputSchema:f.object({})},async()=>await this.handleStats())}async handleCreate(e){let n=e;if(e.from){const r=t.join(this.tempDir,t.basename(e.from));if(!Lm.exists(r))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${r}`},null,2)}],isError:!0};try{n=Lm.readJson(r)}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}if(!(n.title&&n.summary&&n.content&&n.scope&&n.source_type&&n.knowledge_type&&n.status))return{content:[{type:"text",text:JSON.stringify({error:"Missing required fields: title, summary, content, scope, source_type, knowledge_type, status"},null,2)}],isError:!0};const r=await this.knowledgeManagement.create({title:n.title,summary:n.summary,content:n.content,scope:n.scope,source_type:n.source_type,knowledge_type:n.knowledge_type,status:n.status,source_file:n.source_file,contributor:n.contributor,session_id:process.env.CLAUDE_SESSION_ID||n.session_id||"unknown-session"});if(e.from){const n=t.join(this.tempDir,t.basename(e.from));return{content:[{type:"text",text:JSON.stringify({id:r.id,title:r.title,message:`Knowledge item created from ${t.basename(e.from)}`,file_path:n},null,2)}]}}return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async handleGet(e){const n=await this.knowledgeManagement.get(e.id);if(!n)return{content:[{type:"text",text:JSON.stringify({error:"Knowledge item not found"},null,2)}],isError:!0};if(e.to)try{const r=t.join(this.tempDir,t.basename(e.to)),s=Lm.formatKnowledgeAsMarkdown(n);return Lm.writeMarkdown(r,s),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Knowledge item ${e.id} saved to ${t.basename(e.to)}`,file_path:r},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async handleUpdate(e){const{id:n,from:r,...s}=e;let a=s;if(r){const e=t.join(this.tempDir,r);if(!Lm.exists(e))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${e}`},null,2)}],isError:!0};try{a={...Lm.readJson(e),...s}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}const o=await this.knowledgeManagement.update(n,a);return{content:[{type:"text",text:JSON.stringify({id:o.id,session_id:o.session_id,message:"knowledge item updated"},null,2)}]}}async handleDelete(e){return await this.knowledgeManagement.delete(e.id),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge item deleted successfully"})}]}}async handleList(e={}){const{to:n,...r}=e,s=await this.knowledgeManagement.list(r);if(n)try{const e=t.join(this.tempDir,n),a=s.map(e=>Lm.extractKnowledgeForJson(e));return Lm.writeJson(e,{count:s.length,filters:r,timestamp:(new Date).toISOString(),data:a}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`${s.length} knowledge items saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleSearch(e){const{to:n,query:r,limit:s}=e,a=await this.knowledgeManagement.search(r,s);if(n)try{const e=t.join(this.tempDir,n),o=a.map(e=>Lm.extractKnowledgeForJson(e));return Lm.writeJson(e,{query:r,limit:s,count:a.length,timestamp:(new Date).toISOString(),data:o}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Search results (${a.length} items) saved to ${n}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}async handleUpdateStatus(e){const t=await this.knowledgeManagement.updateStatus(e.id,e.status);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async handleStats(){const e=await this.knowledgeManagement.getStats();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async run(){const e=new Zm;await this.server.connect(e),qm.logWarn(`Knowledge Bank MCP server running under ${process.cwd()}`)}}const Vm=z("web-server","web-server");class Hm{constructor(e={}){var t;this.port=e.port||3e3,this.isDev=e.dev||!1,this.pathResolver=(t=this.isDev,new A({isDev:t})),this.app=y(),this.database=K,this.server=null,this.connections=new Set,this.md=new v,this.setupApp()}setupApp(){this.app.set("view engine","ejs");const e=this.pathResolver.getWebViewsPath();this.app.set("views",e),this.app.use(_),this.app.set("layout","layout");const t=this.pathResolver.getWebPublicPath();this.app.use(y.static(t)),this.app.use(y.json()),this.app.use(y.urlencoded({extended:!0})),this.app.locals.formatTimestamp=this.formatTimestamp,this.app.locals.renderMarkdown=this.renderMarkdown.bind(this),this.app.locals.formatJsonAsMarkdown=this.formatJsonAsMarkdown.bind(this),this.setupRoutes()}async reconnect(){try{return Vm.logInfo("Reconnecting to database..."),this.database.withConnection(()=>{}),Vm.logInfo("Database reconnection successful"),!0}catch(e){throw Vm.logError("Database reconnection failed:",e),e}}formatTimestamp(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}renderMarkdown(e){return e?this.md.render(e):""}formatJsonAsMarkdown(e){if(!e)return"";try{const t=JSON.parse(e),n=`\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``;return this.md.render(n)}catch(t){const n=`\`\`\`\n${e}\n\`\`\``;return this.md.render(n)}}setupRoutes(){this.app.get("/api/render/cell",(e,t)=>{const{tableName:n,col:r,value:s}=e.query;t.render("partials/cell",{tableName:n,col:r,val:s,layout:!1})}),this.app.get("/api/render/details",async(e,t)=>{const{tableName:n,id:r}=e.query,s=this.getRowById(n,r);if(!s)return t.status(404).send("Not found");t.render("partials/row-details",{tableName:n,data:s,layout:!1,renderMarkdown:this.renderMarkdown.bind(this),formatJsonAsMarkdown:this.formatJsonAsMarkdown.bind(this),formatTimestamp:this.formatTimestamp})}),this.app.get("/",(e,t)=>{const n=this.getTableNames().map(e=>({name:e,count:this.getTableCount(e)}));t.render("index",{title:"Knowledge Bank Database Browser",tableInfo:n,formatTimestamp:function(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},layout:"layout"})}),this.app.get("/api/tables",(e,t)=>{try{const e=this.getTableNames();t.json({tables:e})}catch(e){Vm.logError("Error getting tables:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/schema",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n);t.json({schema:r})}catch(e){Vm.logError("Error getting table schema:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/data",(e,t)=>{try{const{table:n}=e.params,r=parseInt(e.query.page)||1,s=parseInt(e.query.limit)||100,a=(r-1)*s,o={};e.query.session_id&&(o.session_id=e.query.session_id),e.query.cwd&&(o.cwd=e.query.cwd),e.query.knowledge_type&&(o.knowledge_type=e.query.knowledge_type),e.query.status&&(o.status=e.query.status),e.query.git_branch&&(o.git_branch=e.query.git_branch),e.query.name&&(o.name=e.query.name),e.query.title&&(o.title=e.query.title),e.query.search&&(o.search=e.query.search);const i=e.query.sort||"",c=this.getTableData(n,s,a,o,i),u=this.getTableCount(n,o);t.json({data:c,pagination:{page:r,limit:s,total:u,pages:Math.ceil(u/s)}})}catch(e){Vm.logError("Error getting table data:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/row/:id",(e,t)=>{try{const{table:n,id:r}=e.params,s=this.getRowById(n,r);if(!s)return t.status(404).json({error:"Row not found"});t.json({data:s})}catch(n){Vm.logError(`Error getting row from ${e.params.table}:`,n),t.status(500).json({error:n.message})}}),this.app.get("/api/tables/:table/relations",(e,t)=>{try{const{table:n}=e.params,r=this.getTableRelations(n);t.json({relations:r})}catch(e){Vm.logError("Error getting table relations:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/relations",(e,t)=>{try{const e=this.getDatabaseRelations();t.json({relations:e})}catch(e){Vm.logError("Error getting database relations:",e),t.status(500).json({error:e.message})}}),this.app.post("/api/reconnect",async(e,t)=>{try{await this.reconnect(),t.json({success:!0,message:"Database reconnected successfully"})}catch(e){t.status(500).json({success:!1,error:e.message})}}),this.app.get("/tables/:table",(e,t)=>{try{const{table:n}=e.params,r=this.getTableSchema(n),s=this.getTableRelations(n),a=e.query.sort||"",o=this.parseSortParameter(a),i=this.getTableData(n,10,0,{},a),c=this.getEssentialColumns(n,r);t.render("table",{title:`Table: ${n}`,tableName:n,schema:r,relations:s,sampleData:i,essentialColumns:c,sortInfo:o,layout:"layout"})}catch(n){Vm.logError(`Error viewing table ${e.params.table}:`,n),t.status(500).render("error",{title:"Error",error:n.message,layout:"layout"})}})}getTableNames(){return this.database.withConnection(e=>{const t=["session_event","knowledge_item","session","knowledge_item_fts"];return e.prepare("\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\n ORDER BY name\n ").all().map(e=>e.name).filter(e=>t.includes(e))})}getTableSchema(e){return this.database.withConnection(t=>t.prepare(`PRAGMA table_info(${e})`).all())}parseSortParameter(e){return e?e.endsWith("_asc")?{column:e.slice(0,-4),direction:"ASC",oppositeDirection:"DESC"}:e.endsWith("_desc")?{column:e.slice(0,-5),direction:"DESC",oppositeDirection:"ASC"}:{column:e,direction:"ASC",oppositeDirection:"DESC"}:{column:null,direction:null,oppositeDirection:null}}getTableData(e,t=100,n=0,r={},s=""){let a="*";"knowledge_item"===e?a="id, session_id, title, summary, scope, source_type, knowledge_type, status, created_at, updated_at":"session"===e?a="id, session_id, cwd, git_branch, created_at":"session_event"===e&&(a="id, session_id, name, created_at");let o="";const i=[];if(Object.keys(r).length>0){const t=(t=>{const n=[],r=[];return Object.entries(t).forEach(([t,s])=>{if(null!=s&&""!==s)if("search"!==t){if("session_id"===t||"git_branch"===t||"name"===t||"title"===t)return n.push(`${t} LIKE ?`),void r.push(`%${s}%`);n.push(`${t} = ?`),r.push(s)}else if("knowledge_item"===e){n.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e,e,e)}else if("session"===e){n.push("(session_id LIKE ? OR git_branch LIKE ? OR cwd LIKE ?)");const e=`%${s}%`;r.push(e,e,e)}else if("session_event"===e){n.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${s}%`;r.push(e,e)}}),{clause:n.length>0?` WHERE ${n.join(" AND ")}`:"",params:r}})(r);o=t.clause,i.push(...t.params)}let c="";if(s){const e=this.parseSortParameter(s);e.column&&e.direction&&(c=` ORDER BY ${e.column} ${e.direction}`)}else c=" ORDER BY id ASC";return i.push(t,n),this.database.withConnection(t=>t.prepare(`SELECT ${a} FROM ${e}${o}${c} LIMIT ? OFFSET ?`).all(...i))}getTableCount(e,t={}){let n="";const r=[];if(Object.keys(t).length>0){const s=[];Object.entries(t).forEach(([t,n])=>{if(null!=n&&""!==n)if("search"!==t){if("session_id"===t||"git_branch"===t||"name"===t||"title"===t)return s.push(`${t} LIKE ?`),void r.push(`%${n}%`);s.push(`${t} = ?`),r.push(n)}else if("knowledge_item"===e){s.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e,e,e)}else if("session"===e){s.push("(session_id LIKE ? OR git_branch LIKE ? OR cwd LIKE ?)");const e=`%${n}%`;r.push(e,e,e)}else if("session_event"===e){s.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;r.push(e,e)}}),s.length>0&&(n=` WHERE ${s.join(" AND ")}`)}return this.database.withConnection(t=>t.prepare(`SELECT COUNT(*) as count FROM ${e}${n}`).get(...r).count)}getRowById(e,t){return this.database.withConnection(n=>n.prepare(`SELECT * FROM ${e} WHERE id = ?`).get(t))}getEssentialColumns(e,t){const n=t.map(e=>e.name);return({knowledge_item:["id","title","summary","knowledge_type","status","session_id","created_at"],session:["id","session_id","cwd","git_branch","created_at"],session_event:["id","session_id","name","created_at"],knowledge_item_fts:["rowid","title","summary"]}[e]||["id","name","title","created_at"]).filter(e=>n.includes(e))}getTableRelations(e){return this.database.withConnection(t=>t.prepare(`PRAGMA foreign_key_list(${e})`).all())}getDatabaseRelations(){const e=this.getTableNames(),t={};return e.forEach(e=>{t[e]={foreignKeys:this.getTableRelations(e),referencedBy:[]}}),e.forEach(e=>{t[e].foreignKeys.forEach(n=>{const r=n.table;t[r]&&t[r].referencedBy.push({table:e,from:n.from,to:n.to})})}),t}start(){return new Promise((e,t)=>{try{this.database.withConnection(e=>{x(e)}),this.server=this.app.listen(this.port,()=>{this.isDev?(Vm.logInfo(`Web server started in development mode on port ${this.port}`),Vm.logInfo("🚀 Running from source code (no build required)")):Vm.logInfo(`Web server started on port ${this.port}`),Vm.logInfo(`Open http://localhost:${this.port} in your browser`),e(this)}),this.server.on("connection",e=>{this.connections.add(e),e.on("close",()=>{this.connections.delete(e)})})}catch(e){Vm.logError("Error starting web server:",e),t(e)}})}stop(){return new Promise((e,t)=>{if(!this.server)return void e();const n=setTimeout(()=>{Vm.logWarn("Forcing server shutdown due to timeout");for(const e of this.connections)e.destroy();this.connections.clear(),this.server=null,e()},5e3);this.server.close(r=>{if(clearTimeout(n),r){Vm.logError("Error closing web server:",r);for(const e of this.connections)e.destroy();this.connections.clear(),t(r)}else Vm.logInfo("Web server stopped gracefully"),this.server=null,this.connections.clear(),e()}),this.server.unref()})}}const Jm=z("web-command","web-command"),Km=F.version,Bm=I(),Wm=new e;Wm.name("knowledge-bank").description("Claude Code plugin for lightweight knowledge management").version(Km);const Gm=new X;Wm.command("install").description("Install knowledge bank plugin").action(async()=>{await async function(){H().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e||await new Promise((e,t)=>{u(`claude plugin marketplace add ${L}`,(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{u("claude plugin install core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})}).then(async()=>{s.existsSync(B.tmp)||s.mkdirSync(B.tmp,{recursive:!0}),K.withConnection(e=>{x(e)})}).catch(e=>{console.error("Error during installation:",e)})}()}),Wm.command("uninstall").description("Remove knowledge bank plugin").action(async()=>{await async function(){H().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e?(await new Promise((e,t)=>{u("claude plugin uninstall core@knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})}),await new Promise((e,t)=>{u("claude plugin marketplace remove knowledge-bank",(n,r,s)=>{n?t(n):(s&&console.error(s),console.log(r),e())})})):console.log("knowledge-bank plugin is not installed.")}).catch(e=>{console.error("Error during uninstallation:",e)})}()});const Xm=Wm.command("knowledge").description("Manage knowledge items");Xm.command("create").description("Create a new knowledge item").requiredOption("-t, --title <title>","[REQUIRED] Knowledge title").requiredOption("-s, --summary <summary>","[REQUIRED] Knowledge summary").requiredOption("-c, --content <content>","[REQUIRED] Knowledge content").requiredOption("--scope <scope>",`[REQUIRED] Scope: ${w.join(", ")}`).requiredOption("--source-type <type>",`[REQUIRED] Source type: ${b.join(", ")}`).requiredOption("--knowledge-type <type>",`[REQUIRED] Knowledge type: ${k.join(", ")}`).requiredOption("--status <status>",`[REQUIRED] Status: ${Object.values($).join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "draft",\n "source_file": null,\n "contributor": null,\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T10:30:00Z"\n}').action(async e=>{console.log("creating knowledge");const t=await Gm.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.sourceType,knowledge_type:e.knowledgeType,status:e.status,source_file:e.sourceFile,contributor:e.contributor});console.log(JSON.stringify(t,null,2))}),Xm.command("get").description("Get a knowledge item by ID").argument("<id>","Knowledge item ID",parseInt).addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T11:45:00Z"\n}').action(async e=>{const t=await Gm.get(e);t?console.log(JSON.stringify(t,null,2)):(console.log("Knowledge item not found"),process.exit(1))}),Xm.command("update").description("Update a knowledge item").argument("<id>","Knowledge item ID",parseInt).option("-t, --title <title>","[OPTION] Knowledge title").option("-s, --summary <summary>","[OPTION] Knowledge summary").option("-c, --content <content>","[OPTION] Knowledge content").option("--scope <scope>",`[OPTION] Scope: ${w.join(", ")}`).option("--source-type <type>",`[OPTION] Source type: ${b.join(", ")}`).option("--knowledge-type <type>",`[OPTION] Knowledge type: ${k.join(", ")}`).option("--status <status>",`[OPTION] Status: ${Object.values($).join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "Updated React Hook Pattern",\n "summary": "Enhanced best practices for custom hooks",\n "content": "Always prefix with \'use\', follow hooks rules, and add proper TypeScript types",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n}').action(async(e,t)=>{const n=await Gm.update(e,{title:t.title,summary:t.summary,content:t.content,scope:t.scope,source_type:t.sourceType,knowledge_type:t.knowledgeType,status:t.status,source_file:t.sourceFile,contributor:t.contributor});console.log(JSON.stringify(n,null,2))}),Xm.command("delete").description("Delete a knowledge item").argument("<id>","Knowledge item ID",parseInt).addHelpText("after","\nOutput Example:\nKnowledge item deleted successfully").action(async e=>{await Gm.delete(e),console.log("Knowledge item deleted successfully")}),Xm.command("list").description("List knowledge items").option("--scope <scope>","[OPTION] Filter by scope").option("--status <status>","[OPTION] Filter by status").option("--knowledge-type <type>","[OPTION] Filter by knowledge type").option("--limit <limit>","[OPTION] Limit number of results",parseInt,100).option("--offset <offset>","[OPTION] Offset for pagination",parseInt,0).addHelpText("after",'\nOutput Example:\n{\n "items": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n },\n {\n "id": 124,\n "title": "API Error Handling",\n "summary": "Standard error handling patterns",\n "scope": "project",\n "source_type": "developer",\n "knowledge_type": "architecture",\n "status": "draft",\n "created_at": "2026-01-22T11:00:00Z",\n "updated_at": "2026-01-22T11:00:00Z"\n }\n ],\n "total": 2,\n "limit": 10,\n "offset": 0\n}').action(async e=>{const t=await Gm.list({scope:e.scope,status:e.status,knowledge_type:e.knowledgeType,limit:e.limit,offset:e.offset});console.log(JSON.stringify(t,null,2))}),Xm.command("search").description("Search knowledge items by text").argument("<query...>","Search query terms").option("-l, --limit <limit>","[OPTION] Limit number of results",parseInt,10).addHelpText("after",'\nUsage Examples:\n $ knowledge search react hooks\n $ knowledge search "react hooks" --limit 5\n $ knowledge search title:api content:auth\n\nOutput Example:\n{\n "results": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "relevance_score": 0.95,\n "created_at": "2026-01-22T10:30:00Z"\n }\n ],\n "total_results": 1,\n "query": "react hooks",\n "limit": 10\n}').action(async(e,t)=>{const n=await Gm.search(e,t.limit);console.log(JSON.stringify(n,null,2))}),Xm.command("update-status").description("Update knowledge item status").argument("<id>","Knowledge item ID",parseInt).argument("<status>",`New status: ${Object.values($).join(", ")}`).addHelpText("after",'\nOutput Example:\n{\n "success": true,\n "message": "Status updated successfully",\n "id": 123,\n "old_status": "draft",\n "new_status": "verified",\n "updated_at": "2026-01-22T12:30:00Z"\n}').action(async(e,t)=>{const n=await Gm.updateStatus(e,t);console.log(JSON.stringify(n,null,2))}),Xm.command("stats").description("Get knowledge statistics").addHelpText("after",'\nOutput Example:\n{\n "total_items": 156,\n "by_scope": {\n "personal": 45,\n "project": 89,\n "organization": 22\n },\n "by_status": {\n "draft": 67,\n "suggested": 34,\n "verified": 55\n },\n "by_knowledge_type": {\n "code_pattern": 42,\n "architecture": 38,\n "config": 25,\n "pitfall": 31,\n "api_usage": 20\n },\n "by_source_type": {\n "developer": 78,\n "architect": 23,\n "reviewer": 19,\n "ai": 36\n },\n "recent_activity": {\n "created_last_7_days": 12,\n "updated_last_7_days": 8\n }\n}').action(async()=>{const e=await Gm.getStats();console.log(JSON.stringify(e,null,2))}),Wm.command("session-start").description("Hook: Called when a Claude Code session starts").action(async()=>{await te.parseInput().then(async e=>{new fe(e).execute().then(e=>{console.error("session-start hook executed",e),e.send()})})}),Wm.command("session-end").description("Hook: Called when a Claude Code session ends").action(async()=>{await te.parseInput().then(async e=>{new ke(e).execute().then(e=>{e.send()})})}),Wm.command("notification").description("Hook: Called when a notification is triggered").action(async()=>{await te.parseInput().then(async e=>{new ge(e).execute().then(e=>{e.send()})})}),Wm.command("permission-request").description("Hook: Called when a permission request is made").action(async()=>{await te.parseInput().then(async e=>{new ye(e).execute().then(e=>{e.send()})})}),Wm.command("pre-tool-use").description("Hook: Called before a tool is used").action(async()=>{await te.parseInput().then(async e=>{new be(e).execute().then(e=>{e.send()})})}),Wm.command("post-tool-use").description("Hook: Called after a tool is used").action(async()=>{await te.parseInput().then(async e=>{new _e(e).execute().then(e=>{e.send()})})}),Wm.command("pre-compact").description("Hook: Called before compacting the session").action(async()=>{await te.parseInput().then(async e=>{new ve(e).execute().then(e=>{e.send()})})}),Wm.command("stop").description("Hook: Called when a stop signal is received").action(async()=>{await te.parseInput().then(async e=>{new $e(e).execute().then(e=>{e.send()})})}),Wm.command("subagent-stop").description("Hook: Called when a subagent stops").action(async()=>{await te.parseInput().then(async e=>{new Se(e).execute().then(e=>{e.send()})})}),Wm.command("user-prompt-submit").description("Hook: Called when a user submits a prompt").action(async()=>{await te.parseInput().then(async e=>{new Ee(e).execute().then(e=>{e.send()})})}),Wm.command("mcp-server").description("Start the Knowledge Bank MCP server").action(async()=>{const e=new Um;await e.run()}),Wm.command("web").description("Start a web server for browsing the database").option("-p, --port <port>","Port to listen on",e=>parseInt(e,10),3e3).option("-d, --dev","Start from source code (development mode)").addHelpText("after","\nUsage Example:\n $ knowledge-bank web\n $ knowledge-bank web --port 8080\n $ knowledge-bank web --dev\n $ knowledge-bank web --dev --port 8080\n\nOptions:\n --dev Start in development mode from source code\n --port Specify the port number (default: 3000)\n\nThis command starts a web server that allows you to browse the SQLite database tables\nand their relationships. Open the URL displayed in your browser after starting the server.\n\nDevelopment mode (--dev) runs the server directly from source code without building,\nuseful for development and debugging purposes.").action(async e=>{await async function(e={}){const t=e.port||3e3,n=e.dev||!1;n?Jm.logInfo(`Starting web server in development mode (from source) on port ${t}...`):Jm.logInfo(`Starting web server on port ${t}...`),console.log("================================================="),console.log(" Knowledge Bank Database Browser"),n&&console.log(" 🚀 Development Mode (Source Code)"),console.log("================================================="),console.log(` Starting server on port ${t}...`),console.log(` Open http://localhost:${t} in your browser`),console.log(" Press Ctrl+C to stop the server"),console.log("=================================================");const r=new Hm({port:t,dev:n}),s=async e=>{Jm.logInfo(`\nReceived ${e}, shutting down web server gracefully...`),console.log("\nShutting down server...");try{await r.stop(),Jm.logInfo("Web server stopped successfully"),console.log("Server stopped successfully"),process.exit(0)}catch(e){Jm.logError("Error during shutdown:",e),console.error("Error during shutdown:",e.message),process.exit(1)}};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM")),process.on("unhandledRejection",(e,t)=>{Jm.logError("Unhandled Rejection at:",t,"reason:",e)}),await r.start();const a=setInterval(()=>{},1e3),o=s,i=async e=>{clearInterval(a),await o(e)};return process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r}(e)}),Wm.command("config").description("Get Knowledge Bank configuration settings").option("-t --temp","Get temporary directory path").action(async e=>{e.temp?console.log(Bm.tmp):console.error("unsupported option. Use --temp to get the temporary directory path.")}),Wm.parse(process.argv);
8
+ deps: ${s}}`};const r={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const s in e)"__proto__"!==s&&((Array.isArray(e[s])?t:n)[s]=e[s]);return[t,n]}(e);a(e,t),o(e,n)}};function a(e,n=e.schema){const{gen:r,data:a,it:o}=e;if(0===Object.keys(n).length)return;const i=r.let("missing");for(const c in n){const u=n[c];if(0===u.length)continue;const d=(0,s.propertyInData)(r,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:u.length,deps:u.join(", ")}),o.allErrors?r.if(d,()=>{for(const t of u)(0,s.checkReportMissingProp)(e,t)}):(r.if(t._`${d} && (${(0,s.checkMissingProp)(e,u,i)})`),(0,s.reportMissingProp)(e,i),r.else())}}function o(e,t=e.schema){const{gen:r,data:a,keyword:o,it:i}=e,c=r.name("valid");for(const u in t)(0,n.alwaysValidSchema)(i,t[u])||(r.if((0,s.propertyInData)(r,a,u,i.opts.ownProperties),()=>{const t=e.subschema({keyword:o,schemaProp:u},c);e.mergeValidEvaluated(t,c)},()=>r.var(c,!0)),e.ok(c))}e.validatePropertyDeps=a,e.validateSchemaDeps=o,e.default=r}(Ih)),Ih),o=function(){if(Nh)return Rh;Nh=1,Object.defineProperty(Rh,"__esModule",{value:!0});const e=Ol(),t=Nl(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>e._`{propertyName: ${t.propertyName}}`},code(n){const{gen:s,schema:r,data:a,it:o}=n;if((0,t.alwaysValidSchema)(o,r))return;const i=s.name("valid");s.forIn("key",a,t=>{n.setParams({propertyName:t}),n.subschema({keyword:"propertyNames",data:t,dataTypes:["string"],propertyName:t,compositeRule:!0},i),s.if((0,e.not)(i),()=>{n.error(!0),o.allErrors||s.break()})}),n.ok(i)}};return Rh.default=n,Rh}(),i=jh(),c=function(){if(zh)return Hh;zh=1,Object.defineProperty(Hh,"__esModule",{value:!0});const e=lp(),t=Yl(),n=Nl(),s=jh(),r={keyword:"properties",type:"object",schemaType:"object",code(r){const{gen:a,schema:o,parentSchema:i,data:c,it:u}=r;"all"===u.opts.removeAdditional&&void 0===i.additionalProperties&&s.default.code(new e.KeywordCxt(u,s.default,"additionalProperties"));const d=(0,t.allSchemaProperties)(o);for(const e of d)u.definedProperties.add(e);u.opts.unevaluated&&d.length&&!0!==u.props&&(u.props=n.mergeEvaluated.props(a,(0,n.toHash)(d),u.props));const l=d.filter(e=>!(0,n.alwaysValidSchema)(u,o[e]));if(0===l.length)return;const p=a.name("valid");for(const e of l)h(e)?m(e):(a.if((0,t.propertyInData)(a,c,e,u.opts.ownProperties)),m(e),u.allErrors||a.else().var(p,!0),a.endIf()),r.it.definedProperties.add(e),r.ok(p);function h(e){return u.opts.useDefaults&&!u.compositeRule&&void 0!==o[e].default}function m(e){r.subschema({keyword:"properties",schemaProp:e,dataProp:e},p)}}};return Hh.default=r,Hh}(),u=function(){if(Ah)return Vh;Ah=1,Object.defineProperty(Vh,"__esModule",{value:!0});const e=Yl(),t=Ol(),n=Nl(),s=Nl(),r={keyword:"patternProperties",type:"object",schemaType:"object",code(r){const{gen:a,schema:o,data:i,parentSchema:c,it:u}=r,{opts:d}=u,l=(0,e.allSchemaProperties)(o),p=l.filter(e=>(0,n.alwaysValidSchema)(u,o[e]));if(0===l.length||p.length===l.length&&(!u.opts.unevaluated||!0===u.props))return;const h=d.strictSchema&&!d.allowMatchingProperties&&c.properties,m=a.name("valid");!0===u.props||u.props instanceof t.Name||(u.props=(0,s.evaluatedPropsToName)(a,u.props));const{props:f}=u;function g(e){for(const t in h)new RegExp(e).test(t)&&(0,n.checkStrictMode)(u,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){a.forIn("key",i,o=>{a.if(t._`${(0,e.usePattern)(r,n)}.test(${o})`,()=>{const e=p.includes(n);e||r.subschema({keyword:"patternProperties",schemaProp:n,dataProp:o,dataPropType:s.Type.Str},m),u.opts.unevaluated&&!0!==f?a.assign(t._`${f}[${o}]`,!0):e||u.allErrors||a.if((0,t.not)(m),()=>a.break())})})}!function(){for(const e of l)h&&g(e),u.allErrors?y(e):(a.var(m,!0),y(e),a.if(m))}()}};return Vh.default=r,Vh}(),d=function(){if(Dh)return Jh;Dh=1,Object.defineProperty(Jh,"__esModule",{value:!0});const e=Nl(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:n,schema:s,it:r}=t;if((0,e.alwaysValidSchema)(r,s))return void t.fail();const a=n.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),t.failResult(a,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};return Jh.default=t,Jh}(),l=function(){if(Mh)return Kh;Mh=1,Object.defineProperty(Kh,"__esModule",{value:!0});const e={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Yl().validateUnion,error:{message:"must match a schema in anyOf"}};return Kh.default=e,Kh}(),p=function(){if(Lh)return Bh;Lh=1,Object.defineProperty(Bh,"__esModule",{value:!0});const e=Ol(),t=Nl(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>e._`{passingSchemas: ${t.passing}}`},code(n){const{gen:s,schema:r,parentSchema:a,it:o}=n;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&a.discriminator)return;const i=r,c=s.let("valid",!1),u=s.let("passing",null),d=s.name("_valid");n.setParams({passing:u}),s.block(function(){i.forEach((r,a)=>{let i;(0,t.alwaysValidSchema)(o,r)?s.var(d,!0):i=n.subschema({keyword:"oneOf",schemaProp:a,compositeRule:!0},d),a>0&&s.if(e._`${d} && ${c}`).assign(c,!1).assign(u,e._`[${u}, ${a}]`).else(),s.if(d,()=>{s.assign(c,!0),s.assign(u,a),i&&n.mergeEvaluated(i,e.Name)})})}),n.result(c,()=>n.reset(),()=>n.error(!0))}};return Bh.default=n,Bh}(),h=function(){if(Zh)return Wh;Zh=1,Object.defineProperty(Wh,"__esModule",{value:!0});const e=Nl(),t={keyword:"allOf",schemaType:"array",code(t){const{gen:n,schema:s,it:r}=t;if(!Array.isArray(s))throw new Error("ajv implementation error");const a=n.name("valid");s.forEach((n,s)=>{if((0,e.alwaysValidSchema)(r,n))return;const o=t.subschema({keyword:"allOf",schemaProp:s},a);t.ok(a),t.mergeEvaluated(o)})}};return Wh.default=t,Wh}(),m=function(){if(Fh)return Gh;Fh=1,Object.defineProperty(Gh,"__esModule",{value:!0});const e=Ol(),t=Nl(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>e.str`must match "${t.ifClause}" schema`,params:({params:t})=>e._`{failingKeyword: ${t.ifClause}}`},code(n){const{gen:r,parentSchema:a,it:o}=n;void 0===a.then&&void 0===a.else&&(0,t.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const i=s(o,"then"),c=s(o,"else");if(!i&&!c)return;const u=r.let("valid",!0),d=r.name("_valid");if(function(){const e=n.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);n.mergeEvaluated(e)}(),n.reset(),i&&c){const e=r.let("ifClause");n.setParams({ifClause:e}),r.if(d,l("then",e),l("else",e))}else i?r.if(d,l("then")):r.if((0,e.not)(d),l("else"));function l(t,s){return()=>{const a=n.subschema({keyword:t},d);r.assign(u,d),n.mergeValidEvaluated(a,u),s?r.assign(s,e._`${t}`):n.setParams({ifClause:t})}}n.pass(u,()=>n.error(!0))}};function s(e,n){const s=e.schema[n];return void 0!==s&&!(0,t.alwaysValidSchema)(e,s)}return Gh.default=n,Gh}(),f=function(){if(Uh)return Xh;Uh=1,Object.defineProperty(Xh,"__esModule",{value:!0});const e=Nl(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:n,it:s}){void 0===n.if&&(0,e.checkStrictMode)(s,`"${t}" without "if" is ignored`)}};return Xh.default=t,Xh}();return gh.default=function(g=!1){const y=[d.default,l.default,p.default,h.default,m.default,f.default,o.default,i.default,a.default,c.default,u.default];return g?y.push(t.default,s.default):y.push(e.default,n.default),y.push(r.default),y},gh}var Qh,em,tm={},nm={};function sm(){if(Qh)return nm;Qh=1,Object.defineProperty(nm,"__esModule",{value:!0});const e=Ol(),t={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>e.str`must match format "${t}"`,params:({schemaCode:t})=>e._`{format: ${t}}`},code(t,n){const{gen:s,data:r,$data:a,schema:o,schemaCode:i,it:c}=t,{opts:u,errSchemaPath:d,schemaEnv:l,self:p}=c;u.validateFormats&&(a?function(){const a=s.scopeValue("formats",{ref:p.formats,code:u.code.formats}),o=s.const("fDef",e._`${a}[${i}]`),c=s.let("fType"),d=s.let("format");s.if(e._`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>s.assign(c,e._`${o}.type || "string"`).assign(d,e._`${o}.validate`),()=>s.assign(c,e._`"string"`).assign(d,o)),t.fail$data((0,e.or)(!1===u.strictSchema?e.nil:e._`${i} && !${d}`,function(){const t=l.$async?e._`(${o}.async ? await ${d}(${r}) : ${d}(${r}))`:e._`${d}(${r})`,s=e._`(typeof ${d} == "function" ? ${t} : ${d}.test(${r}))`;return e._`${d} && ${d} !== true && ${c} === ${n} && !${s}`}()))}():function(){const a=p.formats[o];if(!a)return void function(){if(!1!==u.strictSchema)throw new Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${d}"`}p.logger.warn(e())}();if(!0===a)return;const[i,c,h]=function(t){const n=t instanceof RegExp?(0,e.regexpCode)(t):u.code.formats?e._`${u.code.formats}${(0,e.getProperty)(o)}`:void 0,r=s.scopeValue("formats",{key:o,ref:t,code:n});return"object"!=typeof t||t instanceof RegExp?["string",t,r]:[t.type||"string",t.validate,e._`${r}.validate`]}(a);i===n&&t.pass(function(){if("object"==typeof a&&!(a instanceof RegExp)&&a.async){if(!l.$async)throw new Error("async format in sync schema");return e._`await ${h}(${r})`}return"function"==typeof c?e._`${h}(${r})`:e._`${h}.test(${r})`}())}())}};return nm.default=t,nm}var rm,am,om={};function im(){if(am)return Ap;am=1,Object.defineProperty(Ap,"__esModule",{value:!0});const e=function(){if(zp)return Dp;zp=1,Object.defineProperty(Dp,"__esModule",{value:!0});const e=function(){if(Cp)return Mp;Cp=1,Object.defineProperty(Mp,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return Mp.default=e,Mp}(),t=function(){if(jp)return Lp;jp=1,Object.defineProperty(Lp,"__esModule",{value:!0}),Lp.callRef=Lp.getValidate=void 0;const e=yp(),t=Yl(),n=Ol(),s=zl(),r=wp(),a=Nl(),o={keyword:"$ref",schemaType:"string",code(t){const{gen:s,schema:a,it:o}=t,{baseId:u,schemaEnv:d,validateName:l,opts:p,self:h}=o,{root:m}=d;if(("#"===a||"#/"===a)&&u===m.baseId)return function(){if(d===m)return c(t,l,d,d.$async);const e=s.scopeValue("root",{ref:m});return c(t,n._`${e}.validate`,m,m.$async)}();const f=r.resolveRef.call(h,m,u,a);if(void 0===f)throw new e.default(o.opts.uriResolver,u,a);return f instanceof r.SchemaEnv?function(e){const n=i(t,e);c(t,n,e,e.$async)}(f):function(e){const r=s.scopeValue("schema",!0===p.code.source?{ref:e,code:(0,n.stringify)(e)}:{ref:e}),o=s.name("valid"),i=t.subschema({schema:e,dataTypes:[],schemaPath:n.nil,topSchemaRef:r,errSchemaPath:a},o);t.mergeEvaluated(i),t.ok(o)}(f)}};function i(e,t){const{gen:s}=e;return t.validate?s.scopeValue("validate",{ref:t.validate}):n._`${s.scopeValue("wrapper",{ref:t})}.validate`}function c(e,r,o,i){const{gen:c,it:u}=e,{allErrors:d,schemaEnv:l,opts:p}=u,h=p.passContext?s.default.this:n.nil;function m(e){const t=n._`${e}.errors`;c.assign(s.default.vErrors,n._`${s.default.vErrors} === null ? ${t} : ${s.default.vErrors}.concat(${t})`),c.assign(s.default.errors,n._`${s.default.vErrors}.length`)}function f(e){var t;if(!u.opts.unevaluated)return;const s=null===(t=null==o?void 0:o.validate)||void 0===t?void 0:t.evaluated;if(!0!==u.props)if(s&&!s.dynamicProps)void 0!==s.props&&(u.props=a.mergeEvaluated.props(c,s.props,u.props));else{const t=c.var("props",n._`${e}.evaluated.props`);u.props=a.mergeEvaluated.props(c,t,u.props,n.Name)}if(!0!==u.items)if(s&&!s.dynamicItems)void 0!==s.items&&(u.items=a.mergeEvaluated.items(c,s.items,u.items));else{const t=c.var("items",n._`${e}.evaluated.items`);u.items=a.mergeEvaluated.items(c,t,u.items,n.Name)}}i?function(){if(!l.$async)throw new Error("async schema referenced by sync schema");const s=c.let("valid");c.try(()=>{c.code(n._`await ${(0,t.callValidateCode)(e,r,h)}`),f(r),d||c.assign(s,!0)},e=>{c.if(n._`!(${e} instanceof ${u.ValidationError})`,()=>c.throw(e)),m(e),d||c.assign(s,!1)}),e.ok(s)}():e.result((0,t.callValidateCode)(e,r,h),()=>f(r),()=>m(r))}return Lp.getValidate=i,Lp.callRef=c,Lp.default=o,Lp}(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return Dp.default=n,Dp}(),t=mh(),n=Yh(),s=function(){if(em)return tm;em=1,Object.defineProperty(tm,"__esModule",{value:!0});const e=[sm().default];return tm.default=e,tm}(),r=(rm||(rm=1,Object.defineProperty(om,"__esModule",{value:!0}),om.contentVocabulary=om.metadataVocabulary=void 0,om.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],om.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),om),a=[e.default,t.default,(0,n.default)(),s.default,r.metadataVocabulary,r.contentVocabulary];return Ap.default=a,Ap}var cm,um,dm={},lm={};var pm,hm={$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};function mm(){return pm||(pm=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=Rp(),s=im(),r=function(){if(um)return dm;um=1,Object.defineProperty(dm,"__esModule",{value:!0});const e=Ol(),t=(cm||(cm=1,Object.defineProperty(lm,"__esModule",{value:!0}),lm.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(lm.DiscrError=n={}))),lm);var n;const s=wp(),r=yp(),a=Nl(),o={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:n}})=>e===t.DiscrError.Tag?`tag "${n}" must be string`:`value of tag "${n}" must be in oneOf`,params:({params:{discrError:t,tag:n,tagName:s}})=>e._`{error: ${t}, tag: ${s}, tagValue: ${n}}`},code(n){const{gen:o,data:i,schema:c,parentSchema:u,it:d}=n,{oneOf:l}=u;if(!d.opts.discriminator)throw new Error("discriminator: requires discriminator option");const p=c.propertyName;if("string"!=typeof p)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!l)throw new Error("discriminator: requires oneOf keyword");const h=o.let("valid",!1),m=o.const("tag",e._`${i}${(0,e.getProperty)(p)}`);function f(t){const s=o.name("valid"),r=n.subschema({keyword:"oneOf",schemaProp:t},s);return n.mergeEvaluated(r,e.Name),s}o.if(e._`typeof ${m} == "string"`,()=>function(){const i=function(){var e;const t={},n=i(u);let o=!0;for(let t=0;t<l.length;t++){let u=l[t];if((null==u?void 0:u.$ref)&&!(0,a.schemaHasRulesButRef)(u,d.self.RULES)){const e=u.$ref;if(u=s.resolveRef.call(d.self,d.schemaEnv.root,d.baseId,e),u instanceof s.SchemaEnv&&(u=u.schema),void 0===u)throw new r.default(d.opts.uriResolver,d.baseId,e)}const h=null===(e=null==u?void 0:u.properties)||void 0===e?void 0:e[p];if("object"!=typeof h)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);o=o&&(n||i(u)),c(h,t)}if(!o)throw new Error(`discriminator: "${p}" must be required`);return t;function i({required:e}){return Array.isArray(e)&&e.includes(p)}function c(e,t){if(e.const)h(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(const n of e.enum)h(n,t)}}function h(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${p}" values must be unique strings`);t[e]=n}}();o.if(!1);for(const t in i)o.elseIf(e._`${m} === ${t}`),o.assign(h,f(i[t]));o.else(),n.error(!1,{discrError:t.DiscrError.Mapping,tag:m,tagName:p}),o.endIf()}(),()=>n.error(!1,{discrError:t.DiscrError.Tag,tag:m,tagName:p})),n.ok(h)}};return dm.default=o,dm}(),a=hm,o=["/properties"],i="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),s.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(r.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=lp();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var d=Ol();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return d._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return d.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return d.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return d.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return d.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return d.CodeGen}});var l=mp();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return l.default}});var p=yp();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}(fl,fl.exports)),fl.exports}var fm,gm,ym,_m=hl(mm()),vm={exports:{}},wm={},bm={},km=(ym||(ym=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const n=(fm||(fm=1,function(e){function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(r,a),time:t(i(!0),c),"date-time":t(l(!0),p),"iso-time":t(i(),u),"iso-date-time":t(l(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return m.test(e)&&f.test(e)},"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:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},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:function(e){return g.lastIndex=0,g.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=_&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:v},double:{type:"number",validate:v},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\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,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\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,h),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},e.formatNames=Object.keys(e.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function r(e){const t=n.exec(e);if(!t)return!1;const r=+t[1],a=+t[2],o=+t[3];return a>=1&&a<=12&&o>=1&&o<=(2===a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:s[a])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function i(e){return function(t){const n=o.exec(t);if(!n)return!1;const s=+n[1],r=+n[2],a=+n[3],i=n[4],c="-"===n[5]?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||e&&!i)return!1;if(s<=23&&r<=59&&a<60)return!0;const l=r-d*c,p=s-u*c-(l<0?1:0);return(23===p||-1===p)&&(59===l||-1===l)&&a<61}}function c(e,t){if(!e||!t)return;const n=new Date("2020-01-01T"+e).valueOf(),s=new Date("2020-01-01T"+t).valueOf();return n&&s?n-s:void 0}function u(e,t){if(!e||!t)return;const n=o.exec(e),s=o.exec(t);return n&&s?(e=n[1]+n[2]+n[3])>(t=s[1]+s[2]+s[3])?1:e<t?-1:0:void 0}const d=/t|\s/i;function l(e){const t=i(e);return function(e){const n=e.split(d);return 2===n.length&&r(n[0])&&t(n[1])}}function p(e,t){if(!e||!t)return;const n=new Date(e).valueOf(),s=new Date(t).valueOf();return n&&s?n-s:void 0}function h(e,t){if(!e||!t)return;const[n,s]=e.split(d),[r,o]=t.split(d),i=a(n,r);return void 0!==i?i||c(s,o):void 0}const m=/\/|:/,f=/^(?:[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,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-2147483648,_=2**31-1;function v(){return!0}const w=/[^\\]\\Z/}(wm)),wm),s=(gm||(gm=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=mm(),n=Ol(),s=n.operators,r={formatMaximum:{okStr:"<=",ok:s.LTE,fail:s.GT},formatMinimum:{okStr:">=",ok:s.GTE,fail:s.LT},formatExclusiveMaximum:{okStr:"<",ok:s.LT,fail:s.GTE},formatExclusiveMinimum:{okStr:">",ok:s.GT,fail:s.LTE}},a={message:({keyword:e,schemaCode:t})=>n.str`should be ${r[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${r[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(r),type:"string",schemaType:"string",$data:!0,error:a,code(e){const{gen:s,data:a,schemaCode:o,keyword:i,it:c}=e,{opts:u,self:d}=c;if(!u.validateFormats)return;const l=new t.KeywordCxt(c,d.RULES.all.format.definition,"format");function p(e){return n._`${e}.compare(${a}, ${o}) ${r[i].fail} 0`}l.$data?function(){const t=s.scopeValue("formats",{ref:d.formats,code:u.code.formats}),r=s.const("fmt",n._`${t}[${l.schemaCode}]`);e.fail$data((0,n.or)(n._`typeof ${r} != "object"`,n._`${r} instanceof RegExp`,n._`typeof ${r}.compare != "function"`,p(r)))}():function(){const t=l.schema,r=d.formats[t];if(!r||!0===r)return;if("object"!=typeof r||r instanceof RegExp||"function"!=typeof r.compare)throw new Error(`"${i}": format "${t}" does not define "compare" function`);const a=s.scopeValue("formats",{key:t,ref:r,code:u.code.formats?n._`${u.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(p(a))}()},dependencies:["format"]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}(bm)),bm),r=Ol(),a=new r.Name("fullFormats"),o=new r.Name("fastFormats"),i=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;const[r,i]="fast"===t.mode?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,r,i),t.keywords&&(0,s.default)(e),e};function c(e,t,n,s){var a,o;null!==(a=(o=e.opts.code).formats)&&void 0!==a||(o.formats=r._`require("ajv-formats/dist/formats").${s}`);for(const s of t)e.addFormat(s,n[s])}i.get=(e,t="full")=>{const s=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!s)throw new Error(`Unknown format "${e}"`);return s},e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i}(vm,vm.exports)),vm.exports),$m=hl(km);class Em{constructor(e){this._ajv=e??function(){const e=new _m({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return $m(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Sm{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class Tm extends ll{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Mu.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const n=this._loggingLevels.get(t);return!!n&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Em,this.setRequestHandler(kc,e=>this._oninitialize(e)),this.setNotificationHandler(Sc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zu,async(e,t)=>{const n=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=e.params,r=Mu.safeParse(s);return r.success&&this._loggingLevels.set(n,r.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const n={...e};for(const e in t){const s=e,r=t[s];if(void 0===r)continue;const a=n[s];pl(a)&&pl(r)?n[s]={...a,...r}:n[s]=r}return n}(this._capabilities,e)}setRequestHandler(e,t){const n=to(e),s=n?.method;if(!s)throw new Error("Schema is missing a method literal");let r;if(Xa(s)){const e=s,t=e._zod?.def;r=t?.value??e.value}else{const e=s,t=e._def;r=t?.value??e.value}if("string"!=typeof r)throw new Error("Schema method literal must be a string");if("tools/call"===r){const n=async(e,n)=>{const s=Qa(Au,e);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new Ed(oc.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:r}=s.data,a=await Promise.resolve(t(e,n));if(r.task){const e=Qa(zc,a);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Ed(oc.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const o=Qa(ju,a);if(!o.success){const e=o.error instanceof Error?o.error.message:String(o.error);throw new Ed(oc.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}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})`)}}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})`)}}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})`)}}assertTaskCapability(e){!function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Li.includes(t)?t:Mi,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,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],s=n.some(e=>"tool_result"===e.type),r=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=r?Array.isArray(r.content)?r.content:[r.content]:[],o=a.some(e=>"tool_use"===e.type);if(s){if(n.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!o)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(o){const e=new Set(a.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(n.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))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},Qu,t):this.request({method:"sampling/createMessage",params:e},Yu,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const n=e;return this.request({method:"elicitation/create",params:n},md,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const n="form"===e.mode?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},md,t);if("accept"===s.action&&s.content&&n.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!e.valid)throw new Ed(oc.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof Ed)throw e;throw new Ed(oc.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return s}}}createElicitationCompletionNotifier(e,t){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}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},kd,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))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"})}}const Om=Symbol.for("mcp.completable");function xm(e){return!!e&&"object"==typeof e&&Om in e}var Im;!function(e){e.Completable="McpCompletable"}(Im||(Im={}));const Nm=/^[A-Za-z0-9._-]{1,128}$/;function Pm(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Nm.test(e)){const n=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);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.")}}(e,t.warnings),t.isValid}class Rm{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){const s={taskSupport:"required",...t.execution};if("forbidden"===s.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,s,t._meta,n)}}class Cm{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Tm(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new Rm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Lm(Ru)),this.server.assertCanSetRequestHandler(Lm(Au)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ru,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const n={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=no(t.inputSchema);return e?cl(e,{strictUnions:!0,pipeStrategy:"input"}):jm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=no(t.outputSchema);e&&(n.outputSchema=cl(e,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Au,async(e,t)=>{try{const n=this._registeredTools[e.params.name];if(!n)throw new Ed(oc.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Ed(oc.InvalidParams,`Tool ${e.params.name} disabled`);const s=!!e.params.task,r=n.execution?.taskSupport,a="createTask"in n.handler;if(("required"===r||"optional"===r)&&!a)throw new Ed(oc.InternalError,`Tool ${e.params.name} has taskSupport '${r}' but was not registered with registerToolTask`);if("required"===r&&!s)throw new Ed(oc.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===r&&!s&&a)return await this.handleAutomaticTaskPolling(n,e,t);const o=await this.validateToolInput(n,e.params.arguments,e.params.name),i=await this.executeToolHandler(n,o,t);return s||await this.validateToolOutput(n,i,e.params.name),i}catch(e){if(e instanceof Ed&&e.code===oc.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;const s=no(e.inputSchema)??e.inputSchema,r=await eo(s,t);if(!r.success){const e=so("error"in r?r.error:"Unknown error");throw new Ed(oc.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ed(oc.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const s=no(e.outputSchema),r=await eo(s,t.structuredContent);if(!r.success){const e=so("error"in r?r.error:"Unknown error");throw new Ed(oc.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){const s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");const r={...n,taskStore:n.taskStore};if(e.inputSchema){const e=s;return await Promise.resolve(e.createTask(t,r))}{const e=s;return await Promise.resolve(e.createTask(r))}}if(e.inputSchema){const e=s;return await Promise.resolve(e(t,n))}{const e=s;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const s=await this.validateToolInput(e,t.params.arguments,t.params.name),r=e.handler,a={...n,taskStore:n.taskStore},o=s?await Promise.resolve(r.createTask(s,a)):await Promise.resolve(r.createTask(a)),i=o.task.taskId;let c=o.task;const u=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,u));const e=await n.taskStore.getTask(i);if(!e)throw new Ed(oc.InternalError,`Task ${i} not found during polling`);c=e}return await n.taskStore.getTaskResult(i)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Lm(_d)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_d,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ed(oc.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const n=this._registeredPrompts[t.name];if(!n)throw new Ed(oc.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Ed(oc.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Fm;const s=to(n.argsSchema),r=s?.[e.params.argument.name];if(!xm(r))return Fm;const a=function(e){const t=e[Om];return t?.complete}(r);return a?Zm(await a(e.params.argument.value,e.params.context)):Fm}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Fm;throw new Ed(oc.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=n.resourceTemplate.completeCallback(e.params.argument.name);return s?Zm(await s(e.params.argument.value,e.params.context)):Fm}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Lm(Qc)),this.server.assertCanSetRequestHandler(Lm(tu)),this.server.assertCanSetRequestHandler(Lm(au)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Qc,async(e,t)=>{const n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),s=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const n=await e.resourceTemplate.listCallback(t);for(const t of n.resources)s.push({...e.metadata,...t})}return{resources:[...n,...s]}}),this.server.setRequestHandler(tu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(au,async(e,t)=>{const n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new Ed(oc.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,t)}for(const e of Object.values(this._registeredResourceTemplates)){const s=e.resourceTemplate.uriTemplate.match(n.toString());if(s)return e.readCallback(n,s,t)}throw new Ed(oc.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Lm(gu)),this.server.assertCanSetRequestHandler(Lm(vu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(gu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Mm(t.argsSchema):void 0}))})),this.server.setRequestHandler(vu,async(e,t)=>{const n=this._registeredPrompts[e.params.name];if(!n)throw new Ed(oc.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Ed(oc.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){const s=no(n.argsSchema),r=await eo(s,e.params.arguments);if(!r.success){const t=so("error"in r?r.error:"Unknown error");throw new Ed(oc.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const a=r.data,o=n.callback;return await Promise.resolve(o(a,t))}{const e=n.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...n){let s;"object"==typeof n[0]&&(s=n.shift());const r=n[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const n=this._createRegisteredResource(e,void 0,t,s,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const n=this._createRegisteredResourceTemplate(e,void 0,t,s,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,s){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const r=this._createRegisteredResource(e,n.title,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const r=this._createRegisteredResourceTemplate(e,n.title,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}_createRegisteredResource(e,t,n,s,r){const a={name:e,title:t,metadata:s,readCallback:r,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),void 0!==e.name&&(a.name=e.name),void 0!==e.title&&(a.title=e.title),void 0!==e.metadata&&(a.metadata=e.metadata),void 0!==e.callback&&(a.readCallback=e.callback),void 0!==e.enabled&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,s,r){const a={resourceTemplate:n,title:t,metadata:s,readCallback:r,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.template&&(a.resourceTemplate=t.template),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.callback&&(a.readCallback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;const o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,s,r){const a={title:t,description:n,argsSchema:void 0===s?void 0:Ya(s),callback:r,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.description&&(a.description=t.description),void 0!==t.argsSchema&&(a.argsSchema=Ya(t.argsSchema)),void 0!==t.callback&&(a.callback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,s&&Object.values(s).some(e=>xm(e instanceof m?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,s,r,a,o,i,c){Pm(e);const u={title:t,description:n,inputSchema:Dm(s),outputSchema:Dm(r),annotations:a,execution:o,_meta:i,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&Pm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=u)),void 0!==t.title&&(u.title=t.title),void 0!==t.description&&(u.description=t.description),void 0!==t.paramsSchema&&(u.inputSchema=Ya(t.paramsSchema)),void 0!==t.outputSchema&&(u.outputSchema=Ya(t.outputSchema)),void 0!==t.callback&&(u.handler=t.callback),void 0!==t.annotations&&(u.annotations=t.annotations),void 0!==t._meta&&(u._meta=t._meta),void 0!==t.enabled&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,r;if("string"==typeof t[0]&&(n=t.shift()),t.length>1){const e=t[0];Am(e)?(s=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!Am(t[0])&&(r=t.shift())):"object"==typeof e&&null!==e&&(r=t.shift())}const a=t[0];return this._createRegisteredTool(e,void 0,n,s,void 0,r,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:r,inputSchema:a,outputSchema:o,annotations:i,_meta:c}=t;return this._createRegisteredTool(e,s,r,a,o,i,{taskSupport:"forbidden"},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n,s;"string"==typeof t[0]&&(n=t.shift()),t.length>1&&(s=t.shift());const r=t[0],a=this._createRegisteredPrompt(e,void 0,n,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:r,argsSchema:a}=t,o=this._createRegisteredPrompt(e,s,r,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const jm={type:"object",properties:{}};function zm(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function Am(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||zm(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(zm))}function Dm(e){if(e)return Am(e)?Ya(e):e}function Mm(e){const t=to(e);return t?Object.entries(t).map(([e,t])=>{const n=function(e){return e.description}(t),s=function(e){if(Xa(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:n,required:!s}}):[]}function Lm(e){const t=to(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const s=ro(n);if("string"==typeof s)return s;throw new Error("Schema method literal must be a string")}function Zm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Fm={completion:{values:[],hasMore:!1}};class Um{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return cc.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class qm{constructor(e=g.stdin,t=g.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Um,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}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{const e=this._readBuffer.readMessage();if(null===e)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{const n=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}}class Hm{static exists(e){return o(e)}static writeJson(e,t){const s=n(e);i(s,{recursive:!0}),c(e,JSON.stringify(t,null,2),"utf8")}static readJson(e){if(!this.exists(e))throw new Error(`File not found: ${e}`);const t=a(e,"utf8");return JSON.parse(t)}static writeMarkdown(e,t){const s=n(e);i(s,{recursive:!0}),c(e,t,"utf8")}static formatKnowledgeAsMarkdown(e){return`# ${e.title}\n\n**ID:** ${e.id}\n**Summary:** ${e.summary}\n**Knowledge Type:** ${e.knowledge_type}\n**Status:** ${e.status}\n**Scope:** ${e.scope}\n**Source Type:** ${e.source_type}\n${e.source_file?`**Source File:** ${e.source_file}`:""}\n${e.contributor?`**Contributor:** ${e.contributor}`:""}\n${e.created_at?`**Created At:** ${e.created_at}`:""}\n${e.updated_at?`**Updated At:** ${e.updated_at}`:""}\n\n## Content\n\n${e.content}\n`}static extractKnowledgeForJson(e){return{title:e.title,summary:e.summary,content:e.content,knowledge_type:e.knowledge_type,status:e.status,scope:e.scope,source_type:e.source_type,source_file:e.source_file||null,contributor:e.contributor||null}}}const Vm=R(),Jm=D("mcp-server","mcp-server");class Km{constructor(){this.knowledgeManagement=new Q,this.tempDir=Vm.tmp,this.server=new Cm({name:"knowledge-bank",version:q.version},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.registerTool("knowledge_create",{description:"Create a new knowledge item",inputSchema:f.object({session_id:f.string().describe("Session ID for tracking, can be omitted to use env vars CLAUDE_SESSION_ID"),title:f.string().optional().describe("Knowledge title"),summary:f.string().optional().describe("Knowledge summary"),content:f.string().optional().describe("Knowledge content"),scope:f.enum(w).optional().describe("Scope of knowledge"),source_type:f.enum(b).optional().describe("Source type"),knowledge_type:f.enum(k).optional().describe("Knowledge type"),status:f.enum($).optional().describe("Status of knowledge"),source_file:f.string().optional().describe("Source file path (optional)"),contributor:f.string().optional().describe("Contributor name (optional)"),from:f.string().optional().describe("Load knowledge data from JSON file")})},async e=>await this.handleCreate(e)),this.server.registerTool("knowledge_get",{description:"Get a knowledge item by ID",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),to:f.string().optional().describe("Save knowledge to markdown file")})},async e=>await this.handleGet(e)),this.server.registerTool("knowledge_update",{description:"Update a knowledge item",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),title:f.string().optional().describe("Knowledge title"),summary:f.string().optional().describe("Knowledge summary"),content:f.string().optional().describe("Knowledge content"),scope:f.enum(w).optional().describe("Scope of knowledge"),source_type:f.enum(b).optional().describe("Source type"),knowledge_type:f.enum(k).optional().describe("Knowledge type"),status:f.enum($).optional().describe("Status of knowledge"),source_file:f.string().optional().describe("Source file path"),contributor:f.string().optional().describe("Contributor name"),from:f.string().optional().describe("Load update data from JSON file")})},async e=>await this.handleUpdate(e)),this.server.registerTool("knowledge_delete",{description:"Delete a knowledge item",inputSchema:f.object({id:f.number().describe("Knowledge item ID")})},async e=>await this.handleDelete(e)),this.server.registerTool("knowledge_list",{description:"List knowledge items with optional filters",inputSchema:f.object({scope:f.enum(w).optional().describe("Filter by scope"),status:f.enum($).optional().describe("Filter by status"),knowledge_type:f.enum(k).optional().describe("Filter by knowledge type"),limit:f.number().default(100).describe("Limit number of results"),offset:f.number().default(0).describe("Offset for pagination"),to:f.string().optional().describe("Save results to JSON file")})},async e=>await this.handleList(e)),this.server.registerTool("knowledge_search",{description:"Search knowledge items by text query",inputSchema:f.object({query:f.array(f.string()).describe("Search query terms"),limit:f.number().default(10).describe("Limit number of results"),to:f.string().optional().describe("Save results to JSON file")})},async e=>await this.handleSearch(e)),this.server.registerTool("knowledge_update_status",{description:"Update knowledge item status",inputSchema:f.object({id:f.number().describe("Knowledge item ID"),status:f.enum($).describe("New status")})},async e=>await this.handleUpdateStatus(e)),this.server.registerTool("knowledge_stats",{description:"Get knowledge statistics",inputSchema:f.object({})},async()=>await this.handleStats())}async handleCreate(e){let n=e;if(e.from){const s=t.join(this.tempDir,t.basename(e.from));if(!Hm.exists(s))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${s}`},null,2)}],isError:!0};try{n=Hm.readJson(s)}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}const s=await this.knowledgeManagement.create({title:n.title,summary:n.summary,content:n.content,scope:n.scope,source_type:n.source_type,knowledge_type:n.knowledge_type,status:n.status,source_file:n.source_file,contributor:n.contributor,session_id:e.session_id||process.env.CLAUDE_SESSION_ID||n.session_id||"unknown-session"});return e.from?{content:[{type:"text",text:JSON.stringify({id:s.id,title:s.title,message:`Knowledge item created from ${e.from}`,file_path:e.from},null,2)}]}:{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}async handleGet(e){const n=await this.knowledgeManagement.get(e.id);if(!n)return{content:[{type:"text",text:JSON.stringify({error:"Knowledge item not found"},null,2)}],isError:!0};if(e.to)try{const s=t.join(this.tempDir,t.basename(e.to)),r=Hm.formatKnowledgeAsMarkdown(n);return Hm.writeMarkdown(s,r),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Knowledge item ${e.id} saved to ${s}`,file_path:s},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async handleUpdate(e){const{id:n,from:s,...r}=e;let a=r;if(s){const e=t.join(this.tempDir,s);if(!Hm.exists(e))return{content:[{type:"text",text:JSON.stringify({error:`File not found: ${e}`},null,2)}],isError:!0};try{a={...Hm.readJson(e),...r}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error reading JSON file: ${e.message}`},null,2)}],isError:!0}}}const o=await this.knowledgeManagement.update(n,a);return{content:[{type:"text",text:JSON.stringify({id:o.id,session_id:o.session_id,message:"knowledge item updated"},null,2)}]}}async handleDelete(e){return await this.knowledgeManagement.delete(e.id),{content:[{type:"text",text:JSON.stringify({success:!0,message:"Knowledge item deleted successfully"})}]}}async handleList(e={}){const{to:n,...s}=e,r=await this.knowledgeManagement.list(s);if(n)try{const e=t.join(this.tempDir,t.basename(n)),a=r.map(e=>Hm.extractKnowledgeForJson(e));return Hm.writeJson(e,{count:r.length,filters:s,timestamp:(new Date).toISOString(),data:a}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`${r.length} knowledge items saved to ${e}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}async handleSearch(e){const{to:n,query:s,limit:r}=e,a=await this.knowledgeManagement.search(s,r);if(n)try{const e=t.join(this.tempDir,t.basename(n)),o=a.map(e=>Hm.extractKnowledgeForJson(e));return Hm.writeJson(e,{query:s,limit:r,count:a.length,timestamp:(new Date).toISOString(),data:o}),{content:[{type:"text",text:JSON.stringify({success:!0,message:`Search results (${a.length} items) saved to ${e}`,file_path:e},null,2)}]}}catch(e){return{content:[{type:"text",text:JSON.stringify({error:`Error saving file: ${e.message}`},null,2)}],isError:!0}}return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}async handleUpdateStatus(e){const t=await this.knowledgeManagement.updateStatus(e.id,e.status);return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async handleStats(){const e=await this.knowledgeManagement.getStats();return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async run(){const e=new qm;await this.server.connect(e),Jm.logWarn(`Knowledge Bank MCP server running under ${process.cwd()}`)}}const Bm=D("web-server","web-server");class Wm{constructor(e={}){var t;this.port=e.port||3e3,this.isDev=e.dev||!1,this.pathResolver=(t=this.isDev,new M({isDev:t})),this.app=y(),this.database=W,this.server=null,this.connections=new Set,this.md=new v,this.setupApp()}setupApp(){this.app.set("view engine","ejs");const e=this.pathResolver.getWebViewsPath();this.app.set("views",e),this.app.use(_),this.app.set("layout","layout");const t=this.pathResolver.getWebPublicPath();this.app.use(y.static(t)),this.app.use(y.json()),this.app.use(y.urlencoded({extended:!0})),this.app.locals.formatTimestamp=this.formatTimestamp,this.app.locals.renderMarkdown=this.renderMarkdown.bind(this),this.app.locals.formatJsonAsMarkdown=this.formatJsonAsMarkdown.bind(this),this.setupRoutes()}async reconnect(){try{return Bm.logInfo("Reconnecting to database..."),this.database.withConnection(()=>{}),Bm.logInfo("Database reconnection successful"),!0}catch(e){throw Bm.logError("Database reconnection failed:",e),e}}formatTimestamp(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`}renderMarkdown(e){return e?this.md.render(e):""}formatJsonAsMarkdown(e){if(!e)return"";try{const t=JSON.parse(e),n=`\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``;return this.md.render(n)}catch(t){const n=`\`\`\`\n${e}\n\`\`\``;return this.md.render(n)}}setupRoutes(){this.app.get("/api/render/cell",(e,t)=>{const{tableName:n,col:s,value:r}=e.query;t.render("partials/cell",{tableName:n,col:s,val:r,layout:!1})}),this.app.get("/api/render/details",async(e,t)=>{const{tableName:n,id:s}=e.query,r=this.getRowById(n,s);if(!r)return t.status(404).send("Not found");t.render("partials/row-details",{tableName:n,data:r,layout:!1,renderMarkdown:this.renderMarkdown.bind(this),formatJsonAsMarkdown:this.formatJsonAsMarkdown.bind(this),formatTimestamp:this.formatTimestamp})}),this.app.get("/",(e,t)=>{const n=this.getTableNames().map(e=>({name:e,count:this.getTableCount(e)}));t.render("index",{title:"Knowledge Bank Database Browser",tableInfo:n,formatTimestamp:function(e){const t=new Date(parseInt(e));return isNaN(t)?e:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`},layout:"layout"})}),this.app.get("/api/tables",(e,t)=>{try{const e=this.getTableNames();t.json({tables:e})}catch(e){Bm.logError("Error getting tables:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/schema",(e,t)=>{try{const{table:n}=e.params,s=this.getTableSchema(n);t.json({schema:s})}catch(e){Bm.logError("Error getting table schema:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/data",(e,t)=>{try{const{table:n}=e.params,s=parseInt(e.query.page)||1,r=parseInt(e.query.limit)||100,a=(s-1)*r,o={};e.query.session_id&&(o.session_id=e.query.session_id),e.query.first_user_prompt&&(o.first_user_prompt=e.query.first_user_prompt),e.query.cwd&&(o.cwd=e.query.cwd),e.query.knowledge_type&&(o.knowledge_type=e.query.knowledge_type),e.query.scope&&(o.scope=e.query.scope),e.query.git_branch&&(o.git_branch=e.query.git_branch),e.query.name&&(o.name=e.query.name),e.query.title&&(o.title=e.query.title),e.query.uuid&&(o.uuid=e.query.uuid),e.query.type&&(o.type=e.query.type),e.query.search&&(o.search=e.query.search);const i=e.query.sort||"",c=this.getTableData(n,r,a,o,i),u=this.getTableCount(n,o);t.json({data:c,pagination:{page:s,limit:r,total:u,pages:Math.ceil(u/r)}})}catch(e){Bm.logError("Error getting table data:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/tables/:table/row/:id",(e,t)=>{try{const{table:n,id:s}=e.params,r=this.getRowById(n,s);if(!r)return t.status(404).json({error:"Row not found"});t.json({data:r})}catch(n){Bm.logError(`Error getting row from ${e.params.table}:`,n),t.status(500).json({error:n.message})}}),this.app.get("/api/tables/:table/relations",(e,t)=>{try{const{table:n}=e.params,s=this.getTableRelations(n);t.json({relations:s})}catch(e){Bm.logError("Error getting table relations:",e),t.status(500).json({error:e.message})}}),this.app.get("/api/relations",(e,t)=>{try{const e=this.getDatabaseRelations();t.json({relations:e})}catch(e){Bm.logError("Error getting database relations:",e),t.status(500).json({error:e.message})}}),this.app.post("/api/reconnect",async(e,t)=>{try{await this.reconnect(),t.json({success:!0,message:"Database reconnected successfully"})}catch(e){t.status(500).json({success:!1,error:e.message})}}),this.app.get("/tables/:table",(e,t)=>{try{const{table:n}=e.params,s=this.getTableSchema(n),r=this.getTableRelations(n),a=e.query.sort||"",o=this.parseSortParameter(a),i=this.getTableData(n,10,0,{},a),c=this.getEssentialColumns(n,s);t.render("table",{title:`Table: ${n}`,tableName:n,schema:s,relations:r,sampleData:i,essentialColumns:c,sortInfo:o,layout:"layout"})}catch(n){Bm.logError(`Error viewing table ${e.params.table}:`,n),t.status(500).render("error",{title:"Error",error:n.message,layout:"layout"})}})}getTableNames(){return this.database.withConnection(e=>{const t=["session_event","knowledge_item","session","session_detail","knowledge_item_fts"];return e.prepare("\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\n ORDER BY name\n ").all().map(e=>e.name).filter(e=>t.includes(e))})}getTableSchema(e){return this.database.withConnection(t=>t.prepare(`PRAGMA table_info(${e})`).all())}parseSortParameter(e){return e?e.endsWith("_asc")?{column:e.slice(0,-4),direction:"ASC",oppositeDirection:"DESC"}:e.endsWith("_desc")?{column:e.slice(0,-5),direction:"DESC",oppositeDirection:"ASC"}:{column:e,direction:"ASC",oppositeDirection:"DESC"}:{column:null,direction:null,oppositeDirection:null}}getTableData(e,t=100,n=0,s={},r=""){let a="*";"knowledge_item"===e?a="id, session_id, title, summary, scope, source_type, knowledge_type, status, created_at, updated_at":"session"===e?a="id, session_id, first_user_prompt, cwd, git_branch, created_at":"session_event"===e?a="id, session_id, name, created_at":"session_detail"===e&&(a="id, session_id, uuid, type, parentUuid, userType, version, gitBranch, timestamp, created_at");let o="";const i=[];if(Object.keys(s).length>0){const t=(t=>{const n=[],s=[];return Object.entries(t).forEach(([t,r])=>{if(null!=r&&""!==r)if("search"!==t){if("session_id"===t||"first_user_prompt"===t||"git_branch"===t||"name"===t||"title"===t||"uuid"===t||"type"===t)return n.push(`${t} LIKE ?`),void s.push(`%${r}%`);n.push(`${t} = ?`),s.push(r)}else if("knowledge_item"===e){n.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${r}%`;s.push(e,e,e,e)}else if("session"===e){n.push("(session_id LIKE ? OR first_user_prompt LIKE ? OR git_branch LIKE ? OR cwd LIKE ?)");const e=`%${r}%`;s.push(e,e,e,e)}else if("session_event"===e){n.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${r}%`;s.push(e,e)}else if("session_detail"===e){n.push("(uuid LIKE ? OR type LIKE ? OR parentUuid LIKE ? OR session_id LIKE ?)");const e=`%${r}%`;s.push(e,e,e,e)}}),{clause:n.length>0?` WHERE ${n.join(" AND ")}`:"",params:s}})(s);o=t.clause,i.push(...t.params)}let c="";if(r){const e=this.parseSortParameter(r);e.column&&e.direction&&(c=` ORDER BY ${e.column} ${e.direction}`)}else c=" ORDER BY id ASC";return i.push(t,n),this.database.withConnection(t=>t.prepare(`SELECT ${a} FROM ${e}${o}${c} LIMIT ? OFFSET ?`).all(...i))}getTableCount(e,t={}){let n="";const s=[];if(Object.keys(t).length>0){const r=[];Object.entries(t).forEach(([t,n])=>{if(null!=n&&""!==n)if("search"!==t){if("session_id"===t||"first_user_prompt"===t||"git_branch"===t||"name"===t||"title"===t)return r.push(`${t} LIKE ?`),void s.push(`%${n}%`);r.push(`${t} = ?`),s.push(n)}else if("knowledge_item"===e){r.push("(title LIKE ? OR summary LIKE ? OR content LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;s.push(e,e,e,e)}else if("session"===e){r.push("(session_id LIKE ? OR first_user_prompt LIKE ? OR git_branch LIKE ? OR cwd LIKE ?)");const e=`%${n}%`;s.push(e,e,e,e)}else if("session_event"===e){r.push("(name LIKE ? OR session_id LIKE ?)");const e=`%${n}%`;s.push(e,e)}}),r.length>0&&(n=` WHERE ${r.join(" AND ")}`)}return this.database.withConnection(t=>t.prepare(`SELECT COUNT(*) as count FROM ${e}${n}`).get(...s).count)}getRowById(e,t){return this.database.withConnection(n=>n.prepare(`SELECT * FROM ${e} WHERE id = ?`).get(t))}getEssentialColumns(e,t){const n=t.map(e=>e.name);return({knowledge_item:["id","title","summary","knowledge_type","scope","session_id","created_at"],session:["id","session_id","first_user_prompt","cwd","git_branch","created_at"],session_event:["id","session_id","name","created_at"],session_detail:["id","session_id","uuid","type","parentUuid","timestamp","created_at"],knowledge_item_fts:["rowid","title","summary"]}[e]||["id","name","title","created_at"]).filter(e=>n.includes(e))}getTableRelations(e){return this.database.withConnection(t=>t.prepare(`PRAGMA foreign_key_list(${e})`).all())}getDatabaseRelations(){const e=this.getTableNames(),t={};return e.forEach(e=>{t[e]={foreignKeys:this.getTableRelations(e),referencedBy:[]}}),e.forEach(e=>{t[e].foreignKeys.forEach(n=>{const s=n.table;t[s]&&t[s].referencedBy.push({table:e,from:n.from,to:n.to})})}),t}start(){return new Promise((e,t)=>{try{this.database.withConnection(e=>{I(e)}),this.server=this.app.listen(this.port,()=>{this.isDev?(Bm.logInfo(`Web server started in development mode on port ${this.port}`),Bm.logInfo("🚀 Running from source code (no build required)")):Bm.logInfo(`Web server started on port ${this.port}`),Bm.logInfo(`Open http://localhost:${this.port} in your browser`),e(this)}),this.server.on("connection",e=>{this.connections.add(e),e.on("close",()=>{this.connections.delete(e)})})}catch(e){Bm.logError("Error starting web server:",e),t(e)}})}stop(){return new Promise((e,t)=>{if(!this.server)return void e();const n=setTimeout(()=>{Bm.logWarn("Forcing server shutdown due to timeout");for(const e of this.connections)e.destroy();this.connections.clear(),this.server=null,e()},5e3);this.server.close(s=>{if(clearTimeout(n),s){Bm.logError("Error closing web server:",s);for(const e of this.connections)e.destroy();this.connections.clear(),t(s)}else Bm.logInfo("Web server stopped gracefully"),this.server=null,this.connections.clear(),e()}),this.server.unref()})}}const Gm=D("web-command","web-command");class Xm{constructor(e,t,n={}){this.sessionId=e,this.transcriptPath=t,this.options=n,this.logger=D(e,"ParseTranscriptCommand")}async execute(){try{this.logger.logInfo("Starting transcript parsing",{sessionId:this.sessionId,transcriptPath:this.transcriptPath,options:this.options});const e=new Se(this.sessionId);if(this.options.analyze){const t=await e.analyzeTranscript(this.transcriptPath);return t.success?(this.logger.logInfo("Transcript analysis completed",t.stats),console.log("\n=== Transcript Analysis ==="),console.log(`File: ${t.stats.fileName}`),console.log(`File Size: ${(t.stats.fileSize/1024).toFixed(2)} KB`),console.log(`Total Lines: ${t.stats.totalLines}`),console.log(`Valid Entries: ${t.stats.validEntries}`),console.log(`Filtered Out (file-history-snapshot): ${t.stats.filteredOut}`),console.log(`Entries with UUID: ${t.stats.hasUuid}`),console.log(`Entries missing UUID: ${t.stats.missingUuid}`),console.log(`Parse Errors: ${t.stats.errors}`),Object.keys(t.stats.typeDistribution).length>0&&(console.log("\nType Distribution:"),Object.entries(t.stats.typeDistribution).sort((e,t)=>t[1]-e[1]).forEach(([e,t])=>{console.log(` ${e}: ${t}`)}))):(this.logger.logError("Transcript analysis failed",{error:t.error}),console.error(`Analysis failed: ${t.error}`)),t}if(!this.options.force&&await e.isTranscriptProcessed(this.transcriptPath)){const e="Transcript already processed. Use --force to reprocess.";return this.logger.logInfo(e),console.log(e),{success:!0,skipped:!0,reason:"Already processed"}}const n=await e.parseTranscript(this.transcriptPath);return n.success?(this.logger.logInfo("Transcript parsing completed successfully",n.stats),console.log("\n=== Transcript Parsing Results ==="),console.log(`Session ID: ${n.sessionId}`),console.log(`File: ${t.basename(n.filePath)}`),console.log(`Total Lines: ${n.stats.totalLines}`),console.log(`Valid Entries: ${n.stats.validEntries}`),console.log(`Filtered Out: ${n.stats.filteredOut}`),console.log(`Successfully Inserted: ${n.stats.inserted}`),console.log(`Duplicates Skipped: ${n.stats.duplicates}`),console.log(`Errors: ${n.stats.errors}`),n.stats.errorDetails&&n.stats.errorDetails.length>0&&(console.log("\nError Details:"),n.stats.errorDetails.forEach(e=>{console.log(` ${e}`)}))):(this.logger.logError("Transcript parsing failed",{error:n.error}),console.error(`\nParsing failed: ${n.error}`)),n}catch(e){const t=`Command execution failed: ${e.message}`;return this.logger.logError(t,{error:e.stack}),console.error(t),{success:!1,error:e.message}}}}const Ym=q.version,Qm=R(),ef=new e;ef.name("knowledge-bank").description("Claude Code plugin for lightweight knowledge management").version(Ym);const tf=new Q;ef.command("install").description("Install knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e||await new Promise((e,t)=>{u(`claude plugin marketplace add ${U}`,(n,s,r)=>{n?t(n):(r&&console.error(r),console.log(s),e())})}),await new Promise((e,t)=>{u("claude plugin install core@knowledge-bank",(n,s,r)=>{n?t(n):(r&&console.error(r),console.log(s),e())})})}).then(async()=>{r.existsSync(G.tmp)||r.mkdirSync(G.tmp,{recursive:!0}),W.withConnection(e=>{I(e)})}).catch(e=>{console.error("Error during installation:",e)})}()}),ef.command("uninstall").description("Remove knowledge bank plugin").action(async()=>{await async function(){K().then(e=>e.find(e=>"knowledge-bank"===e.name)).then(async e=>{e?(await new Promise((e,t)=>{u("claude plugin uninstall core@knowledge-bank",(n,s,r)=>{n?t(n):(r&&console.error(r),console.log(s),e())})}),await new Promise((e,t)=>{u("claude plugin marketplace remove knowledge-bank",(n,s,r)=>{n?t(n):(r&&console.error(r),console.log(s),e())})})):console.log("knowledge-bank plugin is not installed.")}).catch(e=>{console.error("Error during uninstallation:",e)})}()});const nf=ef.command("knowledge").description("Manage knowledge items");nf.command("create").description("Create a new knowledge item").requiredOption("-t, --title <title>","[REQUIRED] Knowledge title").requiredOption("-s, --summary <summary>","[REQUIRED] Knowledge summary").requiredOption("-c, --content <content>","[REQUIRED] Knowledge content").requiredOption("--scope <scope>",`[REQUIRED] Scope: ${w.join(", ")}`).requiredOption("--source-type <type>",`[REQUIRED] Source type: ${b.join(", ")}`).requiredOption("--knowledge-type <type>",`[REQUIRED] Knowledge type: ${k.join(", ")}`).requiredOption("--status <status>",`[REQUIRED] Status: ${Object.values($).join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "draft",\n "source_file": null,\n "contributor": null,\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T10:30:00Z"\n}').action(async e=>{console.log("creating knowledge");const t=await tf.create({title:e.title,summary:e.summary,content:e.content,scope:e.scope,source_type:e.sourceType,knowledge_type:e.knowledgeType,status:e.status,source_file:e.sourceFile,contributor:e.contributor});console.log(JSON.stringify(t,null,2))}),nf.command("get").description("Get a knowledge item by ID").argument("<id>","Knowledge item ID",parseInt).addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T11:45:00Z"\n}').action(async e=>{const t=await tf.get(e);t?console.log(JSON.stringify(t,null,2)):(console.log("Knowledge item not found"),process.exit(1))}),nf.command("update").description("Update a knowledge item").argument("<id>","Knowledge item ID",parseInt).option("-t, --title <title>","[OPTION] Knowledge title").option("-s, --summary <summary>","[OPTION] Knowledge summary").option("-c, --content <content>","[OPTION] Knowledge content").option("--scope <scope>",`[OPTION] Scope: ${w.join(", ")}`).option("--source-type <type>",`[OPTION] Source type: ${b.join(", ")}`).option("--knowledge-type <type>",`[OPTION] Knowledge type: ${k.join(", ")}`).option("--status <status>",`[OPTION] Status: ${Object.values($).join(", ")}`).option("--source-file <file>","[OPTION] Source file path").option("--contributor <contributor>","[OPTION] Contributor name").addHelpText("after",'\nOutput Example:\n{\n "id": 123,\n "title": "Updated React Hook Pattern",\n "summary": "Enhanced best practices for custom hooks",\n "content": "Always prefix with \'use\', follow hooks rules, and add proper TypeScript types",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "source_file": "src/hooks/useCustomHook.ts",\n "contributor": "Claude",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n}').action(async(e,t)=>{const n=await tf.update(e,{title:t.title,summary:t.summary,content:t.content,scope:t.scope,source_type:t.sourceType,knowledge_type:t.knowledgeType,status:t.status,source_file:t.sourceFile,contributor:t.contributor});console.log(JSON.stringify(n,null,2))}),nf.command("delete").description("Delete a knowledge item").argument("<id>","Knowledge item ID",parseInt).addHelpText("after","\nOutput Example:\nKnowledge item deleted successfully").action(async e=>{await tf.delete(e),console.log("Knowledge item deleted successfully")}),nf.command("list").description("List knowledge items").option("--scope <scope>","[OPTION] Filter by scope").option("--status <status>","[OPTION] Filter by status").option("--knowledge-type <type>","[OPTION] Filter by knowledge type").option("--limit <limit>","[OPTION] Limit number of results",parseInt,100).option("--offset <offset>","[OPTION] Offset for pagination",parseInt,0).addHelpText("after",'\nOutput Example:\n{\n "items": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "created_at": "2026-01-22T10:30:00Z",\n "updated_at": "2026-01-22T12:15:00Z"\n },\n {\n "id": 124,\n "title": "API Error Handling",\n "summary": "Standard error handling patterns",\n "scope": "project",\n "source_type": "developer",\n "knowledge_type": "architecture",\n "status": "draft",\n "created_at": "2026-01-22T11:00:00Z",\n "updated_at": "2026-01-22T11:00:00Z"\n }\n ],\n "total": 2,\n "limit": 10,\n "offset": 0\n}').action(async e=>{const t=await tf.list({scope:e.scope,status:e.status,knowledge_type:e.knowledgeType,limit:e.limit,offset:e.offset});console.log(JSON.stringify(t,null,2))}),nf.command("search").description("Search knowledge items by text").argument("<query...>","Search query terms").option("-l, --limit <limit>","[OPTION] Limit number of results",parseInt,10).addHelpText("after",'\nUsage Examples:\n $ knowledge search react hooks\n $ knowledge search "react hooks" --limit 5\n $ knowledge search title:api content:auth\n\nOutput Example:\n{\n "results": [\n {\n "id": 123,\n "title": "React Custom Hook Pattern",\n "summary": "Best practices for custom hooks",\n "content": "Always prefix with \'use\' and follow hooks rules",\n "scope": "project",\n "source_type": "ai",\n "knowledge_type": "code_pattern",\n "status": "verified",\n "relevance_score": 0.95,\n "created_at": "2026-01-22T10:30:00Z"\n }\n ],\n "total_results": 1,\n "query": "react hooks",\n "limit": 10\n}').action(async(e,t)=>{const n=await tf.search(e,t.limit);console.log(JSON.stringify(n,null,2))}),nf.command("update-status").description("Update knowledge item status").argument("<id>","Knowledge item ID",parseInt).argument("<status>",`New status: ${Object.values($).join(", ")}`).addHelpText("after",'\nOutput Example:\n{\n "success": true,\n "message": "Status updated successfully",\n "id": 123,\n "old_status": "draft",\n "new_status": "verified",\n "updated_at": "2026-01-22T12:30:00Z"\n}').action(async(e,t)=>{const n=await tf.updateStatus(e,t);console.log(JSON.stringify(n,null,2))}),nf.command("stats").description("Get knowledge statistics").addHelpText("after",'\nOutput Example:\n{\n "total_items": 156,\n "by_scope": {\n "personal": 45,\n "project": 89,\n "organization": 22\n },\n "by_status": {\n "draft": 67,\n "suggested": 34,\n "verified": 55\n },\n "by_knowledge_type": {\n "code_pattern": 42,\n "architecture": 38,\n "config": 25,\n "pitfall": 31,\n "api_usage": 20\n },\n "by_source_type": {\n "developer": 78,\n "architect": 23,\n "reviewer": 19,\n "ai": 36\n },\n "recent_activity": {\n "created_last_7_days": 12,\n "updated_last_7_days": 8\n }\n}').action(async()=>{const e=await tf.getStats();console.log(JSON.stringify(e,null,2))}),ef.command("session-start").description("Hook: Called when a Claude Code session starts").action(async()=>{await se.parseInput().then(async e=>{new ye(e).execute().then(e=>{console.error("session-start hook executed",e),e.send()})})}),ef.command("session-end").description("Hook: Called when a Claude Code session ends").action(async()=>{await se.parseInput().then(async e=>{new Te(e).execute().then(e=>{e.send()})})}),ef.command("notification").description("Hook: Called when a notification is triggered").action(async()=>{await se.parseInput().then(async e=>{new _e(e).execute().then(e=>{e.send()})})}),ef.command("permission-request").description("Hook: Called when a permission request is made").action(async()=>{await se.parseInput().then(async e=>{new ve(e).execute().then(e=>{e.send()})})}),ef.command("pre-tool-use").description("Hook: Called before a tool is used").action(async()=>{await se.parseInput().then(async e=>{new $e(e).execute().then(e=>{e.send()})})}),ef.command("post-tool-use").description("Hook: Called after a tool is used").action(async()=>{await se.parseInput().then(async e=>{new we(e).execute().then(e=>{e.send()})})}),ef.command("pre-compact").description("Hook: Called before compacting the session").action(async()=>{await se.parseInput().then(async e=>{new be(e).execute().then(e=>{e.send()})})}),ef.command("stop").description("Hook: Called when a stop signal is received").action(async()=>{await se.parseInput().then(async e=>{new Oe(e).execute().then(e=>{e.send()})})}),ef.command("subagent-stop").description("Hook: Called when a subagent stops").action(async()=>{await se.parseInput().then(async e=>{new xe(e).execute().then(e=>{e.send()})})}),ef.command("user-prompt-submit").description("Hook: Called when a user submits a prompt").action(async()=>{await se.parseInput().then(async e=>{new Ie(e).execute().then(e=>{e.send()})})}),ef.command("mcp-server").description("Start the Knowledge Bank MCP server").action(async()=>{const e=new Km;await e.run()}),ef.command("web").description("Start a web server for browsing the database").option("-p, --port <port>","Port to listen on",e=>parseInt(e,10),3e3).option("-d, --dev","Start from source code (development mode)").addHelpText("after","\nUsage Example:\n $ knowledge-bank web\n $ knowledge-bank web --port 8080\n $ knowledge-bank web --dev\n $ knowledge-bank web --dev --port 8080\n\nOptions:\n --dev Start in development mode from source code\n --port Specify the port number (default: 3000)\n\nThis command starts a web server that allows you to browse the SQLite database tables\nand their relationships. Open the URL displayed in your browser after starting the server.\n\nDevelopment mode (--dev) runs the server directly from source code without building,\nuseful for development and debugging purposes.").action(async e=>{await async function(e={}){const t=e.port||3e3,n=e.dev||!1;n?Gm.logInfo(`Starting web server in development mode (from source) on port ${t}...`):Gm.logInfo(`Starting web server on port ${t}...`),console.log("================================================="),console.log(" Knowledge Bank Database Browser"),n&&console.log(" 🚀 Development Mode (Source Code)"),console.log("================================================="),console.log(` Starting server on port ${t}...`),console.log(` Open http://localhost:${t} in your browser`),console.log(" Press Ctrl+C to stop the server"),console.log("=================================================");const s=new Wm({port:t,dev:n}),r=async e=>{Gm.logInfo(`\nReceived ${e}, shutting down web server gracefully...`),console.log("\nShutting down server...");try{await s.stop(),Gm.logInfo("Web server stopped successfully"),console.log("Server stopped successfully"),process.exit(0)}catch(e){Gm.logError("Error during shutdown:",e),console.error("Error during shutdown:",e.message),process.exit(0)}};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM")),process.on("unhandledRejection",(e,t)=>{Gm.logError("Unhandled Rejection at:",t,"reason:",e)}),await s.start();const a=setInterval(()=>{},1e3),o=r,i=async e=>{clearInterval(a),await o(e)};return process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM"),process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),s}(e)}),ef.command("config").description("Get Knowledge Bank configuration settings").option("-t --temp","Get temporary directory path").action(async e=>{e.temp?console.log(Qm.tmp):console.error("unsupported option. Use --temp to get the temporary directory path.")}),function(e){e.command("parse-transcript <session_id> <transcript_path>").description("Parse a Claude Code transcript JSONL file and store in session_detail table").option("--analyze","Only analyze the transcript without storing data").option("--force","Force reprocessing even if already processed").action(async(e,t,n)=>{const s=new Xm(e,t,n);(await s.execute()).success||process.exit(1)})}(ef),ef.parse(process.argv);