From e2b684f055a0984c91ca993184e719f653718d0d Mon Sep 17 00:00:00 2001 From: Ryan Malia Date: Tue, 30 Jun 2026 18:45:25 -0700 Subject: [PATCH 1/2] fix(install): repair broken smart-explore runtime provisioning Plugin installation suppressed dependency lifecycle scripts, leaving tree-sitter-cli installed without its platform executable. The installer still reported success, but smart_search returned zero symbols and smart_outline could not parse supported files. On Windows the runtime resolver also ignored the downloaded tree-sitter.exe because it checked only the extensionless name. Tree-sitter queries additionally attempted to write compiled grammar data under the user cache, which may be read-only in managed environments. Those failures were suppressed as empty search results. This logic lives in the shared install/repair path, not a Codex-only branch, so the fix and its validation apply to every IDE. Fix runtime provisioning by: - running only tree-sitter-cli's required install script after the script-suppressed dependency install - validating the binary through a timed `tree-sitter --version` probe - resolving tree-sitter.exe before the extensionless name on Windows - installing the Codex plugin directly from the registered local marketplace - writing the Codex .install-version marker only after runtime provisioning succeeds, so it is a truthful "runtime ready" signal - using a writable process-local cache for compiled Tree-sitter grammars - failing installation when the runtime cannot be installed or validated - adding installer, parser, and corrupt-binary regression coverage - documenting the explicit Codex CLI installation command Regenerate the MCP server bundle with the parser fix. --- README.md | 8 +- plugin/scripts/mcp-server.cjs | 126 +++++++++--------- src/npx-cli/install/setup-runtime.ts | 76 ++++++++++- .../integrations/CodexCliInstaller.ts | 79 ++++++++++- src/services/smart-file-read/parser.ts | 36 ++++- tests/cli/verify-critical-modules.test.ts | 70 +++++++++- tests/install-non-tty.test.ts | 11 +- tests/integration/codex-cli-installer.test.ts | 87 +++++++++++- tests/services/smart-file-read/parser.test.ts | 36 +++++ 9 files changed, 444 insertions(+), 85 deletions(-) create mode 100644 tests/services/smart-file-read/parser.test.ts diff --git a/README.md b/README.md index cd764a7dc..41b15bffa 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,12 @@ Or install for Antigravity CLI ([setup guide](https://docs.claude-mem.ai/antigra npx claude-mem install --ide antigravity ``` +Or install for Codex CLI: + +```bash +npx claude-mem install --ide codex-cli +``` + Or install from the plugin marketplace inside Claude Code: ```bash @@ -156,7 +162,7 @@ Or install from the plugin marketplace inside Claude Code: /plugin install claude-mem ``` -Restart Claude Code. Context from previous sessions will automatically appear in new sessions. +Restart the selected IDE. Context from previous sessions will automatically appear in new sessions. > **Note:** Claude-Mem is also published on npm, but `npm install -g claude-mem` installs the **SDK/library only** — it does not register the plugin hooks or set up the worker service. Always install via `npx claude-mem install` or the `/plugin` commands above. diff --git a/plugin/scripts/mcp-server.cjs b/plugin/scripts/mcp-server.cjs index 962754468..908314232 100755 --- a/plugin/scripts/mcp-server.cjs +++ b/plugin/scripts/mcp-server.cjs @@ -1,85 +1,85 @@ #!/usr/bin/env node -"use strict";var j_=Object.create;var Hs=Object.defineProperty;var L_=Object.getOwnPropertyDescriptor;var U_=Object.getOwnPropertyNames;var q_=Object.getPrototypeOf,Z_=Object.prototype.hasOwnProperty;var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Ru=(t,e)=>{for(var r in e)Hs(t,r,{get:e[r],enumerable:!0})},F_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of U_(e))!Z_.call(t,o)&&o!==r&&Hs(t,o,{get:()=>e[o],enumerable:!(n=L_(e,o))||n.enumerable});return t};var $t=(t,e,r)=>(r=t!=null?j_(q_(t)):{},F_(e||!t||!t.__esModule?Hs(r,"default",{value:t,enumerable:!0}):r,t));var pn=E(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.regexpCode=q.getEsmExportName=q.getProperty=q.safeStringify=q.stringify=q.strConcat=q.addCodeArg=q.str=q._=q.nil=q._Code=q.Name=q.IDENTIFIER=q._CodeOrName=void 0;var ln=class{};q._CodeOrName=ln;q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wt=class extends ln{constructor(e){if(super(),!q.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};q.Name=Wt;var je=class extends ln{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Wt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};q._Code=je;q.nil=new je("");function Yf(t,...e){let r=[t[0]],n=0;for(;n{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var xe=pn(),la=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Mo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Mo||(Pe.UsedValueState=Mo={}));Pe.varKinds={const:new xe.Name("const"),let:new xe.Name("let"),var:new xe.Name("var")};var Co=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof xe.Name?e:this.name(e)}name(e){return new xe.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Pe.Scope=Co;var No=class extends xe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,xe._)`.${new xe.Name(r)}[${n}]`}};Pe.ValueScopeName=No;var $b=(0,xe._)`\n`,da=class extends Co{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$b:xe.nil}}get(){return this._scope}name(e){return new No(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,xe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=xe.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Mo.Started);let l=r(u);if(l){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;s=(0,xe._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,xe._)`${s}${l}${this.opts._n}`;else throw new la(u);c.set(u,Mo.Completed)})}return s}};Pe.ValueScope=da});var A=E(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var j=pn(),Je=pa(),At=pn();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return At.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return At.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return At.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return At.Name}});var Uo=pa();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return Uo.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return Uo.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return Uo.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return Uo.varKinds}});M.operators={GT:new j._Code(">"),GTE:new j._Code(">="),LT:new j._Code("<"),LTE:new j._Code("<="),EQ:new j._Code("==="),NEQ:new j._Code("!=="),NOT:new j._Code("!"),OR:new j._Code("||"),AND:new j._Code("&&"),ADD:new j._Code("+")};var yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},fa=class extends yt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Je.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=hr(this.rhs,e,r)),this}get names(){return this.rhs instanceof j._CodeOrName?this.rhs.names:{}}},Do=class extends yt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof j.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=hr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof j.Name?{}:{...this.lhs.names};return Lo(e,this.rhs)}},ma=class extends Do{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ha=class extends yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ga=class extends yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},_a=class extends yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ya=class extends yt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=hr(this.code,e,r),this}get names(){return this.code instanceof j._CodeOrName?this.code.names:{}}},fn=class extends yt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(xb(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Jt(e,r.names),{})}},St=class extends fn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Sa=class extends fn{},mr=class extends St{};mr.kind="else";var Vt=class t extends St{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new mr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Xf(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=hr(this.condition,e,r),this}get names(){let e=super.names;return Lo(e,this.condition),this.else&&Jt(e,this.else.names),e}};Vt.kind="if";var Kt=class extends St{};Kt.kind="for";var va=class extends Kt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=hr(this.iteration,e,r),this}get names(){return Jt(super.names,this.iteration.names)}},ba=class extends Kt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Je.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Lo(super.names,this.from);return Lo(e,this.to)}},jo=class extends Kt{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=hr(this.iterable,e,r),this}get names(){return Jt(super.names,this.iterable.names)}},mn=class extends St{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};mn.kind="func";var hn=class extends fn{render(e){return"return "+super.render(e)}};hn.kind="return";var Ea=class extends St{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Jt(e,this.catch.names),this.finally&&Jt(e,this.finally.names),e}},gn=class extends St{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};gn.kind="catch";var _n=class extends St{render(e){return"finally"+super.render(e)}};_n.kind="finally";var wa=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` -`:""},this._extScope=e,this._scope=new Je.Scope({parent:e}),this._nodes=[new Sa]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new fa(e,s,n)),s}const(e,r,n){return this._def(Je.varKinds.const,e,r,n)}let(e,r,n){return this._def(Je.varKinds.let,e,r,n)}var(e,r,n){return this._def(Je.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Do(e,r,n))}add(e,r){return this._leafNode(new ma(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==j.nil&&this._leafNode(new ya(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,j.addCodeArg)(r,o));return r.push("}"),new j._Code(r)}if(e,r,n){if(this._blockNode(new Vt(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vt(e))}else(){return this._elseNode(new mr)}endIf(){return this._endBlockNode(Vt,mr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new va(e),r)}forRange(e,r,n,o,s=this.opts.es5?Je.varKinds.var:Je.varKinds.let){let i=this._scope.toName(e);return this._for(new ba(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Je.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof j.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,j._)`${i}.length`,a=>{this.var(s,(0,j._)`${i}[${a}]`),n(s)})}return this._for(new jo("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Je.varKinds.var:Je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,j._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new jo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kt)}label(e){return this._leafNode(new ha(e))}break(e){return this._leafNode(new ga(e))}return(e){let r=new hn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(hn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ea;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new gn(s),r(s)}return n&&(this._currNode=o.finally=new _n,this.code(n)),this._endBlockNode(gn,_n)}throw(e){return this._leafNode(new _a(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=j.nil,n,o){return this._blockNode(new mn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(mn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=wa;function Jt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Lo(t,e){return e instanceof j._CodeOrName?Jt(t,e.names):t}function hr(t,e,r){if(t instanceof j.Name)return n(t);if(!o(t))return t;return new j._Code(t._items.reduce((s,i)=>(i instanceof j.Name&&(i=n(i)),i instanceof j._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof j._Code&&s._items.some(i=>i instanceof j.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function xb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Xf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,j._)`!${ka(t)}`}M.not=Xf;var Pb=Qf(M.operators.AND);function Tb(...t){return t.reduce(Pb)}M.and=Tb;var zb=Qf(M.operators.OR);function Rb(...t){return t.reduce(zb)}M.or=Rb;function Qf(t){return(e,r)=>e===j.nil?r:r===j.nil?e:(0,j._)`${ka(e)} ${t} ${ka(r)}`}function ka(t){return t instanceof j.Name?t:(0,j._)`(${t})`}});var Z=E(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var K=A(),Ib=pn();function Ob(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=Ob;function Ab(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(rm(t,e),!nm(e,t.self.RULES.all))}C.alwaysValidSchema=Ab;function rm(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||im(t,`unknown keyword: "${s}"`)}C.checkUnknownRules=rm;function nm(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=nm;function Mb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Mb;function Cb({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${t}${e}${(0,K.getProperty)(n)}`}C.schemaRefOrVal=Cb;function Nb(t){return om(decodeURIComponent(t))}C.unescapeFragment=Nb;function Db(t){return encodeURIComponent(xa(t))}C.escapeFragment=Db;function xa(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=xa;function om(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=om;function jb(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=jb;function em({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof K.Name?(s instanceof K.Name?t(o,s,i):e(o,s,i),i):s instanceof K.Name?(e(o,i,s),s):r(s,i);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}C.mergeEvaluated={props:em({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,K._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,K._)`${r} || {}`),Pa(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:sm}),items:em({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,K._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,K._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function sm(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,K._)`{}`);return e!==void 0&&Pa(t,r,e),r}C.evaluatedPropsToName=sm;function Pa(t,e,r){Object.keys(r).forEach(n=>t.assign((0,K._)`${e}${(0,K.getProperty)(n)}`,!0))}C.setEvaluated=Pa;var tm={};function Lb(t,e){return t.scopeValue("func",{ref:e,code:tm[e.code]||(tm[e.code]=new Ib._Code(e.code))})}C.useFunc=Lb;var $a;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})($a||(C.Type=$a={}));function Ub(t,e,r){if(t instanceof K.Name){let n=e===$a.Num;return r?n?(0,K._)`"[" + ${t} + "]"`:(0,K._)`"['" + ${t} + "']"`:n?(0,K._)`"/" + ${t}`:(0,K._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(t).toString():"/"+xa(t)}C.getErrorPath=Ub;function im(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=im});var vt=E(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var ye=A(),qb={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};Ta.default=qb});var yn=E(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.extendErrors=Se.resetErrorsCount=Se.reportExtraError=Se.reportError=Se.keyword$DataError=Se.keywordError=void 0;var U=A(),qo=Z(),we=vt();Se.keywordError={message:({keyword:t})=>(0,U.str)`must pass "${t}" keyword validation`};Se.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,U.str)`"${t}" keyword must be ${e} ($data)`:(0,U.str)`"${t}" keyword is invalid ($data)`};function Zb(t,e=Se.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=um(t,e,r);n??(i||a)?am(s,c):cm(o,(0,U._)`[${c}]`)}Se.reportError=Zb;function Fb(t,e=Se.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=um(t,e,r);am(o,a),s||i||cm(n,we.default.vErrors)}Se.reportExtraError=Fb;function Hb(t,e){t.assign(we.default.errors,e),t.if((0,U._)`${we.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,U._)`${we.default.vErrors}.length`,e),()=>t.assign(we.default.vErrors,null)))}Se.resetErrorsCount=Hb;function Wb({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,we.default.errors,a=>{t.const(i,(0,U._)`${we.default.vErrors}[${a}]`),t.if((0,U._)`${i}.instancePath === undefined`,()=>t.assign((0,U._)`${i}.instancePath`,(0,U.strConcat)(we.default.instancePath,s.errorPath))),t.assign((0,U._)`${i}.schemaPath`,(0,U.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,U._)`${i}.schema`,r),t.assign((0,U._)`${i}.data`,n))})}Se.extendErrors=Wb;function am(t,e){let r=t.const("err",e);t.if((0,U._)`${we.default.vErrors} === null`,()=>t.assign(we.default.vErrors,(0,U._)`[${r}]`),(0,U._)`${we.default.vErrors}.push(${r})`),t.code((0,U._)`${we.default.errors}++`)}function cm(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,U._)`new ${t.ValidationError}(${e})`):(r.assign((0,U._)`${n}.errors`,e),r.return(!1))}var Gt={keyword:new U.Name("keyword"),schemaPath:new U.Name("schemaPath"),params:new U.Name("params"),propertyName:new U.Name("propertyName"),message:new U.Name("message"),schema:new U.Name("schema"),parentSchema:new U.Name("parentSchema")};function um(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,U._)`{}`:Vb(t,e,r)}function Vb(t,e,r={}){let{gen:n,it:o}=t,s=[Kb(o,r),Jb(t,r)];return Gb(t,e,s),n.object(...s)}function Kb({errorPath:t},{instancePath:e}){let r=e?(0,U.str)`${t}${(0,qo.getErrorPath)(e,qo.Type.Str)}`:t;return[we.default.instancePath,(0,U.strConcat)(we.default.instancePath,r)]}function Jb({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,U.str)`${e}/${t}`;return r&&(o=(0,U.str)`${o}${(0,qo.getErrorPath)(r,qo.Type.Str)}`),[Gt.schemaPath,o]}function Gb(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Gt.keyword,o],[Gt.params,typeof e=="function"?e(t):e||(0,U._)`{}`]),c.messages&&n.push([Gt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Gt.schema,i],[Gt.parentSchema,(0,U._)`${l}${d}`],[we.default.data,s]),u&&n.push([Gt.propertyName,u])}});var dm=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.boolOrEmptySchema=gr.topBoolOrEmptySchema=void 0;var Yb=yn(),Bb=A(),Xb=vt(),Qb={message:"boolean schema is false"};function eE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?lm(t,!1):typeof r=="object"&&r.$async===!0?e.return(Xb.default.data):(e.assign((0,Bb._)`${n}.errors`,null),e.return(!0))}gr.topBoolOrEmptySchema=eE;function tE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),lm(t)):r.var(e,!0)}gr.boolOrEmptySchema=tE;function lm(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Yb.reportError)(o,Qb,void 0,e)}});var za=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.getRules=_r.isJSONType=void 0;var rE=["string","number","integer","boolean","null","object","array"],nE=new Set(rE);function oE(t){return typeof t=="string"&&nE.has(t)}_r.isJSONType=oE;function sE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}_r.getRules=sE});var Ra=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.shouldUseRule=Mt.shouldUseGroup=Mt.schemaHasRulesForType=void 0;function iE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&pm(t,n)}Mt.schemaHasRulesForType=iE;function pm(t,e){return e.rules.some(r=>fm(t,r))}Mt.shouldUseGroup=pm;function fm(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mt.shouldUseRule=fm});var Sn=E(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var aE=za(),cE=Ra(),uE=yn(),O=A(),mm=Z(),yr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(yr||(ve.DataType=yr={}));function lE(t){let e=hm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ve.getSchemaTypes=lE;function hm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(aE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ve.getJSONTypes=hm;function dE(t,e){let{gen:r,data:n,opts:o}=t,s=pE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,cE.schemaHasRulesForType)(t,e[0]));if(i){let a=Oa(e,n,o.strictNumbers,yr.Wrong);r.if(a,()=>{s.length?fE(t,e,s):Aa(t)})}return i}ve.coerceAndCheckDataType=dE;var gm=new Set(["string","number","integer","boolean","null"]);function pE(t,e){return e?t.filter(r=>gm.has(r)||e==="array"&&r==="array"):[]}function fE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,O._)`typeof ${o}`),a=n.let("coerced",(0,O._)`undefined`);s.coerceTypes==="array"&&n.if((0,O._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,O._)`${o}[0]`).assign(i,(0,O._)`typeof ${o}`).if(Oa(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,O._)`${a} !== undefined`);for(let u of r)(gm.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Aa(t),n.endIf(),n.if((0,O._)`${a} !== undefined`,()=>{n.assign(o,a),mE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,O._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,O._)`"" + ${o}`).elseIf((0,O._)`${o} === null`).assign(a,(0,O._)`""`);return;case"number":n.elseIf((0,O._)`${i} == "boolean" || ${o} === null - || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,O._)`+${o}`);return;case"integer":n.elseIf((0,O._)`${i} === "boolean" || ${o} === null - || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,O._)`+${o}`);return;case"boolean":n.elseIf((0,O._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,O._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,O._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,O._)`${i} === "string" || ${i} === "number" - || ${i} === "boolean" || ${o} === null`).assign(a,(0,O._)`[${o}]`)}}}function mE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,O._)`${e} !== undefined`,()=>t.assign((0,O._)`${e}[${r}]`,n))}function Ia(t,e,r,n=yr.Correct){let o=n===yr.Correct?O.operators.EQ:O.operators.NEQ,s;switch(t){case"null":return(0,O._)`${e} ${o} null`;case"array":s=(0,O._)`Array.isArray(${e})`;break;case"object":s=(0,O._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,O._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,O._)`typeof ${e} ${o} ${t}`}return n===yr.Correct?s:(0,O.not)(s);function i(a=O.nil){return(0,O.and)((0,O._)`typeof ${e} == "number"`,a,r?(0,O._)`isFinite(${e})`:O.nil)}}ve.checkDataType=Ia;function Oa(t,e,r,n){if(t.length===1)return Ia(t[0],e,r,n);let o,s=(0,mm.toHash)(t);if(s.array&&s.object){let i=(0,O._)`typeof ${e} != "object"`;o=s.null?i:(0,O._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=O.nil;s.number&&delete s.integer;for(let i in s)o=(0,O.and)(o,Ia(i,e,r,n));return o}ve.checkDataTypes=Oa;var hE={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,O._)`{type: ${t}}`:(0,O._)`{type: ${e}}`};function Aa(t){let e=gE(t);(0,uE.reportError)(e,hE)}ve.reportTypeError=Aa;function gE(t){let{gen:e,data:r,schema:n}=t,o=(0,mm.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ym=E(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.assignDefaults=void 0;var Sr=A(),_E=Z();function yE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)_m(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>_m(t,s,o.default))}Zo.assignDefaults=yE;function _m(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Sr._)`${s}${(0,Sr.getProperty)(e)}`;if(o){(0,_E.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Sr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Sr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Sr._)`${a} = ${(0,Sr.stringify)(r)}`)}});var Le=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.validateUnion=W.validateArray=W.usePattern=W.callValidateCode=W.schemaProperties=W.allSchemaProperties=W.noPropertyInData=W.propertyInData=W.isOwnProperty=W.hasPropFunc=W.reportMissingProp=W.checkMissingProp=W.checkReportMissingProp=void 0;var Q=A(),Ma=Z(),Ct=vt(),SE=Z();function vE(t,e){let{gen:r,data:n,it:o}=t;r.if(Na(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Q._)`${e}`},!0),t.error()})}W.checkReportMissingProp=vE;function bE({gen:t,data:e,it:{opts:r}},n,o){return(0,Q.or)(...n.map(s=>(0,Q.and)(Na(t,e,s,r.ownProperties),(0,Q._)`${o} = ${s}`)))}W.checkMissingProp=bE;function EE(t,e){t.setParams({missingProperty:e},!0),t.error()}W.reportMissingProp=EE;function Sm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Q._)`Object.prototype.hasOwnProperty`})}W.hasPropFunc=Sm;function Ca(t,e,r){return(0,Q._)`${Sm(t)}.call(${e}, ${r})`}W.isOwnProperty=Ca;function wE(t,e,r,n){let o=(0,Q._)`${e}${(0,Q.getProperty)(r)} !== undefined`;return n?(0,Q._)`${o} && ${Ca(t,e,r)}`:o}W.propertyInData=wE;function Na(t,e,r,n){let o=(0,Q._)`${e}${(0,Q.getProperty)(r)} === undefined`;return n?(0,Q.or)(o,(0,Q.not)(Ca(t,e,r))):o}W.noPropertyInData=Na;function vm(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}W.allSchemaProperties=vm;function kE(t,e){return vm(e).filter(r=>!(0,Ma.alwaysValidSchema)(t,e[r]))}W.schemaProperties=kE;function $E({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Q._)`${t}, ${e}, ${n}${o}`:e,d=[[Ct.default.instancePath,(0,Q.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let p=(0,Q._)`${l}, ${r.object(...d)}`;return c!==Q.nil?(0,Q._)`${a}.call(${c}, ${p})`:(0,Q._)`${a}(${p})`}W.callValidateCode=$E;var xE=(0,Q._)`new RegExp`;function PE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Q._)`${o.code==="new RegExp"?xE:(0,SE.useFunc)(t,o)}(${r}, ${n})`})}W.usePattern=PE;function TE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Q._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ma.Type.Num},s),e.if((0,Q.not)(s),a)})}}W.validateArray=TE;function zE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ma.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Q._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Q.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}W.validateUnion=zE});var wm=E(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.validateKeywordUsage=nt.validSchemaType=nt.funcKeywordCode=nt.macroKeywordCode=void 0;var ke=A(),Yt=vt(),RE=Le(),IE=yn();function OE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Em(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ke.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}nt.macroKeywordCode=OE;function AE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;CE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Em(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&bm(t),S(()=>t.error());else{let v=e.async?f():m();e.modifying&&bm(t),S(()=>ME(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,ke._)`await `),$=>n.assign(d,!1).if((0,ke._)`${$} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,ke._)`${$}.errors`),()=>n.throw($))),v}function m(){let v=(0,ke._)`${l}.errors`;return n.assign(v,null),g(ke.nil),v}function g(v=e.async?(0,ke._)`await `:ke.nil){let $=c.opts.passContext?Yt.default.this:Yt.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ke._)`${v}${(0,RE.callValidateCode)(t,l,$,b)}`,e.modifying)}function S(v){var $;n.if((0,ke.not)(($=e.valid)!==null&&$!==void 0?$:d),v)}}nt.funcKeywordCode=AE;function bm(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ke._)`${n.parentData}[${n.parentDataProperty}]`))}function ME(t,e){let{gen:r}=t;r.if((0,ke._)`Array.isArray(${e})`,()=>{r.assign(Yt.default.vErrors,(0,ke._)`${Yt.default.vErrors} === null ? ${e} : ${Yt.default.vErrors}.concat(${e})`).assign(Yt.default.errors,(0,ke._)`${Yt.default.vErrors}.length`),(0,IE.extendErrors)(t)},()=>t.error())}function CE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Em(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ke.stringify)(r)})}function NE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}nt.validSchemaType=NE;function DE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}nt.validateKeywordUsage=DE});var $m=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var ot=A(),km=Z();function jE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}${(0,ot.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,km.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Nt.getSubschema=jE;function LE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,ot._)`${e.data}${(0,ot.getProperty)(r)}`,!0);c(p),t.errorPath=(0,ot.str)`${u}${(0,km.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,ot._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof ot.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Nt.extendSubschemaData=LE;function UE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Nt.extendSubschemaMode=UE});var Da=E((oM,xm)=>{"use strict";xm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Tm=E((sM,Pm)=>{"use strict";var Dt=Pm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Fo(e,n,o,t,"",t)};Dt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Dt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Dt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Dt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Fo(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Dt.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var ZE=Z(),FE=Da(),HE=Tm(),WE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function VE(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ja(t):e?zm(t)<=e:!1}Te.inlineRef=VE;var KE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ja(t){for(let e in t){if(KE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ja)||typeof r=="object"&&ja(r))return!0}return!1}function zm(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!WE.has(r)&&(typeof t[r]=="object"&&(0,ZE.eachItem)(t[r],n=>e+=zm(n)),e===1/0))return 1/0}return e}function Rm(t,e="",r){r!==!1&&(e=vr(e));let n=t.parse(e);return Im(t,n)}Te.getFullPath=Rm;function Im(t,e){return t.serialize(e).split("#")[0]+"#"}Te._getFullPath=Im;var JE=/#\/?$/;function vr(t){return t?t.replace(JE,""):""}Te.normalizeId=vr;function GE(t,e,r){return r=vr(r),t.resolve(e,r)}Te.resolveUrl=GE;var YE=/^[a-z_][-a-z0-9._]*$/i;function BE(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=vr(t[r]||e),s={"":o},i=Rm(n,o,!1),a={},c=new Set;return HE(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,S=s[m];typeof d[r]=="string"&&(S=v.call(this,d[r])),$.call(this,d.$anchor),$.call(this,d.$dynamicAnchor),s[p]=S;function v(b){let x=this.opts.uriResolver.resolve;if(b=vr(S?x(S,b):b),c.has(b))throw l(b);c.add(b);let k=this.refs[b];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(d,k.schema,b):b!==vr(g)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=g),b}function $(b){if(typeof b=="string"){if(!YE.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!FE(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=BE});var wn=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.getData=jt.KeywordCxt=jt.validateFunctionCode=void 0;var Nm=dm(),Om=Sn(),Ua=Ra(),Ho=Sn(),XE=ym(),En=wm(),La=$m(),T=A(),R=vt(),QE=vn(),bt=Z(),bn=yn();function ew(t){if(Lm(t)&&(Um(t),jm(t))){nw(t);return}Dm(t,()=>(0,Nm.topBoolOrEmptySchema)(t))}jt.validateFunctionCode=ew;function Dm({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${R.default.data}, ${R.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Am(r,o)}`),rw(t,o),t.code(s)}):t.func(e,(0,T._)`${R.default.data}, ${tw(o)}`,n.$async,()=>t.code(Am(r,o)).code(s))}function tw(t){return(0,T._)`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${t.dynamicRef?(0,T._)`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function rw(t,e){t.if(R.default.valCxt,()=>{t.var(R.default.instancePath,(0,T._)`${R.default.valCxt}.${R.default.instancePath}`),t.var(R.default.parentData,(0,T._)`${R.default.valCxt}.${R.default.parentData}`),t.var(R.default.parentDataProperty,(0,T._)`${R.default.valCxt}.${R.default.parentDataProperty}`),t.var(R.default.rootData,(0,T._)`${R.default.valCxt}.${R.default.rootData}`),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{t.var(R.default.instancePath,(0,T._)`""`),t.var(R.default.parentData,(0,T._)`undefined`),t.var(R.default.parentDataProperty,(0,T._)`undefined`),t.var(R.default.rootData,R.default.data),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`{}`)})}function nw(t){let{schema:e,opts:r,gen:n}=t;Dm(t,()=>{r.$comment&&e.$comment&&Zm(t),cw(t),n.let(R.default.vErrors,null),n.let(R.default.errors,0),r.unevaluated&&ow(t),qm(t),dw(t)})}function ow(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function Am(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function sw(t,e){if(Lm(t)&&(Um(t),jm(t))){iw(t,e);return}(0,Nm.boolOrEmptySchema)(t,e)}function jm({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Lm(t){return typeof t.schema!="boolean"}function iw(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Zm(t),uw(t),lw(t);let s=n.const("_errs",R.default.errors);qm(t,s),n.var(e,(0,T._)`${s} === ${R.default.errors}`)}function Um(t){(0,bt.checkUnknownRules)(t),aw(t)}function qm(t,e){if(t.opts.jtd)return Mm(t,[],!1,e);let r=(0,Om.getSchemaTypes)(t.schema),n=(0,Om.coerceAndCheckDataType)(t,r);Mm(t,r,!n,e)}function aw(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function cw(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(t,"default is ignored in the schema root")}function uw(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,QE.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lw(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Zm({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${R.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${R.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function dw(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${R.default.errors} === 0`,()=>e.return(R.default.data),()=>e.throw((0,T._)`new ${o}(${R.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,R.default.vErrors),s.unevaluated&&pw(t),e.return((0,T._)`${R.default.errors} === 0`))}function pw({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function Mm(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,bt.schemaHasRulesButRef)(s,l))){o.block(()=>Hm(t,"$ref",l.all.$ref.definition));return}c.jtd||fw(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Ua.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ho.checkDataType)(p.type,i,c.strictNumbers)),Cm(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ho.reportTypeError)(t)),o.endIf()):Cm(t,p),a||o.if((0,T._)`${R.default.errors} === ${n||0}`))}}function Cm(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,XE.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ua.shouldUseRule)(n,s)&&Hm(t,s.keyword,s.definition,e.type)})}function fw(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(mw(t,e),t.opts.allowUnionTypes||hw(t,e),gw(t,t.dataTypes))}function mw(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Fm(t.dataTypes,r)||qa(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),yw(t,e)}}function hw(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&qa(t,"use allowUnionTypes to allow union type keyword")}function gw(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ua.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>_w(e,i))&&qa(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function _w(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Fm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function yw(t,e){let r=[];for(let n of t.dataTypes)Fm(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function qa(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(t,e,t.opts.strictTypes)}var Wo=class{constructor(e,r,n){if((0,En.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Wm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,En.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",R.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?bn.reportExtraError:bn.reportError)(this,this.def.error,r)}$dataError(){(0,bn.reportError)(this,this.def.$dataError||bn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,bn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Ho.checkDataTypes)(c,r,s.opts.strictNumbers,Ho.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,La.getSubschema)(this.it,e);(0,La.extendSubschemaData)(n,this.it,e),(0,La.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return sw(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=bt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=bt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};jt.KeywordCxt=Wo;function Hm(t,e,r,n){let o=new Wo(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,En.funcKeywordCode)(o,r):"macro"in r?(0,En.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,En.funcKeywordCode)(o,r)}var Sw=/^\/(?:[^~]|~0|~1)*$/,vw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Wm(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return R.default.rootData;if(t[0]==="/"){if(!Sw.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=R.default.rootData}else{let u=vw.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,bt.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}jt.getData=Wm});var Vo=E(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Za=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Fa.default=Za});var kn=E(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var Ha=vn(),Wa=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ha.resolveUrl)(e,r,n),this.missingSchema=(0,Ha.normalizeId)((0,Ha.getFullPath)(e,this.missingRef))}};Va.default=Wa});var Jo=E(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.resolveSchema=Ue.getCompilingSchema=Ue.resolveRef=Ue.compileSchema=Ue.SchemaEnv=void 0;var Ge=A(),bw=Vo(),Bt=vt(),Ye=vn(),Vm=Z(),Ew=wn(),br=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Ye.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ue.SchemaEnv=br;function Ja(t){let e=Km.call(this,t);if(e)return e;let r=(0,Ye.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ge.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:bw.default,code:(0,Ge._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Bt.default.data,parentData:Bt.default.parentData,parentDataProperty:Bt.default.parentDataProperty,dataNames:[Bt.default.data],dataPathArr:[Ge.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ge.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ge.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ge._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Ew.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Bt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Bt.default.self}`,`${Bt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof Ge.Name?void 0:m,items:g instanceof Ge.Name?void 0:g,dynamicProps:m instanceof Ge.Name,dynamicItems:g instanceof Ge.Name},f.source&&(f.source.evaluated=(0,Ge.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Ue.compileSchema=Ja;function ww(t,e,r){var n;r=(0,Ye.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=xw.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new br({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=kw.call(this,s)}Ue.resolveRef=ww;function kw(t){return(0,Ye.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ja.call(this,t)}function Km(t){for(let e of this._compilations)if($w(e,t))return e}Ue.getCompilingSchema=Km;function $w(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function xw(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ko.call(this,t,e)}function Ko(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Ye._getFullPath)(this.opts.uriResolver,r),o=(0,Ye.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ka.call(this,r,t);let s=(0,Ye.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ko.call(this,t,i);return typeof a?.schema!="object"?void 0:Ka.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ja.call(this,i),s===(0,Ye.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Ye.resolveUrl)(this.opts.uriResolver,o,u)),new br({schema:a,schemaId:c,root:t,baseId:o})}return Ka.call(this,r,i)}}Ue.resolveSchema=Ko;var Pw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ka(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Vm.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Pw.has(a)&&u&&(e=(0,Ye.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Vm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ye.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ko.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new br({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Jm=E((dM,Tw)=>{Tw.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ya=E((pM,Xm)=>{"use strict";var zw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ym=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 Ga(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Rw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Gm(t){return t.length=0,!0}function Iw(t,e,r){if(t.length){let n=Ga(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Ow(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Iw;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Gm}else{o.push(u);continue}}return o.length&&(a===Gm?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ga(o))),r.address=n.join(""),r}function Bm(t){if(Aw(t,":")<2)return{host:t,isIPV6:!1};let e=Ow(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Aw(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:Dw}=Ya(),jw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Lw=["http","https","ws","wss","urn","urn:uuid"];function Uw(t){return Lw.indexOf(t)!==-1}function Ba(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Qm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function eh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function qw(t){return t.secure=Ba(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Zw(t){if((t.port===(Ba(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Fw(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jw);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Xa(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Hw(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Xa(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Ww(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Dw(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Vw(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var th={scheme:"http",domainHost:!0,parse:Qm,serialize:eh},Kw={scheme:"https",domainHost:th.domainHost,parse:Qm,serialize:eh},Go={scheme:"ws",domainHost:!0,parse:qw,serialize:Zw},Jw={scheme:"wss",domainHost:Go.domainHost,parse:Go.parse,serialize:Go.serialize},Gw={scheme:"urn",parse:Fw,serialize:Hw,skipNormalize:!0},Yw={scheme:"urn:uuid",parse:Ww,serialize:Vw,skipNormalize:!0},Yo={http:th,https:Kw,ws:Go,wss:Jw,urn:Gw,"urn:uuid":Yw};Object.setPrototypeOf(Yo,null);function Xa(t){return t&&(Yo[t]||Yo[t.toLowerCase()])||void 0}rh.exports={wsIsSecure:Ba,SCHEMES:Yo,isValidSchemeName:Uw,getSchemeHandler:Xa}});var ih=E((mM,Xo)=>{"use strict";var{normalizeIPv6:Bw,removeDotSegments:$n,recomposeAuthority:Xw,normalizeComponentEncoding:Bo,isIPv4:Qw,nonSimpleDomain:ek}=Ya(),{SCHEMES:tk,getSchemeHandler:oh}=nh();function rk(t,e){return typeof t=="string"?t=st(Et(t,e),e):typeof t=="object"&&(t=Et(st(t,e),e)),t}function nk(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=sh(Et(t,n),Et(e,n),n,!0);return n.skipEscape=!0,st(o,n)}function sh(t,e,r,n){let o={};return n||(t=Et(st(t,r),r),e=Et(st(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=$n(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=$n(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=$n(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=$n(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ok(t,e,r){return typeof t=="string"?(t=unescape(t),t=st(Bo(Et(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=st(Bo(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=st(Bo(Et(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=st(Bo(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function st(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=oh(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Xw(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=$n(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var sk=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Et(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(sk);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(Qw(n.host)===!1){let c=Bw(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=oh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&ek(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Qa={SCHEMES:tk,normalize:rk,resolve:nk,resolveComponent:sh,equal:ok,serialize:st,parse:Et};Xo.exports=Qa;Xo.exports.default=Qa;Xo.exports.fastUri=Qa});var ch=E(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var ah=ih();ah.code='require("ajv/dist/runtime/uri").default';ec.default=ah});var gh=E(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=void 0;var ik=wn();Object.defineProperty(he,"KeywordCxt",{enumerable:!0,get:function(){return ik.KeywordCxt}});var Er=A();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return Er.Name}});Object.defineProperty(he,"CodeGen",{enumerable:!0,get:function(){return Er.CodeGen}});var ak=Vo(),fh=kn(),ck=za(),xn=Jo(),uk=A(),Pn=vn(),Qo=Sn(),rc=Z(),uh=Jm(),lk=ch(),mh=(t,e)=>new RegExp(t,e);mh.code="new RegExp";var dk=["removeAdditional","useDefaults","coerceTypes"],pk=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),fk={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."},mk={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},lh=200;function hk(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,S,v,$,b,x,k,_e,V,tt,Ae;let kt=t.strict,Fs=(e=t.code)===null||e===void 0?void 0:e.optimize,Tu=Fs===!0||Fs===void 0?1:Fs||0,zu=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:mh,D_=(o=t.uriResolver)!==null&&o!==void 0?o:lk.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:kt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:kt)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:kt)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:kt)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:kt)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Tu,regExp:zu}:{optimize:Tu,regExp:zu},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:lh,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:lh,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:($=t.messages)!==null&&$!==void 0?$:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(_e=t.validateSchema)!==null&&_e!==void 0?_e:!0,validateFormats:(V=t.validateFormats)!==null&&V!==void 0?V:!0,unicodeRegExp:(tt=t.unicodeRegExp)!==null&&tt!==void 0?tt:!0,int32range:(Ae=t.int32range)!==null&&Ae!==void 0?Ae:!0,uriResolver:D_}}var Tn=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...hk(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new uk.ValueScope({scope:{},prefixes:pk,es5:r,lines:n}),this.logger=bk(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ck.getRules)(),dh.call(this,fk,e,"NOT SUPPORTED"),dh.call(this,mk,e,"DEPRECATED","warn"),this._metaOpts=Sk.call(this),e.formats&&_k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&yk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),gk.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=uh;n==="id"&&(o={...uh},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof fh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Pn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ph.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xn.SchemaEnv({schema:{},schemaId:n});if(r=xn.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ph.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Pn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(wk.call(this,n,r),!r)return(0,rc.eachItem)(n,s=>tc.call(this,s)),this;$k.call(this,r);let o={...r,type:(0,Qo.getJSONTypes)(r.type),schemaType:(0,Qo.getJSONTypes)(r.schemaType)};return(0,rc.eachItem)(n,o.type.length===0?s=>tc.call(this,s,o):s=>o.type.forEach(i=>tc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=hh(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Pn.normalizeId)(i||n);let u=Pn.getSchemaRefs.call(this,e,n);return c=new xn.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):xn.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{xn.compileSchema.call(this,e)}finally{this.opts=r}}};Tn.ValidationError=ak.default;Tn.MissingRefError=fh.default;he.default=Tn;function dh(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ph(t){return t=(0,Pn.normalizeId)(t),this.schemas[t]||this.refs[t]}function gk(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function _k(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function yk(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Sk(){let t={...this.opts};for(let e of dk)delete t[e];return t}var vk={log(){},warn(){},error(){}};function bk(t){if(t===!1)return vk;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Ek=/^[a-z_$][a-z0-9_$:-]*$/i;function wk(t,e){let{RULES:r}=this;if((0,rc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Ek.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function tc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Qo.getJSONTypes)(e.type),schemaType:(0,Qo.getJSONTypes)(e.schemaType)}};e.before?kk.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function kk(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function $k(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=hh(e)),t.validateSchema=this.compile(e,!0))}var xk={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function hh(t){return{anyOf:[t,xk]}}});var _h=E(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var Pk={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};nc.default=Pk});var bh=E(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var Tk=kn(),yh=Le(),ze=A(),wr=vt(),Sh=Jo(),es=Z(),zk={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Sh.resolveRef.call(c,u,o,r);if(l===void 0)throw new Tk.default(n.opts.uriResolver,o,r);if(l instanceof Sh.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return ts(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return ts(t,(0,ze._)`${m}.validate`,u,u.$async)}function p(m){let g=vh(t,m);ts(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ze.stringify)(m)}:{ref:m}),S=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:ze.nil,topSchemaRef:g,errSchemaPath:r},S);t.mergeEvaluated(v),t.ok(S)}}};function vh(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ze._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xt.getValidate=vh;function ts(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?wr.default.this:ze.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,ze._)`await ${(0,yh.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,ze._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,yh.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,ze._)`${m}.errors`;o.assign(wr.default.vErrors,(0,ze._)`${wr.default.vErrors} === null ? ${g} : ${wr.default.vErrors}.concat(${g})`),o.assign(wr.default.errors,(0,ze._)`${wr.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let S=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=es.mergeEvaluated.props(o,S.props,s.props));else{let v=o.var("props",(0,ze._)`${m}.evaluated.props`);s.props=es.mergeEvaluated.props(o,v,s.props,ze.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=es.mergeEvaluated.items(o,S.items,s.items));else{let v=o.var("items",(0,ze._)`${m}.evaluated.items`);s.items=es.mergeEvaluated.items(o,v,s.items,ze.Name)}}}Xt.callRef=ts;Xt.default=zk});var Eh=E(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Rk=_h(),Ik=bh(),Ok=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Rk.default,Ik.default];oc.default=Ok});var wh=E(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var rs=A(),Lt=rs.operators,ns={maximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},minimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},exclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},exclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},Ak={message:({keyword:t,schemaCode:e})=>(0,rs.str)`must be ${ns[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rs._)`{comparison: ${ns[t].okStr}, limit: ${e}}`},Mk={keyword:Object.keys(ns),type:"number",schemaType:"number",$data:!0,error:Ak,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,rs._)`${r} ${ns[e].fail} ${n} || isNaN(${r})`)}};sc.default=Mk});var kh=E(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var zn=A(),Ck={message:({schemaCode:t})=>(0,zn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,zn._)`{multipleOf: ${t}}`},Nk={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Ck,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,zn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,zn._)`${i} !== parseInt(${i})`;t.fail$data((0,zn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ic.default=Nk});var xh=E(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});function $h(t){let e=t.length,r=0,n=0,o;for(;n=55296&&o<=56319&&n{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var Qt=A(),Dk=Z(),jk=xh(),Lk={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},Uk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Lk,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,i=o.opts.unicode===!1?(0,Qt._)`${r}.length`:(0,Qt._)`${(0,Dk.useFunc)(t.gen,jk.default)}(${r})`;t.fail$data((0,Qt._)`${i} ${s} ${n}`)}};cc.default=Uk});var Th=E(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var qk=Le(),os=A(),Zk={message:({schemaCode:t})=>(0,os.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,os._)`{pattern: ${t}}`},Fk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Zk,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,os._)`(new RegExp(${o}, ${i}))`:(0,qk.usePattern)(t,n);t.fail$data((0,os._)`!${a}.test(${e})`)}};uc.default=Fk});var zh=E(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Rn=A(),Hk={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Rn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Rn._)`{limit: ${t}}`},Wk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Hk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Rn.operators.GT:Rn.operators.LT;t.fail$data((0,Rn._)`Object.keys(${r}).length ${o} ${n}`)}};lc.default=Wk});var Rh=E(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var In=Le(),On=A(),Vk=Z(),Kk={message:({params:{missingProperty:t}})=>(0,On.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,On._)`{missingProperty: ${t}}`},Jk={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Kk,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let S=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${g}" is not defined at "${S}" (strictRequired)`;(0,Vk.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(On.nil,d);else for(let f of r)(0,In.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,In.checkMissingProp)(t,r,f)),(0,In.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,In.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,In.propertyInData)(e,o,f,a.ownProperties)),e.if((0,On.not)(m),()=>{t.error(),e.break()})},On.nil)}}};dc.default=Jk});var Ih=E(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var An=A(),Gk={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,An.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,An._)`{limit: ${t}}`},Yk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Gk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?An.operators.GT:An.operators.LT;t.fail$data((0,An._)`${r}.length ${o} ${n}`)}};pc.default=Yk});var ss=E(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Oh=Da();Oh.code='require("ajv/dist/runtime/equal").default';fc.default=Oh});var Ah=E(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var mc=Sn(),ge=A(),Bk=Z(),Xk=ss(),Qk={message:({params:{i:t,j:e}})=>(0,ge.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ge._)`{i: ${t}, j: ${e}}`},e0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Qk,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,mc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ge._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,ge._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,ge._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let S=e.name("item"),v=(0,mc.checkDataTypes)(u,S,a.opts.strictNumbers,mc.DataType.Wrong),$=e.const("indices",(0,ge._)`{}`);e.for((0,ge._)`;${m}--;`,()=>{e.let(S,(0,ge._)`${r}[${m}]`),e.if(v,(0,ge._)`continue`),u.length>1&&e.if((0,ge._)`typeof ${S} == "string"`,(0,ge._)`${S} += "_"`),e.if((0,ge._)`typeof ${$}[${S}] == "number"`,()=>{e.assign(g,(0,ge._)`${$}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,ge._)`${$}[${S}] = ${m}`)})}function f(m,g){let S=(0,Bk.useFunc)(e,Xk.default),v=e.name("outer");e.label(v).for((0,ge._)`;${m}--;`,()=>e.for((0,ge._)`${g} = ${m}; ${g}--;`,()=>e.if((0,ge._)`${S}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};hc.default=e0});var Mh=E(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var gc=A(),t0=Z(),r0=ss(),n0={message:"must be equal to constant",params:({schemaCode:t})=>(0,gc._)`{allowedValue: ${t}}`},o0={keyword:"const",$data:!0,error:n0,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,gc._)`!${(0,t0.useFunc)(e,r0.default)}(${r}, ${o})`):t.fail((0,gc._)`${s} !== ${r}`)}};_c.default=o0});var Ch=E(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Mn=A(),s0=Z(),i0=ss(),a0={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Mn._)`{allowedValues: ${t}}`},c0={keyword:"enum",schemaType:"array",$data:!0,error:a0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,s0.useFunc)(e,i0.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Mn.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Mn._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Mn._)`${u()}(${r}, ${f}[${m}])`:(0,Mn._)`${r} === ${g}`}}};yc.default=c0});var Nh=E(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var u0=wh(),l0=kh(),d0=Ph(),p0=Th(),f0=zh(),m0=Rh(),h0=Ih(),g0=Ah(),_0=Mh(),y0=Ch(),S0=[u0.default,l0.default,d0.default,p0.default,f0.default,m0.default,h0.default,g0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_0.default,y0.default];Sc.default=S0});var bc=E(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.validateAdditionalItems=void 0;var er=A(),vc=Z(),v0={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},b0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:v0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,vc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Dh(t,n)}};function Dh(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,vc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,er._)`${a} <= ${e.length}`);r.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:vc.Type.Num},u),i.allErrors||r.if((0,er.not)(u),()=>r.break())})}}Cn.validateAdditionalItems=Dh;Cn.default=b0});var Ec=E(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.validateTuple=void 0;var jh=A(),is=Z(),E0=Le(),w0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Lh(t,"additionalItems",e);r.items=!0,!(0,is.alwaysValidSchema)(r,e)&&t.ok((0,E0.validateArray)(t))}};function Lh(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=is.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,jh._)`${s}.length`);r.forEach((d,p)=>{(0,is.alwaysValidSchema)(a,d)||(n.if((0,jh._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let S=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,is.checkStrictMode)(a,S,p.strictTuples)}}}Nn.validateTuple=Lh;Nn.default=w0});var Uh=E(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var k0=Ec(),$0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,k0.validateTuple)(t,"items")};wc.default=$0});var Zh=E(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var qh=A(),x0=Z(),P0=Le(),T0=bc(),z0={message:({params:{len:t}})=>(0,qh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,qh._)`{limit: ${t}}`},R0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:z0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,x0.alwaysValidSchema)(n,e)&&(o?(0,T0.validateAdditionalItems)(t,o):t.ok((0,P0.validateArray)(t)))}};kc.default=R0});var Fh=E($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var qe=A(),as=Z(),I0={message:({params:{min:t,max:e}})=>e===void 0?(0,qe.str)`must contain at least ${t} valid item(s)`:(0,qe.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,qe._)`{minContains: ${t}}`:(0,qe._)`{minContains: ${t}, maxContains: ${e}}`},O0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:I0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,qe._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,as.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,as.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,as.alwaysValidSchema)(s,r)){let g=(0,qe._)`${l} >= ${i}`;a!==void 0&&(g=(0,qe._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,qe._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),S=e.let("count",0);f(g,()=>e.if(g,()=>m(S)))}function f(g,S){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:as.Type.Num,compositeRule:!0},g),S()})}function m(g){e.code((0,qe._)`${g}++`),a===void 0?e.if((0,qe._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,qe._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,qe._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};$c.default=O0});var Vh=E(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var xc=A(),A0=Z(),Dn=Le();it.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,xc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,xc._)`{property: ${t}, +"use strict";var ey=Object.create;var Bs=Object.defineProperty;var ty=Object.getOwnPropertyDescriptor;var ry=Object.getOwnPropertyNames;var ny=Object.getPrototypeOf,oy=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Lu=(t,e)=>{for(var r in e)Bs(t,r,{get:e[r],enumerable:!0})},sy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ry(e))!oy.call(t,o)&&o!==r&&Bs(t,o,{get:()=>e[o],enumerable:!(n=ty(e,o))||n.enumerable});return t};var xt=(t,e,r)=>(r=t!=null?ey(ny(t)):{},sy(e||!t||!t.__esModule?Bs(r,"default",{value:t,enumerable:!0}):r,t));var _n=w(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.regexpCode=F.getEsmExportName=F.getProperty=F.safeStringify=F.stringify=F.strConcat=F.addCodeArg=F.str=F._=F.nil=F._Code=F.Name=F.IDENTIFIER=F._CodeOrName=void 0;var hn=class{};F._CodeOrName=hn;F.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wt=class extends hn{constructor(e){if(super(),!F.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};F.Name=Wt;var qe=class extends hn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Wt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};F._Code=qe;F.nil=new qe("");function im(t,...e){let r=[t[0]],n=0;for(;n{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.ValueScope=Re.ValueScopeName=Re.Scope=Re.varKinds=Re.UsedValueState=void 0;var ze=_n(),_a=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Fo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Fo||(Re.UsedValueState=Fo={}));Re.varKinds={const:new ze.Name("const"),let:new ze.Name("let"),var:new ze.Name("var")};var Ho=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ze.Name?e:this.name(e)}name(e){return new ze.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Re.Scope=Ho;var Wo=class extends ze.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ze._)`.${new ze.Name(r)}[${n}]`}};Re.ValueScopeName=Wo;var Hb=(0,ze._)`\n`,ya=class extends Ho{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Hb:ze.nil}}get(){return this._scope}name(e){return new Wo(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ze._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=ze.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Fo.Started);let l=r(u);if(l){let d=this.opts.es5?Re.varKinds.var:Re.varKinds.const;s=(0,ze._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,ze._)`${s}${l}${this.opts._n}`;else throw new _a(u);c.set(u,Fo.Completed)})}return s}};Re.ValueScope=ya});var O=w(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var j=_n(),Ye=Sa(),Ot=_n();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Jo=Sa();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return Jo.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return Jo.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return Jo.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return Jo.varKinds}});M.operators={GT:new j._Code(">"),GTE:new j._Code(">="),LT:new j._Code("<"),LTE:new j._Code("<="),EQ:new j._Code("==="),NEQ:new j._Code("!=="),NOT:new j._Code("!"),OR:new j._Code("||"),AND:new j._Code("&&"),ADD:new j._Code("+")};var gt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},va=class extends gt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ye.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=gr(this.rhs,e,r)),this}get names(){return this.rhs instanceof j._CodeOrName?this.rhs.names:{}}},Vo=class extends gt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof j.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=gr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof j.Name?{}:{...this.lhs.names};return Go(e,this.rhs)}},ba=class extends Vo{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ea=class extends gt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wa=class extends gt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ka=class extends gt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},xa=class extends gt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=gr(this.code,e,r),this}get names(){return this.code instanceof j._CodeOrName?this.code.names:{}}},yn=class extends gt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Wb(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Gt(e,r.names),{})}},_t=class extends yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$a=class extends yn{},hr=class extends _t{};hr.kind="else";var Vt=class t extends _t{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new hr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(cm(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=gr(this.condition,e,r),this}get names(){let e=super.names;return Go(e,this.condition),this.else&&Gt(e,this.else.names),e}};Vt.kind="if";var Kt=class extends _t{};Kt.kind="for";var Pa=class extends Kt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=gr(this.iteration,e,r),this}get names(){return Gt(super.names,this.iteration.names)}},Ta=class extends Kt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ye.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Go(super.names,this.from);return Go(e,this.to)}},Ko=class extends Kt{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=gr(this.iterable,e,r),this}get names(){return Gt(super.names,this.iterable.names)}},Sn=class extends _t{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Sn.kind="func";var vn=class extends yn{render(e){return"return "+super.render(e)}};vn.kind="return";var za=class extends _t{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Gt(e,this.catch.names),this.finally&&Gt(e,this.finally.names),e}},bn=class extends _t{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};bn.kind="catch";var En=class extends _t{render(e){return"finally"+super.render(e)}};En.kind="finally";var Ra=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` +`:""},this._extScope=e,this._scope=new Ye.Scope({parent:e}),this._nodes=[new $a]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new va(e,s,n)),s}const(e,r,n){return this._def(Ye.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ye.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ye.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Vo(e,r,n))}add(e,r){return this._leafNode(new ba(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==j.nil&&this._leafNode(new xa(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,j.addCodeArg)(r,o));return r.push("}"),new j._Code(r)}if(e,r,n){if(this._blockNode(new Vt(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vt(e))}else(){return this._elseNode(new hr)}endIf(){return this._endBlockNode(Vt,hr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Pa(e),r)}forRange(e,r,n,o,s=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let i=this._scope.toName(e);return this._for(new Ta(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Ye.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof j.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,j._)`${i}.length`,a=>{this.var(s,(0,j._)`${i}[${a}]`),n(s)})}return this._for(new Ko("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,j._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ko("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kt)}label(e){return this._leafNode(new Ea(e))}break(e){return this._leafNode(new wa(e))}return(e){let r=new vn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(vn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new za;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new bn(s),r(s)}return n&&(this._currNode=o.finally=new En,this.code(n)),this._endBlockNode(bn,En)}throw(e){return this._leafNode(new ka(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=j.nil,n,o){return this._blockNode(new Sn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=Ra;function Gt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Go(t,e){return e instanceof j._CodeOrName?Gt(t,e.names):t}function gr(t,e,r){if(t instanceof j.Name)return n(t);if(!o(t))return t;return new j._Code(t._items.reduce((s,i)=>(i instanceof j.Name&&(i=n(i)),i instanceof j._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof j._Code&&s._items.some(i=>i instanceof j.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Wb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function cm(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,j._)`!${Ia(t)}`}M.not=cm;var Vb=um(M.operators.AND);function Kb(...t){return t.reduce(Vb)}M.and=Kb;var Gb=um(M.operators.OR);function Jb(...t){return t.reduce(Gb)}M.or=Jb;function um(t){return(e,r)=>e===j.nil?r:r===j.nil?e:(0,j._)`${Ia(e)} ${t} ${Ia(r)}`}function Ia(t){return t instanceof j.Name?t:(0,j._)`(${t})`}});var q=w(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var K=O(),Yb=_n();function Bb(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=Bb;function Xb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pm(t,e),!fm(e,t.self.RULES.all))}C.alwaysValidSchema=Xb;function pm(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||gm(t,`unknown keyword: "${s}"`)}C.checkUnknownRules=pm;function fm(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=fm;function Qb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Qb;function eE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${t}${e}${(0,K.getProperty)(n)}`}C.schemaRefOrVal=eE;function tE(t){return mm(decodeURIComponent(t))}C.unescapeFragment=tE;function rE(t){return encodeURIComponent(Oa(t))}C.escapeFragment=rE;function Oa(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Oa;function mm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=mm;function nE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=nE;function lm({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof K.Name?(s instanceof K.Name?t(o,s,i):e(o,s,i),i):s instanceof K.Name?(e(o,i,s),s):r(s,i);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}C.mergeEvaluated={props:lm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,K._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,K._)`${r} || {}`),Ma(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:hm}),items:lm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,K._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,K._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function hm(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,K._)`{}`);return e!==void 0&&Ma(t,r,e),r}C.evaluatedPropsToName=hm;function Ma(t,e,r){Object.keys(r).forEach(n=>t.assign((0,K._)`${e}${(0,K.getProperty)(n)}`,!0))}C.setEvaluated=Ma;var dm={};function oE(t,e){return t.scopeValue("func",{ref:e,code:dm[e.code]||(dm[e.code]=new Yb._Code(e.code))})}C.useFunc=oE;var Aa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Aa||(C.Type=Aa={}));function sE(t,e,r){if(t instanceof K.Name){let n=e===Aa.Num;return r?n?(0,K._)`"[" + ${t} + "]"`:(0,K._)`"['" + ${t} + "']"`:n?(0,K._)`"/" + ${t}`:(0,K._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(t).toString():"/"+Oa(t)}C.getErrorPath=sE;function gm(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=gm});var yt=w(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var ve=O(),iE={data:new ve.Name("data"),valCxt:new ve.Name("valCxt"),instancePath:new ve.Name("instancePath"),parentData:new ve.Name("parentData"),parentDataProperty:new ve.Name("parentDataProperty"),rootData:new ve.Name("rootData"),dynamicAnchors:new ve.Name("dynamicAnchors"),vErrors:new ve.Name("vErrors"),errors:new ve.Name("errors"),this:new ve.Name("this"),self:new ve.Name("self"),scope:new ve.Name("scope"),json:new ve.Name("json"),jsonPos:new ve.Name("jsonPos"),jsonLen:new ve.Name("jsonLen"),jsonPart:new ve.Name("jsonPart")};Ca.default=iE});var wn=w(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.extendErrors=be.resetErrorsCount=be.reportExtraError=be.reportError=be.keyword$DataError=be.keywordError=void 0;var Z=O(),Yo=q(),$e=yt();be.keywordError={message:({keyword:t})=>(0,Z.str)`must pass "${t}" keyword validation`};be.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Z.str)`"${t}" keyword must be ${e} ($data)`:(0,Z.str)`"${t}" keyword is invalid ($data)`};function aE(t,e=be.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Sm(t,e,r);n??(i||a)?_m(s,c):ym(o,(0,Z._)`[${c}]`)}be.reportError=aE;function cE(t,e=be.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Sm(t,e,r);_m(o,a),s||i||ym(n,$e.default.vErrors)}be.reportExtraError=cE;function uE(t,e){t.assign($e.default.errors,e),t.if((0,Z._)`${$e.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Z._)`${$e.default.vErrors}.length`,e),()=>t.assign($e.default.vErrors,null)))}be.resetErrorsCount=uE;function lE({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,$e.default.errors,a=>{t.const(i,(0,Z._)`${$e.default.vErrors}[${a}]`),t.if((0,Z._)`${i}.instancePath === undefined`,()=>t.assign((0,Z._)`${i}.instancePath`,(0,Z.strConcat)($e.default.instancePath,s.errorPath))),t.assign((0,Z._)`${i}.schemaPath`,(0,Z.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Z._)`${i}.schema`,r),t.assign((0,Z._)`${i}.data`,n))})}be.extendErrors=lE;function _m(t,e){let r=t.const("err",e);t.if((0,Z._)`${$e.default.vErrors} === null`,()=>t.assign($e.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${$e.default.vErrors}.push(${r})`),t.code((0,Z._)`${$e.default.errors}++`)}function ym(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Z._)`new ${t.ValidationError}(${e})`):(r.assign((0,Z._)`${n}.errors`,e),r.return(!1))}var Jt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Sm(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Z._)`{}`:dE(t,e,r)}function dE(t,e,r={}){let{gen:n,it:o}=t,s=[pE(o,r),fE(t,r)];return mE(t,e,s),n.object(...s)}function pE({errorPath:t},{instancePath:e}){let r=e?(0,Z.str)`${t}${(0,Yo.getErrorPath)(e,Yo.Type.Str)}`:t;return[$e.default.instancePath,(0,Z.strConcat)($e.default.instancePath,r)]}function fE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Z.str)`${e}/${t}`;return r&&(o=(0,Z.str)`${o}${(0,Yo.getErrorPath)(r,Yo.Type.Str)}`),[Jt.schemaPath,o]}function mE(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Jt.keyword,o],[Jt.params,typeof e=="function"?e(t):e||(0,Z._)`{}`]),c.messages&&n.push([Jt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Jt.schema,i],[Jt.parentSchema,(0,Z._)`${l}${d}`],[$e.default.data,s]),u&&n.push([Jt.propertyName,u])}});var bm=w(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.boolOrEmptySchema=_r.topBoolOrEmptySchema=void 0;var hE=wn(),gE=O(),_E=yt(),yE={message:"boolean schema is false"};function SE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?vm(t,!1):typeof r=="object"&&r.$async===!0?e.return(_E.default.data):(e.assign((0,gE._)`${n}.errors`,null),e.return(!0))}_r.topBoolOrEmptySchema=SE;function vE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),vm(t)):r.var(e,!0)}_r.boolOrEmptySchema=vE;function vm(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,hE.reportError)(o,yE,void 0,e)}});var Na=w(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.getRules=yr.isJSONType=void 0;var bE=["string","number","integer","boolean","null","object","array"],EE=new Set(bE);function wE(t){return typeof t=="string"&&EE.has(t)}yr.isJSONType=wE;function kE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}yr.getRules=kE});var Da=w(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.shouldUseRule=Mt.shouldUseGroup=Mt.schemaHasRulesForType=void 0;function xE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Em(t,n)}Mt.schemaHasRulesForType=xE;function Em(t,e){return e.rules.some(r=>wm(t,r))}Mt.shouldUseGroup=Em;function wm(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mt.shouldUseRule=wm});var kn=w(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.reportTypeError=Ee.checkDataTypes=Ee.checkDataType=Ee.coerceAndCheckDataType=Ee.getJSONTypes=Ee.getSchemaTypes=Ee.DataType=void 0;var $E=Na(),PE=Da(),TE=wn(),A=O(),km=q(),Sr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Sr||(Ee.DataType=Sr={}));function zE(t){let e=xm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ee.getSchemaTypes=zE;function xm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($E.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ee.getJSONTypes=xm;function RE(t,e){let{gen:r,data:n,opts:o}=t,s=IE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,PE.schemaHasRulesForType)(t,e[0]));if(i){let a=La(e,n,o.strictNumbers,Sr.Wrong);r.if(a,()=>{s.length?AE(t,e,s):Ua(t)})}return i}Ee.coerceAndCheckDataType=RE;var $m=new Set(["string","number","integer","boolean","null"]);function IE(t,e){return e?t.filter(r=>$m.has(r)||e==="array"&&r==="array"):[]}function AE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,A._)`typeof ${o}`),a=n.let("coerced",(0,A._)`undefined`);s.coerceTypes==="array"&&n.if((0,A._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,A._)`${o}[0]`).assign(i,(0,A._)`typeof ${o}`).if(La(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,A._)`${a} !== undefined`);for(let u of r)($m.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ua(t),n.endIf(),n.if((0,A._)`${a} !== undefined`,()=>{n.assign(o,a),OE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,A._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":n.elseIf((0,A._)`${i} == "boolean" || ${o} === null + || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":n.elseIf((0,A._)`${i} === "boolean" || ${o} === null + || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":n.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,A._)`${i} === "string" || ${i} === "number" + || ${i} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function OE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,A._)`${e} !== undefined`,()=>t.assign((0,A._)`${e}[${r}]`,n))}function ja(t,e,r,n=Sr.Correct){let o=n===Sr.Correct?A.operators.EQ:A.operators.NEQ,s;switch(t){case"null":return(0,A._)`${e} ${o} null`;case"array":s=(0,A._)`Array.isArray(${e})`;break;case"object":s=(0,A._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,A._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,A._)`typeof ${e} ${o} ${t}`}return n===Sr.Correct?s:(0,A.not)(s);function i(a=A.nil){return(0,A.and)((0,A._)`typeof ${e} == "number"`,a,r?(0,A._)`isFinite(${e})`:A.nil)}}Ee.checkDataType=ja;function La(t,e,r,n){if(t.length===1)return ja(t[0],e,r,n);let o,s=(0,km.toHash)(t);if(s.array&&s.object){let i=(0,A._)`typeof ${e} != "object"`;o=s.null?i:(0,A._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=A.nil;s.number&&delete s.integer;for(let i in s)o=(0,A.and)(o,ja(i,e,r,n));return o}Ee.checkDataTypes=La;var ME={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,A._)`{type: ${t}}`:(0,A._)`{type: ${e}}`};function Ua(t){let e=CE(t);(0,TE.reportError)(e,ME)}Ee.reportTypeError=Ua;function CE(t){let{gen:e,data:r,schema:n}=t,o=(0,km.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Tm=w(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.assignDefaults=void 0;var vr=O(),NE=q();function DE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Pm(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Pm(t,s,o.default))}Bo.assignDefaults=DE;function Pm(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vr._)`${s}${(0,vr.getProperty)(e)}`;if(o){(0,NE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vr._)`${a} = ${(0,vr.stringify)(r)}`)}});var Ze=w(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.validateUnion=V.validateArray=V.usePattern=V.callValidateCode=V.schemaProperties=V.allSchemaProperties=V.noPropertyInData=V.propertyInData=V.isOwnProperty=V.hasPropFunc=V.reportMissingProp=V.checkMissingProp=V.checkReportMissingProp=void 0;var X=O(),qa=q(),Ct=yt(),jE=q();function LE(t,e){let{gen:r,data:n,it:o}=t;r.if(Fa(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,X._)`${e}`},!0),t.error()})}V.checkReportMissingProp=LE;function UE({gen:t,data:e,it:{opts:r}},n,o){return(0,X.or)(...n.map(s=>(0,X.and)(Fa(t,e,s,r.ownProperties),(0,X._)`${o} = ${s}`)))}V.checkMissingProp=UE;function qE(t,e){t.setParams({missingProperty:e},!0),t.error()}V.reportMissingProp=qE;function zm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}V.hasPropFunc=zm;function Za(t,e,r){return(0,X._)`${zm(t)}.call(${e}, ${r})`}V.isOwnProperty=Za;function ZE(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Za(t,e,r)}`:o}V.propertyInData=ZE;function Fa(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Za(t,e,r))):o}V.noPropertyInData=Fa;function Rm(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}V.allSchemaProperties=Rm;function FE(t,e){return Rm(e).filter(r=>!(0,qa.alwaysValidSchema)(t,e[r]))}V.schemaProperties=FE;function HE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,X._)`${t}, ${e}, ${n}${o}`:e,d=[[Ct.default.instancePath,(0,X.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let p=(0,X._)`${l}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${p})`:(0,X._)`${a}(${p})`}V.callValidateCode=HE;var WE=(0,X._)`new RegExp`;function VE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,X._)`${o.code==="new RegExp"?WE:(0,jE.useFunc)(t,o)}(${r}, ${n})`})}V.usePattern=VE;function KE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,X._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:qa.Type.Num},s),e.if((0,X.not)(s),a)})}}V.validateArray=KE;function GE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,qa.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,X._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,X.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}V.validateUnion=GE});var Om=w(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.validateKeywordUsage=nt.validSchemaType=nt.funcKeywordCode=nt.macroKeywordCode=void 0;var Pe=O(),Yt=yt(),JE=Ze(),YE=wn();function BE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Am(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Pe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}nt.macroKeywordCode=BE;function XE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;ew(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Am(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)_(),e.modifying&&Im(t),S(()=>t.error());else{let b=e.async?f():m();e.modifying&&Im(t),S(()=>QE(t,b))}}function f(){let b=n.let("ruleErrs",null);return n.try(()=>_((0,Pe._)`await `),E=>n.assign(d,!1).if((0,Pe._)`${E} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Pe._)`${E}.errors`),()=>n.throw(E))),b}function m(){let b=(0,Pe._)`${l}.errors`;return n.assign(b,null),_(Pe.nil),b}function _(b=e.async?(0,Pe._)`await `:Pe.nil){let E=c.opts.passContext?Yt.default.this:Yt.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Pe._)`${b}${(0,JE.callValidateCode)(t,l,E,v)}`,e.modifying)}function S(b){var E;n.if((0,Pe.not)((E=e.valid)!==null&&E!==void 0?E:d),b)}}nt.funcKeywordCode=XE;function Im(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Pe._)`${n.parentData}[${n.parentDataProperty}]`))}function QE(t,e){let{gen:r}=t;r.if((0,Pe._)`Array.isArray(${e})`,()=>{r.assign(Yt.default.vErrors,(0,Pe._)`${Yt.default.vErrors} === null ? ${e} : ${Yt.default.vErrors}.concat(${e})`).assign(Yt.default.errors,(0,Pe._)`${Yt.default.vErrors}.length`),(0,YE.extendErrors)(t)},()=>t.error())}function ew({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Am(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Pe.stringify)(r)})}function tw(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}nt.validSchemaType=tw;function rw({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}nt.validateKeywordUsage=rw});var Cm=w(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var ot=O(),Mm=q();function nw(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}${(0,ot.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Mm.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Nt.getSubschema=nw;function ow(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,ot._)`${e.data}${(0,ot.getProperty)(r)}`,!0);c(p),t.errorPath=(0,ot.str)`${u}${(0,Mm.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,ot._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof ot.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Nt.extendSubschemaData=ow;function sw(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Nt.extendSubschemaMode=sw});var Ha=w((xM,Nm)=>{"use strict";Nm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var jm=w(($M,Dm)=>{"use strict";var Dt=Dm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Xo(e,n,o,t,"",t)};Dt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Dt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Dt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Dt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Xo(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Dt.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.getSchemaRefs=Ie.resolveUrl=Ie.normalizeId=Ie._getFullPath=Ie.getFullPath=Ie.inlineRef=void 0;var aw=q(),cw=Ha(),uw=jm(),lw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function dw(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wa(t):e?Lm(t)<=e:!1}Ie.inlineRef=dw;var pw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wa(t){for(let e in t){if(pw.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Wa)||typeof r=="object"&&Wa(r))return!0}return!1}function Lm(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!lw.has(r)&&(typeof t[r]=="object"&&(0,aw.eachItem)(t[r],n=>e+=Lm(n)),e===1/0))return 1/0}return e}function Um(t,e="",r){r!==!1&&(e=br(e));let n=t.parse(e);return qm(t,n)}Ie.getFullPath=Um;function qm(t,e){return t.serialize(e).split("#")[0]+"#"}Ie._getFullPath=qm;var fw=/#\/?$/;function br(t){return t?t.replace(fw,""):""}Ie.normalizeId=br;function mw(t,e,r){return r=br(r),t.resolve(e,r)}Ie.resolveUrl=mw;var hw=/^[a-z_][-a-z0-9._]*$/i;function gw(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=br(t[r]||e),s={"":o},i=Um(n,o,!1),a={},c=new Set;return uw(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let _=i+p,S=s[m];typeof d[r]=="string"&&(S=b.call(this,d[r])),E.call(this,d.$anchor),E.call(this,d.$dynamicAnchor),s[p]=S;function b(v){let $=this.opts.uriResolver.resolve;if(v=br(S?$(S,v):v),c.has(v))throw l(v);c.add(v);let x=this.refs[v];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,v):v!==br(_)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=_),v}function E(v){if(typeof v=="string"){if(!hw.test(v))throw new Error(`invalid anchor "${v}"`);b.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!cw(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ie.getSchemaRefs=gw});var Tn=w(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.getData=jt.KeywordCxt=jt.validateFunctionCode=void 0;var Vm=bm(),Zm=kn(),Ka=Da(),Qo=kn(),_w=Tm(),Pn=Om(),Va=Cm(),T=O(),R=yt(),yw=xn(),St=q(),$n=wn();function Sw(t){if(Jm(t)&&(Ym(t),Gm(t))){Ew(t);return}Km(t,()=>(0,Vm.topBoolOrEmptySchema)(t))}jt.validateFunctionCode=Sw;function Km({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${R.default.data}, ${R.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Fm(r,o)}`),bw(t,o),t.code(s)}):t.func(e,(0,T._)`${R.default.data}, ${vw(o)}`,n.$async,()=>t.code(Fm(r,o)).code(s))}function vw(t){return(0,T._)`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${t.dynamicRef?(0,T._)`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function bw(t,e){t.if(R.default.valCxt,()=>{t.var(R.default.instancePath,(0,T._)`${R.default.valCxt}.${R.default.instancePath}`),t.var(R.default.parentData,(0,T._)`${R.default.valCxt}.${R.default.parentData}`),t.var(R.default.parentDataProperty,(0,T._)`${R.default.valCxt}.${R.default.parentDataProperty}`),t.var(R.default.rootData,(0,T._)`${R.default.valCxt}.${R.default.rootData}`),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{t.var(R.default.instancePath,(0,T._)`""`),t.var(R.default.parentData,(0,T._)`undefined`),t.var(R.default.parentDataProperty,(0,T._)`undefined`),t.var(R.default.rootData,R.default.data),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`{}`)})}function Ew(t){let{schema:e,opts:r,gen:n}=t;Km(t,()=>{r.$comment&&e.$comment&&Xm(t),Pw(t),n.let(R.default.vErrors,null),n.let(R.default.errors,0),r.unevaluated&&ww(t),Bm(t),Rw(t)})}function ww(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function Fm(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function kw(t,e){if(Jm(t)&&(Ym(t),Gm(t))){xw(t,e);return}(0,Vm.boolOrEmptySchema)(t,e)}function Gm({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Jm(t){return typeof t.schema!="boolean"}function xw(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Xm(t),Tw(t),zw(t);let s=n.const("_errs",R.default.errors);Bm(t,s),n.var(e,(0,T._)`${s} === ${R.default.errors}`)}function Ym(t){(0,St.checkUnknownRules)(t),$w(t)}function Bm(t,e){if(t.opts.jtd)return Hm(t,[],!1,e);let r=(0,Zm.getSchemaTypes)(t.schema),n=(0,Zm.coerceAndCheckDataType)(t,r);Hm(t,r,!n,e)}function $w(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,St.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Pw(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,St.checkStrictMode)(t,"default is ignored in the schema root")}function Tw(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,yw.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zw(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Xm({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${R.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${R.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Rw(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${R.default.errors} === 0`,()=>e.return(R.default.data),()=>e.throw((0,T._)`new ${o}(${R.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,R.default.vErrors),s.unevaluated&&Iw(t),e.return((0,T._)`${R.default.errors} === 0`))}function Iw({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function Hm(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,St.schemaHasRulesButRef)(s,l))){o.block(()=>eh(t,"$ref",l.all.$ref.definition));return}c.jtd||Aw(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Ka.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Qo.checkDataType)(p.type,i,c.strictNumbers)),Wm(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Qo.reportTypeError)(t)),o.endIf()):Wm(t,p),a||o.if((0,T._)`${R.default.errors} === ${n||0}`))}}function Wm(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,_w.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ka.shouldUseRule)(n,s)&&eh(t,s.keyword,s.definition,e.type)})}function Aw(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ow(t,e),t.opts.allowUnionTypes||Mw(t,e),Cw(t,t.dataTypes))}function Ow(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Qm(t.dataTypes,r)||Ga(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dw(t,e)}}function Mw(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ga(t,"use allowUnionTypes to allow union type keyword")}function Cw(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ka.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Nw(e,i))&&Ga(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Nw(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Qm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dw(t,e){let r=[];for(let n of t.dataTypes)Qm(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ga(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,St.checkStrictMode)(t,e,t.opts.strictTypes)}var es=class{constructor(e,r,n){if((0,Pn.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,St.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",th(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Pn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",R.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?$n.reportExtraError:$n.reportError)(this,this.def.error,r)}$dataError(){(0,$n.reportError)(this,this.def.$dataError||$n.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$n.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Qo.checkDataTypes)(c,r,s.opts.strictNumbers,Qo.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,Va.getSubschema)(this.it,e);(0,Va.extendSubschemaData)(n,this.it,e),(0,Va.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return kw(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=St.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=St.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};jt.KeywordCxt=es;function eh(t,e,r,n){let o=new es(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Pn.funcKeywordCode)(o,r):"macro"in r?(0,Pn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Pn.funcKeywordCode)(o,r)}var jw=/^\/(?:[^~]|~0|~1)*$/,Lw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function th(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return R.default.rootData;if(t[0]==="/"){if(!jw.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=R.default.rootData}else{let u=Lw.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,St.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}jt.getData=th});var ts=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Ja=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ya.default=Ja});var zn=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Ba=xn(),Xa=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ba.resolveUrl)(e,r,n),this.missingSchema=(0,Ba.normalizeId)((0,Ba.getFullPath)(e,this.missingRef))}};Qa.default=Xa});var ns=w(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Be=O(),Uw=ts(),Bt=yt(),Xe=xn(),rh=q(),qw=Tn(),Er=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Xe.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Fe.SchemaEnv=Er;function tc(t){let e=nh.call(this,t);if(e)return e;let r=(0,Xe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Be.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Uw.default,code:(0,Be._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Bt.default.data,parentData:Bt.default.parentData,parentDataProperty:Bt.default.parentDataProperty,dataNames:[Bt.default.data],dataPathArr:[Be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Be.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Be._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,qw.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Bt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Bt.default.self}`,`${Bt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:_}=u;f.evaluated={props:m instanceof Be.Name?void 0:m,items:_ instanceof Be.Name?void 0:_,dynamicProps:m instanceof Be.Name,dynamicItems:_ instanceof Be.Name},f.source&&(f.source.evaluated=(0,Be.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Fe.compileSchema=tc;function Zw(t,e,r){var n;r=(0,Xe.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Ww.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Er({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Fw.call(this,s)}Fe.resolveRef=Zw;function Fw(t){return(0,Xe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:tc.call(this,t)}function nh(t){for(let e of this._compilations)if(Hw(e,t))return e}Fe.getCompilingSchema=nh;function Hw(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Ww(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||rs.call(this,t,e)}function rs(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Xe._getFullPath)(this.opts.uriResolver,r),o=(0,Xe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ec.call(this,r,t);let s=(0,Xe.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=rs.call(this,t,i);return typeof a?.schema!="object"?void 0:ec.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||tc.call(this,i),s===(0,Xe.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Xe.resolveUrl)(this.opts.uriResolver,o,u)),new Er({schema:a,schemaId:c,root:t,baseId:o})}return ec.call(this,r,i)}}Fe.resolveSchema=rs;var Vw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ec(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,rh.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Vw.has(a)&&u&&(e=(0,Xe.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,rh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Xe.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=rs.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Er({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var oh=w((AM,Kw)=>{Kw.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var nc=w((OM,ch)=>{"use strict";var Gw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ih=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 rc(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Jw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function sh(t){return t.length=0,!0}function Yw(t,e,r){if(t.length){let n=rc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Bw(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Yw;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=sh}else{o.push(u);continue}}return o.length&&(a===sh?r.zone=o.join(""):i?n.push(o.join("")):n.push(rc(o))),r.address=n.join(""),r}function ah(t){if(Xw(t,":")<2)return{host:t,isIPV6:!1};let e=Bw(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Xw(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:rk}=nc(),nk=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ok=["http","https","ws","wss","urn","urn:uuid"];function sk(t){return ok.indexOf(t)!==-1}function oc(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function uh(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function lh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ik(t){return t.secure=oc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ak(t){if((t.port===(oc(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function ck(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(nk);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=sc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uk(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=sc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function lk(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!rk(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function dk(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var dh={scheme:"http",domainHost:!0,parse:uh,serialize:lh},pk={scheme:"https",domainHost:dh.domainHost,parse:uh,serialize:lh},os={scheme:"ws",domainHost:!0,parse:ik,serialize:ak},fk={scheme:"wss",domainHost:os.domainHost,parse:os.parse,serialize:os.serialize},mk={scheme:"urn",parse:ck,serialize:uk,skipNormalize:!0},hk={scheme:"urn:uuid",parse:lk,serialize:dk,skipNormalize:!0},ss={http:dh,https:pk,ws:os,wss:fk,urn:mk,"urn:uuid":hk};Object.setPrototypeOf(ss,null);function sc(t){return t&&(ss[t]||ss[t.toLowerCase()])||void 0}ph.exports={wsIsSecure:oc,SCHEMES:ss,isValidSchemeName:sk,getSchemeHandler:sc}});var gh=w((CM,as)=>{"use strict";var{normalizeIPv6:gk,removeDotSegments:Rn,recomposeAuthority:_k,normalizeComponentEncoding:is,isIPv4:yk,nonSimpleDomain:Sk}=nc(),{SCHEMES:vk,getSchemeHandler:mh}=fh();function bk(t,e){return typeof t=="string"?t=st(vt(t,e),e):typeof t=="object"&&(t=vt(st(t,e),e)),t}function Ek(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=hh(vt(t,n),vt(e,n),n,!0);return n.skipEscape=!0,st(o,n)}function hh(t,e,r,n){let o={};return n||(t=vt(st(t,r),r),e=vt(st(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Rn(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Rn(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Rn(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Rn(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function wk(t,e,r){return typeof t=="string"?(t=unescape(t),t=st(is(vt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=st(is(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=st(is(vt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=st(is(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function st(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=mh(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=_k(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Rn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var kk=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function vt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(kk);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(yk(n.host)===!1){let c=gk(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=mh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&Sk(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var ic={SCHEMES:vk,normalize:bk,resolve:Ek,resolveComponent:hh,equal:wk,serialize:st,parse:vt};as.exports=ic;as.exports.default=ic;as.exports.fastUri=ic});var yh=w(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var _h=gh();_h.code='require("ajv/dist/runtime/uri").default';ac.default=_h});var $h=w(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=void 0;var xk=Tn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return xk.KeywordCxt}});var wr=O();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return wr._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return wr.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return wr.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return wr.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return wr.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return wr.CodeGen}});var $k=ts(),wh=zn(),Pk=Na(),In=ns(),Tk=O(),An=xn(),cs=kn(),uc=q(),Sh=oh(),zk=yh(),kh=(t,e)=>new RegExp(t,e);kh.code="new RegExp";var Rk=["removeAdditional","useDefaults","coerceTypes"],Ik=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Ak={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."},Ok={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},vh=200;function Mk(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,_,S,b,E,v,$,x,Se,we,Zt,nr;let ce=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,Ge=kt===!0||kt===void 0?1:kt||0,Lr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:kh,Q_=(o=t.uriResolver)!==null&&o!==void 0?o:zk.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ce)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ce)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ce)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:ce)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:ce)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Ge,regExp:Lr}:{optimize:Ge,regExp:Lr},loopRequired:(_=t.loopRequired)!==null&&_!==void 0?_:vh,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:vh,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(E=t.messages)!==null&&E!==void 0?E:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:($=t.schemaId)!==null&&$!==void 0?$:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(Se=t.validateSchema)!==null&&Se!==void 0?Se:!0,validateFormats:(we=t.validateFormats)!==null&&we!==void 0?we:!0,unicodeRegExp:(Zt=t.unicodeRegExp)!==null&&Zt!==void 0?Zt:!0,int32range:(nr=t.int32range)!==null&&nr!==void 0?nr:!0,uriResolver:Q_}}var On=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Mk(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Tk.ValueScope({scope:{},prefixes:Ik,es5:r,lines:n}),this.logger=Uk(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Pk.getRules)(),bh.call(this,Ak,e,"NOT SUPPORTED"),bh.call(this,Ok,e,"DEPRECATED","warn"),this._metaOpts=jk.call(this),e.formats&&Nk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Dk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ck.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Sh;n==="id"&&(o={...Sh},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof wh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,An.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Eh.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new In.SchemaEnv({schema:{},schemaId:n});if(r=In.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Eh.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,An.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Zk.call(this,n,r),!r)return(0,uc.eachItem)(n,s=>cc.call(this,s)),this;Hk.call(this,r);let o={...r,type:(0,cs.getJSONTypes)(r.type),schemaType:(0,cs.getJSONTypes)(r.schemaType)};return(0,uc.eachItem)(n,o.type.length===0?s=>cc.call(this,s,o):s=>o.type.forEach(i=>cc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=xh(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,An.normalizeId)(i||n);let u=An.getSchemaRefs.call(this,e,n);return c=new In.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):In.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{In.compileSchema.call(this,e)}finally{this.opts=r}}};On.ValidationError=$k.default;On.MissingRefError=wh.default;_e.default=On;function bh(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Eh(t){return t=(0,An.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ck(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Nk(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Dk(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function jk(){let t={...this.opts};for(let e of Rk)delete t[e];return t}var Lk={log(){},warn(){},error(){}};function Uk(t){if(t===!1)return Lk;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var qk=/^[a-z_$][a-z0-9_$:-]*$/i;function Zk(t,e){let{RULES:r}=this;if((0,uc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!qk.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function cc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,cs.getJSONTypes)(e.type),schemaType:(0,cs.getJSONTypes)(e.schemaType)}};e.before?Fk.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Fk(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Hk(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xh(e)),t.validateSchema=this.compile(e,!0))}var Wk={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xh(t){return{anyOf:[t,Wk]}}});var Ph=w(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Vk={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lc.default=Vk});var Ih=w(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var Kk=zn(),Th=Ze(),Ae=O(),kr=yt(),zh=ns(),us=q(),Gk={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=zh.resolveRef.call(c,u,o,r);if(l===void 0)throw new Kk.default(n.opts.uriResolver,o,r);if(l instanceof zh.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return ls(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return ls(t,(0,Ae._)`${m}.validate`,u,u.$async)}function p(m){let _=Rh(t,m);ls(t,_,m,m.$async)}function f(m){let _=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ae.stringify)(m)}:{ref:m}),S=e.name("valid"),b=t.subschema({schema:m,dataTypes:[],schemaPath:Ae.nil,topSchemaRef:_,errSchemaPath:r},S);t.mergeEvaluated(b),t.ok(S)}}};function Rh(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ae._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xt.getValidate=Rh;function ls(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?kr.default.this:Ae.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Ae._)`await ${(0,Th.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},_=>{o.if((0,Ae._)`!(${_} instanceof ${s.ValidationError})`,()=>o.throw(_)),p(_),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,Th.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let _=(0,Ae._)`${m}.errors`;o.assign(kr.default.vErrors,(0,Ae._)`${kr.default.vErrors} === null ? ${_} : ${kr.default.vErrors}.concat(${_})`),o.assign(kr.default.errors,(0,Ae._)`${kr.default.vErrors}.length`)}function f(m){var _;if(!s.opts.unevaluated)return;let S=(_=r?.validate)===null||_===void 0?void 0:_.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=us.mergeEvaluated.props(o,S.props,s.props));else{let b=o.var("props",(0,Ae._)`${m}.evaluated.props`);s.props=us.mergeEvaluated.props(o,b,s.props,Ae.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=us.mergeEvaluated.items(o,S.items,s.items));else{let b=o.var("items",(0,Ae._)`${m}.evaluated.items`);s.items=us.mergeEvaluated.items(o,b,s.items,Ae.Name)}}}Xt.callRef=ls;Xt.default=Gk});var Ah=w(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Jk=Ph(),Yk=Ih(),Bk=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Jk.default,Yk.default];dc.default=Bk});var Oh=w(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var ds=O(),Lt=ds.operators,ps={maximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},minimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},exclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},exclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},Xk={message:({keyword:t,schemaCode:e})=>(0,ds.str)`must be ${ps[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ds._)`{comparison: ${ps[t].okStr}, limit: ${e}}`},Qk={keyword:Object.keys(ps),type:"number",schemaType:"number",$data:!0,error:Xk,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ds._)`${r} ${ps[e].fail} ${n} || isNaN(${r})`)}};pc.default=Qk});var Mh=w(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Mn=O(),e0={message:({schemaCode:t})=>(0,Mn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Mn._)`{multipleOf: ${t}}`},t0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:e0,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Mn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Mn._)`${i} !== parseInt(${i})`;t.fail$data((0,Mn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};fc.default=t0});var Nh=w(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});function Ch(t){let e=t.length,r=0,n=0,o;for(;n=55296&&o<=56319&&n{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Qt=O(),r0=q(),n0=Nh(),o0={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},s0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:o0,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,i=o.opts.unicode===!1?(0,Qt._)`${r}.length`:(0,Qt._)`${(0,r0.useFunc)(t.gen,n0.default)}(${r})`;t.fail$data((0,Qt._)`${i} ${s} ${n}`)}};hc.default=s0});var jh=w(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var i0=Ze(),a0=q(),xr=O(),c0={message:({schemaCode:t})=>(0,xr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xr._)`{pattern: ${t}}`},u0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:c0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,xr._)`new RegExp`:(0,a0.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,xr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,xr._)`!${l}`)}else{let c=(0,i0.usePattern)(t,o);t.fail$data((0,xr._)`!${c}.test(${r})`)}}};gc.default=u0});var Lh=w(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Cn=O(),l0={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Cn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Cn._)`{limit: ${t}}`},d0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:l0,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Cn.operators.GT:Cn.operators.LT;t.fail$data((0,Cn._)`Object.keys(${r}).length ${o} ${n}`)}};_c.default=d0});var Uh=w(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Nn=Ze(),Dn=O(),p0=q(),f0={message:({params:{missingProperty:t}})=>(0,Dn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Dn._)`{missingProperty: ${t}}`},m0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:f0,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let _ of r)if(f?.[_]===void 0&&!m.has(_)){let S=i.schemaEnv.baseId+i.errSchemaPath,b=`required property "${_}" is not defined at "${S}" (strictRequired)`;(0,p0.checkStrictMode)(i,b,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Dn.nil,d);else for(let f of r)(0,Nn.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Nn.checkMissingProp)(t,r,f)),(0,Nn.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Nn.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Nn.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Dn.not)(m),()=>{t.error(),e.break()})},Dn.nil)}}};yc.default=m0});var qh=w(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var jn=O(),h0={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,jn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,jn._)`{limit: ${t}}`},g0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:h0,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?jn.operators.GT:jn.operators.LT;t.fail$data((0,jn._)`${r}.length ${o} ${n}`)}};Sc.default=g0});var fs=w(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Zh=Ha();Zh.code='require("ajv/dist/runtime/equal").default';vc.default=Zh});var Fh=w(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var bc=kn(),ye=O(),_0=q(),y0=fs(),S0={message:({params:{i:t,j:e}})=>(0,ye.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ye._)`{i: ${t}, j: ${e}}`},v0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:S0,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,bc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ye._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,ye._)`${r}.length`),_=e.let("j");t.setParams({i:m,j:_}),e.assign(c,!0),e.if((0,ye._)`${m} > 1`,()=>(d()?p:f)(m,_))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,_){let S=e.name("item"),b=(0,bc.checkDataTypes)(u,S,a.opts.strictNumbers,bc.DataType.Wrong),E=e.const("indices",(0,ye._)`{}`);e.for((0,ye._)`;${m}--;`,()=>{e.let(S,(0,ye._)`${r}[${m}]`),e.if(b,(0,ye._)`continue`),u.length>1&&e.if((0,ye._)`typeof ${S} == "string"`,(0,ye._)`${S} += "_"`),e.if((0,ye._)`typeof ${E}[${S}] == "number"`,()=>{e.assign(_,(0,ye._)`${E}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,ye._)`${E}[${S}] = ${m}`)})}function f(m,_){let S=(0,_0.useFunc)(e,y0.default),b=e.name("outer");e.label(b).for((0,ye._)`;${m}--;`,()=>e.for((0,ye._)`${_} = ${m}; ${_}--;`,()=>e.if((0,ye._)`${S}(${r}[${m}], ${r}[${_}])`,()=>{t.error(),e.assign(c,!1).break(b)})))}}};Ec.default=v0});var Hh=w(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var wc=O(),b0=q(),E0=fs(),w0={message:"must be equal to constant",params:({schemaCode:t})=>(0,wc._)`{allowedValue: ${t}}`},k0={keyword:"const",$data:!0,error:w0,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,wc._)`!${(0,b0.useFunc)(e,E0.default)}(${r}, ${o})`):t.fail((0,wc._)`${s} !== ${r}`)}};kc.default=k0});var Wh=w(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Ln=O(),x0=q(),$0=fs(),P0={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ln._)`{allowedValues: ${t}}`},T0={keyword:"enum",schemaType:"array",$data:!0,error:P0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,x0.useFunc)(e,$0.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Ln.or)(...o.map((m,_)=>p(f,_)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Ln._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let _=o[m];return typeof _=="object"&&_!==null?(0,Ln._)`${u()}(${r}, ${f}[${m}])`:(0,Ln._)`${r} === ${_}`}}};xc.default=T0});var Vh=w($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var z0=Oh(),R0=Mh(),I0=Dh(),A0=jh(),O0=Lh(),M0=Uh(),C0=qh(),N0=Fh(),D0=Hh(),j0=Wh(),L0=[z0.default,R0.default,I0.default,A0.default,O0.default,M0.default,C0.default,N0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},D0.default,j0.default];$c.default=L0});var Tc=w(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.validateAdditionalItems=void 0;var er=O(),Pc=q(),U0={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},q0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:U0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Pc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Kh(t,n)}};function Kh(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,er._)`${a} <= ${e.length}`);r.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Pc.Type.Num},u),i.allErrors||r.if((0,er.not)(u),()=>r.break())})}}Un.validateAdditionalItems=Kh;Un.default=q0});var zc=w(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.validateTuple=void 0;var Gh=O(),ms=q(),Z0=Ze(),F0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Jh(t,"additionalItems",e);r.items=!0,!(0,ms.alwaysValidSchema)(r,e)&&t.ok((0,Z0.validateArray)(t))}};function Jh(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ms.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Gh._)`${s}.length`);r.forEach((d,p)=>{(0,ms.alwaysValidSchema)(a,d)||(n.if((0,Gh._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,_=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!_){let S=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ms.checkStrictMode)(a,S,p.strictTuples)}}}qn.validateTuple=Jh;qn.default=F0});var Yh=w(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var H0=zc(),W0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,H0.validateTuple)(t,"items")};Rc.default=W0});var Xh=w(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Bh=O(),V0=q(),K0=Ze(),G0=Tc(),J0={message:({params:{len:t}})=>(0,Bh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Bh._)`{limit: ${t}}`},Y0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:J0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,V0.alwaysValidSchema)(n,e)&&(o?(0,G0.validateAdditionalItems)(t,o):t.ok((0,K0.validateArray)(t)))}};Ic.default=Y0});var Qh=w(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var He=O(),hs=q(),B0={message:({params:{min:t,max:e}})=>e===void 0?(0,He.str)`must contain at least ${t} valid item(s)`:(0,He.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,He._)`{minContains: ${t}}`:(0,He._)`{minContains: ${t}, maxContains: ${e}}`},X0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:B0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,He._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,hs.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,hs.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,hs.alwaysValidSchema)(s,r)){let _=(0,He._)`${l} >= ${i}`;a!==void 0&&(_=(0,He._)`${_} && ${l} <= ${a}`),t.pass(_);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,He._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let _=e.name("_valid"),S=e.let("count",0);f(_,()=>e.if(_,()=>m(S)))}function f(_,S){e.forRange("i",0,l,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:hs.Type.Num,compositeRule:!0},_),S()})}function m(_){e.code((0,He._)`${_}++`),a===void 0?e.if((0,He._)`${_} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,He._)`${_} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,He._)`${_} >= ${i}`,()=>e.assign(d,!0)))}}};Ac.default=X0});var rg=w(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var Oc=O(),Q0=q(),Zn=Ze();it.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Oc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Oc._)`{property: ${t}, missingProperty: ${n}, depsCount: ${e}, - deps: ${r}}`};var M0={keyword:"dependencies",type:"object",schemaType:"object",error:it.error,code(t){let[e,r]=C0(t);Hh(t,e),Wh(t,r)}};function C0({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Hh(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Dn.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Dn.checkReportMissingProp)(t,u)}):(r.if((0,xc._)`${c} && (${(0,Dn.checkMissingProp)(t,a,s)})`),(0,Dn.reportMissingProp)(t,s),r.else())}}it.validatePropertyDeps=Hh;function Wh(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,A0.alwaysValidSchema)(s,e[a])||(r.if((0,Dn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}it.validateSchemaDeps=Wh;it.default=M0});var Jh=E(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Kh=A(),N0=Z(),D0={message:"property name must be valid",params:({params:t})=>(0,Kh._)`{propertyName: ${t.propertyName}}`},j0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:D0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,N0.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Kh.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Pc.default=j0});var zc=E(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var cs=Le(),Be=A(),L0=vt(),us=Z(),U0={message:"must NOT have additional properties",params:({params:t})=>(0,Be._)`{additionalProperty: ${t.additionalProperty}}`},q0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:U0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,us.alwaysValidSchema)(i,r))return;let u=(0,cs.allSchemaProperties)(n.properties),l=(0,cs.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Be._)`${s} === ${L0.default.errors}`);function d(){e.forIn("key",o,S=>{!u.length&&!l.length?m(S):e.if(p(S),()=>m(S))})}function p(S){let v;if(u.length>8){let $=(0,us.schemaRefOrVal)(i,n.properties,"properties");v=(0,cs.isOwnProperty)(e,$,S)}else u.length?v=(0,Be.or)(...u.map($=>(0,Be._)`${S} === ${$}`)):v=Be.nil;return l.length&&(v=(0,Be.or)(v,...l.map($=>(0,Be._)`${(0,cs.usePattern)(t,$)}.test(${S})`))),(0,Be.not)(v)}function f(S){e.code((0,Be._)`delete ${o}[${S}]`)}function m(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,us.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(S,v,!1),e.if((0,Be.not)(v),()=>{t.reset(),f(S)})):(g(S,v),a||e.if((0,Be.not)(v),()=>e.break()))}}function g(S,v,$){let b={keyword:"additionalProperties",dataProp:S,dataPropType:us.Type.Str};$===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};Tc.default=q0});var Bh=E(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Z0=wn(),Gh=Le(),Rc=Z(),Yh=zc(),F0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Yh.default.code(new Z0.KeywordCxt(s,Yh.default,"additionalProperties"));let i=(0,Gh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Rc.mergeEvaluated.props(e,(0,Rc.toHash)(i),s.props));let a=i.filter(d=>!(0,Rc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Gh.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Ic.default=F0});var tg=E(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Xh=Le(),ls=A(),Qh=Z(),eg=Z(),H0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Xh.allSchemaProperties)(r),c=a.filter(g=>(0,Qh.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ls.Name)&&(s.props=(0,eg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let S in u)new RegExp(g).test(S)&&(0,Qh.checkStrictMode)(s,`property ${S} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,S=>{e.if((0,ls._)`${(0,Xh.usePattern)(t,g)}.test(${S})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:S,dataPropType:eg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ls._)`${d}[${S}]`,!0):!v&&!s.allErrors&&e.if((0,ls.not)(l),()=>e.break())})})}}};Oc.default=H0});var rg=E(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var W0=Z(),V0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,W0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ac.default=V0});var ng=E(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var K0=Le(),J0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:K0.validateUnion,error:{message:"must match a schema in anyOf"}};Mc.default=J0});var og=E(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var ds=A(),G0=Z(),Y0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ds._)`{passingSchemas: ${t.passing}}`},B0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Y0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,G0.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ds._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ds._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,ds.Name)})})}}};Cc.default=B0});var sg=E(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var X0=Z(),Q0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,X0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Nc.default=Q0});var cg=E(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ps=A(),ag=Z(),e$={message:({params:t})=>(0,ps.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ps._)`{failingKeyword: ${t.ifClause}}`},t$={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:e$,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ag.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ig(n,"then"),s=ig(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,ps.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,ps._)`${l}`):t.setParams({ifClause:l})}}}};function ig(t,e){let r=t.schema[e];return r!==void 0&&!(0,ag.alwaysValidSchema)(t,r)}Dc.default=t$});var ug=E(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var r$=Z(),n$={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,r$.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};jc.default=n$});var lg=E(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var o$=bc(),s$=Uh(),i$=Ec(),a$=Zh(),c$=Fh(),u$=Vh(),l$=Jh(),d$=zc(),p$=Bh(),f$=tg(),m$=rg(),h$=ng(),g$=og(),_$=sg(),y$=cg(),S$=ug();function v$(t=!1){let e=[m$.default,h$.default,g$.default,_$.default,y$.default,S$.default,l$.default,d$.default,u$.default,p$.default,f$.default];return t?e.push(s$.default,a$.default):e.push(o$.default,i$.default),e.push(c$.default),e}Lc.default=v$});var dg=E(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var ie=A(),b$={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},E$={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:b$,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ie._)`${m}[${i}]`),S=r.let("fType"),v=r.let("format");r.if((0,ie._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(S,(0,ie._)`${g}.type || "string"`).assign(v,(0,ie._)`${g}.validate`),()=>r.assign(S,(0,ie._)`"string"`).assign(v,g)),t.fail$data((0,ie.or)($(),b()));function $(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${v}`}function b(){let x=l.$async?(0,ie._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ie._)`${v}(${n})`,k=(0,ie._)`(typeof ${v} == "function" ? ${x} : ${v}.test(${n}))`;return(0,ie._)`${v} && ${v} !== true && ${S} === ${e} && !${k}`}}function f(){let m=d.formats[s];if(!m){$();return}if(m===!0)return;let[g,S,v]=b(m);g===e&&t.pass(x());function $(){if(c.strictSchema===!1){d.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(k){let _e=k instanceof RegExp?(0,ie.regexpCode)(k):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,V=r.scopeValue("formats",{key:s,ref:k,code:_e});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,ie._)`${V}.validate`]:["string",k,V]}function x(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${v}(${n})`}return typeof S=="function"?(0,ie._)`${v}(${n})`:(0,ie._)`${v}.test(${n})`}}}};Uc.default=E$});var pg=E(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var w$=dg(),k$=[w$.default];qc.default=k$});var fg=E(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.contentVocabulary=kr.metadataVocabulary=void 0;kr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var hg=E(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var $$=Eh(),x$=Nh(),P$=lg(),T$=pg(),mg=fg(),z$=[$$.default,x$.default,(0,P$.default)(),T$.default,mg.metadataVocabulary,mg.contentVocabulary];Zc.default=z$});var _g=E(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.DiscrError=void 0;var gg;(function(t){t.Tag="tag",t.Mapping="mapping"})(gg||(fs.DiscrError=gg={}))});var Sg=E(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var $r=A(),Fc=_g(),yg=Jo(),R$=kn(),I$=Z(),O$={message:({params:{discrError:t,tagName:e}})=>t===Fc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,$r._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},A$={keyword:"discriminator",type:"object",schemaType:"object",error:O$,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,$r._)`${r}${(0,$r.getProperty)(a)}`);e.if((0,$r._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Fc.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,$r._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Fc.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,$r.Name),m}function p(){var f;let m={},g=v(o),S=!0;for(let x=0;x{M$.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Vc=E((ee,Wc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var C$=gh(),N$=hg(),D$=Sg(),bg=vg(),j$=["/properties"],ms="http://json-schema.org/draft-07/schema",xr=class extends C$.default{_addVocabularies(){super._addVocabularies(),N$.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(D$.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(bg,j$):bg;this.addMetaSchema(e,ms,!1),this.refs["http://json-schema.org/schema"]=ms}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ms)?ms:void 0)}};ee.Ajv=xr;Wc.exports=ee=xr;Wc.exports.Ajv=xr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=xr;var L$=wn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return L$.KeywordCxt}});var Pr=A();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return Pr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return Pr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return Pr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return Pr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return Pr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return Pr.CodeGen}});var U$=Vo();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return U$.default}});var q$=kn();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return q$.default}})});var zg=E(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.formatNames=ct.fastFormats=ct.fullFormats=void 0;function at(t,e){return{validate:t,compare:e}}ct.fullFormats={date:at($g,Yc),time:at(Jc(!0),Bc),"date-time":at(Eg(!0),Pg),"iso-time":at(Jc(),xg),"iso-date-time":at(Eg(),Tg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:K$,"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:ex,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:J$,int32:{type:"number",validate:B$},int64:{type:"number",validate:X$},float:{type:"number",validate:kg},double:{type:"number",validate:kg},password:!0,binary:!0};ct.fastFormats={...ct.fullFormats,date:at(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Yc),time:at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bc),"date-time":at(/^\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,Pg),"iso-time":at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,xg),"iso-date-time":at(/^\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,Tg),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};ct.formatNames=Object.keys(ct.fullFormats);function Z$(t){return t%4===0&&(t%100!==0||t%400===0)}var F$=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,H$=[0,31,28,31,30,31,30,31,31,30,31,30,31];function $g(t){let e=F$.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Z$(r)?29:H$[n])}function Yc(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Bc(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function xg(t,e){if(!(t&&e))return;let r=Kc.exec(t),n=Kc.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=G$}function X$(t){return Number.isInteger(t)}function kg(){return!0}var Q$=/[^\\]\\Z/;function ex(t){if(Q$.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Rg=E(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.formatLimitDefinition=void 0;var tx=Vc(),Xe=A(),Ut=Xe.operators,hs={formatMaximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},formatMinimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},formatExclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},formatExclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},rx={message:({keyword:t,schemaCode:e})=>(0,Xe.str)`should be ${hs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Xe._)`{comparison: ${hs[t].okStr}, limit: ${e}}`};Tr.formatLimitDefinition={keyword:Object.keys(hs),type:"string",schemaType:"string",$data:!0,error:rx,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new tx.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Xe._)`${p}[${c.schemaCode}]`);t.fail$data((0,Xe.or)((0,Xe._)`typeof ${f} != "object"`,(0,Xe._)`${f} instanceof RegExp`,(0,Xe._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,Xe._)`${i.code.formats}${(0,Xe.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Xe._)`${p}.compare(${r}, ${n}) ${hs[o].fail} 0`}},dependencies:["format"]};var nx=t=>(t.addKeyword(Tr.formatLimitDefinition),t);Tr.default=nx});var Mg=E((jn,Ag)=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});var zr=zg(),ox=Rg(),Xc=A(),Ig=new Xc.Name("fullFormats"),sx=new Xc.Name("fastFormats"),Qc=(t,e={keywords:!0})=>{if(Array.isArray(e))return Og(t,e,zr.fullFormats,Ig),t;let[r,n]=e.mode==="fast"?[zr.fastFormats,sx]:[zr.fullFormats,Ig],o=e.formats||zr.formatNames;return Og(t,o,r,n),e.keywords&&(0,ox.default)(t),t};Qc.get=(t,e="full")=>{let n=(e==="fast"?zr.fastFormats:zr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Og(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Xc._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Ag.exports=jn=Qc;Object.defineProperty(jn,"__esModule",{value:!0});jn.default=Qc});var ft=require("fs"),Au=require("path");var J=require("path"),Ws=require("os"),Cr=require("fs"),Iu=require("url"),J_={};function H_(){return typeof __dirname<"u"?__dirname:(0,J.dirname)((0,Iu.fileURLToPath)(J_.url))}var zP=H_();function Yn(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,J.join)((0,Ws.homedir)(),".claude-mem"),e=(0,J.join)(t,"settings.json");try{if((0,Cr.existsSync)(e)){let r=JSON.parse((0,Cr.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return t}var ae=Yn(),W_=process.env.CLAUDE_CONFIG_DIR||(0,J.join)((0,Ws.homedir)(),".claude"),Vs=(0,J.join)(W_,"plugins","marketplaces","thedotmack"),V_=(0,J.join)(ae,"logs"),Ou=(0,J.join)(ae,"settings.json"),RP=(0,J.join)(ae,"claude-mem.db"),K_=(0,J.join)(ae,"observer-sessions"),IP=(0,J.basename)(K_);var Me={dataDir:()=>ae,workerPid:()=>(0,J.join)(ae,"worker.pid"),serverPid:()=>(0,J.join)(ae,".server-beta.pid"),serverPort:()=>(0,J.join)(ae,".server-beta.port"),serverRuntime:()=>(0,J.join)(ae,".server-beta.runtime.json"),settings:()=>(0,J.join)(ae,"settings.json"),database:()=>(0,J.join)(ae,"claude-mem.db"),chroma:()=>(0,J.join)(ae,"chroma"),combinedCerts:()=>(0,J.join)(ae,"combined_certs.pem"),transcriptsConfig:()=>(0,J.join)(ae,"transcript-watch.json"),transcriptsState:()=>(0,J.join)(ae,"transcript-watch-state.json"),corpora:()=>(0,J.join)(ae,"corpora"),supervisorRegistry:()=>(0,J.join)(ae,"supervisor.json"),envFile:()=>(0,J.join)(ae,".env"),logsDir:()=>V_};var G_=null;function Y_(t){return(G_??process.stderr.write.bind(process.stderr))(t)}function Ks(t){Y_(t)}var Gs=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Gs||{}),Js=null,Ys=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=Me.logsDir();(0,ft.existsSync)(e)||(0,ft.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Au.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=Me.settings();if((0,ft.existsSync)(e)){let r=(0,ft.readFileSync)(e,"utf-8"),o=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Gs[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} -${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${i}:${a}.${c}`}log(e,r,n,o,s){if(e{for(let u of a)(0,Zn.checkReportMissingProp)(t,u)}):(r.if((0,Oc._)`${c} && (${(0,Zn.checkMissingProp)(t,a,s)})`),(0,Zn.reportMissingProp)(t,s),r.else())}}it.validatePropertyDeps=eg;function tg(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Q0.alwaysValidSchema)(s,e[a])||(r.if((0,Zn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}it.validateSchemaDeps=tg;it.default=ex});var og=w(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var ng=O(),rx=q(),nx={message:"property name must be valid",params:({params:t})=>(0,ng._)`{propertyName: ${t.propertyName}}`},ox={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nx,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,rx.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,ng.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Mc.default=ox});var Nc=w(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var gs=Ze(),Qe=O(),sx=yt(),_s=q(),ix={message:"must NOT have additional properties",params:({params:t})=>(0,Qe._)`{additionalProperty: ${t.additionalProperty}}`},ax={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ix,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,_s.alwaysValidSchema)(i,r))return;let u=(0,gs.allSchemaProperties)(n.properties),l=(0,gs.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Qe._)`${s} === ${sx.default.errors}`);function d(){e.forIn("key",o,S=>{!u.length&&!l.length?m(S):e.if(p(S),()=>m(S))})}function p(S){let b;if(u.length>8){let E=(0,_s.schemaRefOrVal)(i,n.properties,"properties");b=(0,gs.isOwnProperty)(e,E,S)}else u.length?b=(0,Qe.or)(...u.map(E=>(0,Qe._)`${S} === ${E}`)):b=Qe.nil;return l.length&&(b=(0,Qe.or)(b,...l.map(E=>(0,Qe._)`${(0,gs.usePattern)(t,E)}.test(${S})`))),(0,Qe.not)(b)}function f(S){e.code((0,Qe._)`delete ${o}[${S}]`)}function m(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,_s.alwaysValidSchema)(i,r)){let b=e.name("valid");c.removeAdditional==="failing"?(_(S,b,!1),e.if((0,Qe.not)(b),()=>{t.reset(),f(S)})):(_(S,b),a||e.if((0,Qe.not)(b),()=>e.break()))}}function _(S,b,E){let v={keyword:"additionalProperties",dataProp:S,dataPropType:_s.Type.Str};E===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,b)}}};Cc.default=ax});var ag=w(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var cx=Tn(),sg=Ze(),Dc=q(),ig=Nc(),ux={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ig.default.code(new cx.KeywordCxt(s,ig.default,"additionalProperties"));let i=(0,sg.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Dc.mergeEvaluated.props(e,(0,Dc.toHash)(i),s.props));let a=i.filter(d=>!(0,Dc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,sg.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};jc.default=ux});var dg=w(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var cg=Ze(),ys=O(),ug=q(),lg=q(),lx={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,cg.allSchemaProperties)(r),c=a.filter(_=>(0,ug.alwaysValidSchema)(s,r[_]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ys.Name)&&(s.props=(0,lg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let _ of a)u&&f(_),s.allErrors?m(_):(e.var(l,!0),m(_),e.if(l))}function f(_){for(let S in u)new RegExp(_).test(S)&&(0,ug.checkStrictMode)(s,`property ${S} matches pattern ${_} (use allowMatchingProperties)`)}function m(_){e.forIn("key",n,S=>{e.if((0,ys._)`${(0,cg.usePattern)(t,_)}.test(${S})`,()=>{let b=c.includes(_);b||t.subschema({keyword:"patternProperties",schemaProp:_,dataProp:S,dataPropType:lg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ys._)`${d}[${S}]`,!0):!b&&!s.allErrors&&e.if((0,ys.not)(l),()=>e.break())})})}}};Lc.default=lx});var pg=w(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var dx=q(),px={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,dx.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Uc.default=px});var fg=w(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var fx=Ze(),mx={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fx.validateUnion,error:{message:"must match a schema in anyOf"}};qc.default=mx});var mg=w(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Ss=O(),hx=q(),gx={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ss._)`{passingSchemas: ${t.passing}}`},_x={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gx,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,hx.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ss._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ss._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ss.Name)})})}}};Zc.default=_x});var hg=w(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var yx=q(),Sx={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,yx.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Fc.default=Sx});var yg=w(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var vs=O(),_g=q(),vx={message:({params:t})=>(0,vs.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,vs._)`{failingKeyword: ${t.ifClause}}`},bx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_g.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=gg(n,"then"),s=gg(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,vs.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,vs._)`${l}`):t.setParams({ifClause:l})}}}};function gg(t,e){let r=t.schema[e];return r!==void 0&&!(0,_g.alwaysValidSchema)(t,r)}Hc.default=bx});var Sg=w(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Ex=q(),wx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Ex.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Wc.default=wx});var vg=w(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var kx=Tc(),xx=Yh(),$x=zc(),Px=Xh(),Tx=Qh(),zx=rg(),Rx=og(),Ix=Nc(),Ax=ag(),Ox=dg(),Mx=pg(),Cx=fg(),Nx=mg(),Dx=hg(),jx=yg(),Lx=Sg();function Ux(t=!1){let e=[Mx.default,Cx.default,Nx.default,Dx.default,jx.default,Lx.default,Rx.default,Ix.default,zx.default,Ax.default,Ox.default];return t?e.push(xx.default,Px.default):e.push(kx.default,$x.default),e.push(Tx.default),e}Vc.default=Ux});var bg=w(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var ie=O(),qx={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},Zx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qx,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),_=r.const("fDef",(0,ie._)`${m}[${i}]`),S=r.let("fType"),b=r.let("format");r.if((0,ie._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>r.assign(S,(0,ie._)`${_}.type || "string"`).assign(b,(0,ie._)`${_}.validate`),()=>r.assign(S,(0,ie._)`"string"`).assign(b,_)),t.fail$data((0,ie.or)(E(),v()));function E(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${b}`}function v(){let $=l.$async?(0,ie._)`(${_}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,ie._)`${b}(${n})`,x=(0,ie._)`(typeof ${b} == "function" ? ${$} : ${b}.test(${n}))`;return(0,ie._)`${b} && ${b} !== true && ${S} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){E();return}if(m===!0)return;let[_,S,b]=v(m);_===e&&t.pass($());function E(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(x){let Se=x instanceof RegExp?(0,ie.regexpCode)(x):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,we=r.scopeValue("formats",{key:s,ref:x,code:Se});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,ie._)`${we}.validate`]:["string",x,we]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${b}(${n})`}return typeof S=="function"?(0,ie._)`${b}(${n})`:(0,ie._)`${b}.test(${n})`}}}};Kc.default=Zx});var Eg=w(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Fx=bg(),Hx=[Fx.default];Gc.default=Hx});var wg=w($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xg=w(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Wx=Ah(),Vx=Vh(),Kx=vg(),Gx=Eg(),kg=wg(),Jx=[Wx.default,Vx.default,(0,Kx.default)(),Gx.default,kg.metadataVocabulary,kg.contentVocabulary];Jc.default=Jx});var Pg=w(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.DiscrError=void 0;var $g;(function(t){t.Tag="tag",t.Mapping="mapping"})($g||(bs.DiscrError=$g={}))});var zg=w(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Pr=O(),Yc=Pg(),Tg=ns(),Yx=zn(),Bx=q(),Xx={message:({params:{discrError:t,tagName:e}})=>t===Yc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Pr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Qx={keyword:"discriminator",type:"object",schemaType:"object",error:Xx,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Pr._)`${r}${(0,Pr.getProperty)(a)}`);e.if((0,Pr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Yc.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Pr._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Yc.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),_=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(_,Pr.Name),m}function p(){var f;let m={},_=b(o),S=!0;for(let $=0;${e$.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Qc=w((Q,Xc)=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.MissingRefError=Q.ValidationError=Q.CodeGen=Q.Name=Q.nil=Q.stringify=Q.str=Q._=Q.KeywordCxt=Q.Ajv=void 0;var t$=$h(),r$=xg(),n$=zg(),Ig=Rg(),o$=["/properties"],Es="http://json-schema.org/draft-07/schema",Tr=class extends t$.default{_addVocabularies(){super._addVocabularies(),r$.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n$.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ig,o$):Ig;this.addMetaSchema(e,Es,!1),this.refs["http://json-schema.org/schema"]=Es}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Es)?Es:void 0)}};Q.Ajv=Tr;Xc.exports=Q=Tr;Xc.exports.Ajv=Tr;Object.defineProperty(Q,"__esModule",{value:!0});Q.default=Tr;var s$=Tn();Object.defineProperty(Q,"KeywordCxt",{enumerable:!0,get:function(){return s$.KeywordCxt}});var zr=O();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return zr._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return zr.str}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return zr.stringify}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return zr.nil}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return zr.Name}});Object.defineProperty(Q,"CodeGen",{enumerable:!0,get:function(){return zr.CodeGen}});var i$=ts();Object.defineProperty(Q,"ValidationError",{enumerable:!0,get:function(){return i$.default}});var a$=zn();Object.defineProperty(Q,"MissingRefError",{enumerable:!0,get:function(){return a$.default}})});var Lg=w(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.formatNames=ct.fastFormats=ct.fullFormats=void 0;function at(t,e){return{validate:t,compare:e}}ct.fullFormats={date:at(Cg,nu),time:at(tu(!0),ou),"date-time":at(Ag(!0),Dg),"iso-time":at(tu(),Ng),"iso-date-time":at(Ag(),jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:f$,"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:v$,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:m$,int32:{type:"number",validate:_$},int64:{type:"number",validate:y$},float:{type:"number",validate:Mg},double:{type:"number",validate:Mg},password:!0,binary:!0};ct.fastFormats={...ct.fullFormats,date:at(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nu),time:at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ou),"date-time":at(/^\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,Dg),"iso-time":at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ng),"iso-date-time":at(/^\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,jg),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};ct.formatNames=Object.keys(ct.fullFormats);function c$(t){return t%4===0&&(t%100!==0||t%400===0)}var u$=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,l$=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Cg(t){let e=u$.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&c$(r)?29:l$[n])}function nu(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function ou(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Ng(t,e){if(!(t&&e))return;let r=eu.exec(t),n=eu.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=h$}function y$(t){return Number.isInteger(t)}function Mg(){return!0}var S$=/[^\\]\\Z/;function v$(t){if(S$.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ug=w(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.formatLimitDefinition=void 0;var b$=Qc(),et=O(),Ut=et.operators,ws={formatMaximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},formatMinimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},formatExclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},formatExclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},E$={message:({keyword:t,schemaCode:e})=>(0,et.str)`should be ${ws[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,et._)`{comparison: ${ws[t].okStr}, limit: ${e}}`};Rr.formatLimitDefinition={keyword:Object.keys(ws),type:"string",schemaType:"string",$data:!0,error:E$,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new b$.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,et._)`${p}[${c.schemaCode}]`);t.fail$data((0,et.or)((0,et._)`typeof ${f} != "object"`,(0,et._)`${f} instanceof RegExp`,(0,et._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,et._)`${i.code.formats}${(0,et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,et._)`${p}.compare(${r}, ${n}) ${ws[o].fail} 0`}},dependencies:["format"]};var w$=t=>(t.addKeyword(Rr.formatLimitDefinition),t);Rr.default=w$});var Hg=w((Fn,Fg)=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});var Ir=Lg(),k$=Ug(),su=O(),qg=new su.Name("fullFormats"),x$=new su.Name("fastFormats"),iu=(t,e={keywords:!0})=>{if(Array.isArray(e))return Zg(t,e,Ir.fullFormats,qg),t;let[r,n]=e.mode==="fast"?[Ir.fastFormats,x$]:[Ir.fullFormats,qg],o=e.formats||Ir.formatNames;return Zg(t,o,r,n),e.keywords&&(0,k$.default)(t),t};iu.get=(t,e="full")=>{let n=(e==="fast"?Ir.fastFormats:Ir.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Zg(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,su._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Fg.exports=Fn=iu;Object.defineProperty(Fn,"__esModule",{value:!0});Fn.default=iu});var dt=require("fs"),Fu=require("path");var L=require("path"),Xs=require("os"),Ur=require("fs");var Uu=require("url");var fy={};function iy(){return typeof __dirname<"u"?__dirname:(0,L.dirname)((0,Uu.fileURLToPath)(fy.url))}var KP=iy();function oo(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,L.join)((0,Xs.homedir)(),".claude-mem"),e=(0,L.join)(t,"settings.json");try{if((0,Ur.existsSync)(e)){let r=JSON.parse((0,Ur.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return t}var ee=oo(),so=process.env.CLAUDE_CONFIG_DIR||(0,L.join)((0,Xs.homedir)(),".claude"),Qs=(0,L.join)(so,"plugins","marketplaces","thedotmack"),ay=(0,L.join)(ee,"archives"),cy=(0,L.join)(ee,"logs"),uy=(0,L.join)(ee,"trash"),ly=(0,L.join)(ee,"backups"),dy=(0,L.join)(ee,"modes"),qu=(0,L.join)(ee,"settings.json"),GP=(0,L.join)(ee,"claude-mem.db"),py=(0,L.join)(ee,"vector-db"),Zu=(0,L.join)(ee,"observer-sessions"),JP=(0,L.basename)(Zu),YP=(0,L.join)(so,"settings.json"),BP=(0,L.join)(so,"commands"),XP=(0,L.join)(so,"CLAUDE.md");var De={dataDir:()=>ee,workerPid:()=>(0,L.join)(ee,"worker.pid"),serverPid:()=>(0,L.join)(ee,".server-beta.pid"),serverPort:()=>(0,L.join)(ee,".server-beta.port"),serverRuntime:()=>(0,L.join)(ee,".server-beta.runtime.json"),settings:()=>(0,L.join)(ee,"settings.json"),database:()=>(0,L.join)(ee,"claude-mem.db"),chroma:()=>(0,L.join)(ee,"chroma"),combinedCerts:()=>(0,L.join)(ee,"combined_certs.pem"),transcriptsConfig:()=>(0,L.join)(ee,"transcript-watch.json"),transcriptsState:()=>(0,L.join)(ee,"transcript-watch-state.json"),corpora:()=>(0,L.join)(ee,"corpora"),supervisorRegistry:()=>(0,L.join)(ee,"supervisor.json"),envFile:()=>(0,L.join)(ee,".env"),logsDir:()=>cy,archives:()=>ay,trash:()=>uy,backups:()=>ly,modes:()=>dy,vectorDb:()=>py,observerSessions:()=>Zu};var my=null;function hy(t){return(my??process.stderr.write.bind(process.stderr))(t)}function ei(t){hy(t)}var ri=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(ri||{}),ti=null,ni=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=De.logsDir();(0,dt.existsSync)(e)||(0,dt.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Fu.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=De.settings();if((0,dt.existsSync)(e)){let r=(0,dt.readFileSync)(e,"utf-8"),o=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ri[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} +${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${i}:${a}.${c}`}log(e,r,n,o,s){if(e0&&(d=` {${Object.entries(S).map(([$,b])=>`${$}=${b}`).join(", ")}}`)}let p=`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`;if(this.logFilePath)try{(0,ft.appendFileSync)(this.logFilePath,p+` -`,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));Ks(`[LOGGER] Failed to write to log file: ${m.message} -${m.stack??""} -`)}else Ks(p+` -`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){Js=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!Js||!(n instanceof Error))return;Js(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},y=new Ys;var Mu;function _(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var rt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},nr=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Mu=globalThis).__zod_globalConfig??(Mu.__zod_globalConfig={});var or=globalThis.__zod_globalConfig;function Re(t){return t&&Object.assign(or,t),or}var L={};Ru(L,{BIGINT_FORMAT_RANGES:()=>ju,Class:()=>Xs,NUMBER_FORMAT_RANGES:()=>oi,aborted:()=>Tt,allowsEval:()=>ti,assert:()=>ty,assertEqual:()=>B_,assertIs:()=>Q_,assertNever:()=>ey,assertNotEqual:()=>X_,assignProp:()=>xt,base64ToUint8Array:()=>Uu,base64urlToUint8Array:()=>yy,cached:()=>ir,captureStackTrace:()=>Qn,cleanEnum:()=>_y,cleanRegex:()=>Lr,clone:()=>Ke,cloneDef:()=>ny,createTransparentProxy:()=>uy,defineLazy:()=>F,esc:()=>Xn,escapeRegex:()=>ht,explicitlyAborted:()=>si,extend:()=>py,finalizeIssue:()=>Ce,floatSafeRemainder:()=>Qs,getElementAtPath:()=>oy,getEnumValues:()=>Dr,getLengthableOrigin:()=>Ur,getParsedType:()=>cy,getSizableOrigin:()=>Lu,hexToUint8Array:()=>vy,isObject:()=>Ft,isPlainObject:()=>Pt,issue:()=>ar,joinValues:()=>Bn,jsonStringifyReplacer:()=>sr,merge:()=>my,mergeDefs:()=>mt,normalizeParams:()=>z,nullish:()=>jr,numKeys:()=>ay,objectClone:()=>ry,omit:()=>dy,optionalKeys:()=>ni,parsedType:()=>ii,partial:()=>hy,pick:()=>ly,prefixIssues:()=>gt,primitiveTypes:()=>Du,promiseAllObject:()=>sy,propertyKeyTypes:()=>ri,randomString:()=>iy,required:()=>gy,safeExtend:()=>fy,shallowClone:()=>Nu,slugify:()=>ei,stringifyPrimitive:()=>eo,uint8ArrayToBase64:()=>qu,uint8ArrayToBase64url:()=>Sy,uint8ArrayToHex:()=>by,unwrapMessage:()=>Nr});function B_(t){return t}function X_(t){return t}function Q_(t){}function ey(t){throw new Error("Unexpected value in exhaustive check")}function ty(t){}function Dr(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Bn(t,e="|"){return t.map(r=>eo(r)).join(e)}function sr(t,e){return typeof e=="bigint"?e.toString():e}function ir(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function jr(t){return t==null}function Lr(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Qs(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)r?.[n],t):t}function sy(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s{};function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ti=ir(()=>{if(or.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Pt(t){if(Ft(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Ft(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Nu(t){return Pt(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function ay(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var cy=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ri=new Set(["string","number","symbol"]),Du=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ht(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function uy(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function eo(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ni(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var oi={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]},ju={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ly(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=mt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return xt(this,"shape",i),i},checks:[]});return Ke(t,s)}function dy(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=mt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return xt(this,"shape",i),i},checks:[]});return Ke(t,s)}function py(t,e){if(!Pt(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=mt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return xt(this,"shape",s),s}});return Ke(t,o)}function fy(t,e){if(!Pt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=mt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return xt(this,"shape",n),n}});return Ke(t,r)}function my(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=mt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return xt(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Ke(t,r)}function hy(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=mt(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return xt(this,"shape",c),c},checks:[]});return Ke(e,i)}function gy(t,e,r){let n=mt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return xt(this,"shape",s),s}});return Ke(e,n)}function Tt(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Nr(t){return typeof t=="string"?t:t?.message}function Ce(t,e,r){let n=t.message?t.message:Nr(t.inst?._zod.def?.error?.(t))??Nr(e?.error?.(t))??Nr(r.customError?.(t))??Nr(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function Lu(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ur(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ii(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function ar(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function _y(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Uu(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var Xs=class{constructor(...e){}};var Zu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,sr,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},to=_("$ZodError",Zu),ai=_("$ZodError",Zu,{Parent:Error});function Fu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Hu(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new rt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ce(c,s,Re())));throw Qn(a,o?.callee),a}return i.value};var no=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ce(c,s,Re())));throw Qn(a,o?.callee),a}return i.value};var qr=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new rt;return s.issues.length?{success:!1,error:new(t??to)(s.issues.map(i=>Ce(i,o,Re())))}:{success:!0,data:s.value}},Zr=qr(ai),Fr=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Ce(i,o,Re())))}:{success:!0,data:s.value}},oo=Fr(ai),Wu=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ro(t)(e,r,o)};var Vu=t=>(e,r,n)=>ro(t)(e,r,n);var Ku=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return no(t)(e,r,o)};var Ju=t=>async(e,r,n)=>no(t)(e,r,n);var Gu=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return qr(t)(e,r,o)};var Yu=t=>(e,r,n)=>qr(t)(e,r,n);var Bu=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Fr(t)(e,r,o)};var Xu=t=>async(e,r,n)=>Fr(t)(e,r,n);var Qu=/^[cC][0-9a-z]{6,}$/,el=/^[0-9a-z]+$/,tl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rl=/^[0-9a-vA-V]{20}$/,nl=/^[A-Za-z0-9]{27}$/,ol=/^[a-zA-Z0-9_-]{21}$/,sl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var il=/^([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})$/,ci=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var al=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var wy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function cl(){return new RegExp(wy,"u")}var ul=/^(?:(?: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])$/,ll=/^(([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}|:))$/;var dl=/^((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])$/,pl=/^(([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])$/,fl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ui=/^[A-Za-z0-9_-]*$/;var ml=/^https?$/,hl=/^\+[1-9]\d{6,14}$/,gl="(?:(?:\\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])))",_l=new RegExp(`^${gl}$`);function yl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Sl(t){return new RegExp(`^${yl(t)}$`)}function vl(t){let e=yl({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${gl}T(?:${n})$`)}var bl=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var El=/^-?\d+$/,li=/^-?\d+(?:\.\d+)?$/,wl=/^(?:true|false)$/i,kl=/^null$/i;var $l=/^[^A-Z]*$/,xl=/^[^a-z]*$/;var de=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Pl={number:"number",bigint:"bigint",object:"date"},di=_("$ZodCheckLessThan",(t,e)=>{de.init(t,e);let r=Pl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{de.init(t,e);let r=Pl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tl=_("$ZodCheckMultipleOf",(t,e)=>{de.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Qs(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),zl=_("$ZodCheckNumberFormat",(t,e)=>{de.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=oi[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=El)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Rl=_("$ZodCheckMaxLength",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=n.value;if(o.length<=e.maximum)return;let i=Ur(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Il=_("$ZodCheckMinLength",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ur(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ol=_("$ZodCheckLengthEquals",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ur(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Hr=_("$ZodCheckStringFormat",(t,e)=>{var r,n;de.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Al=_("$ZodCheckRegex",(t,e)=>{Hr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ml=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=$l),Hr.init(t,e)}),Cl=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=xl),Hr.init(t,e)}),Nl=_("$ZodCheckIncludes",(t,e)=>{de.init(t,e);let r=ht(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Dl=_("$ZodCheckStartsWith",(t,e)=>{de.init(t,e);let r=new RegExp(`^${ht(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),jl=_("$ZodCheckEndsWith",(t,e)=>{de.init(t,e);let r=new RegExp(`.*${ht(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Ll=_("$ZodCheckOverwrite",(t,e)=>{de.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var io=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(` +`+JSON.stringify(s,null,2)}catch{l=" "+this.formatData(s)}else l=" "+this.formatData(s);let d="";if(o){let{sessionId:f,memorySessionId:m,correlationId:_,...S}=o;Object.keys(S).length>0&&(d=` {${Object.entries(S).map(([E,v])=>`${E}=${v}`).join(", ")}}`)}let p=`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`;if(this.logFilePath)try{(0,dt.appendFileSync)(this.logFilePath,p+` +`,"utf8")}catch(f){ei(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)} +`)}else ei(p+` +`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){ti=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!ti||!(n instanceof Error))return;ti(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}happyPathError(e,r,n,o,s=""){let u=((new Error().stack||"").split(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",d={...n,location:l};return this.warn(e,`[HAPPY-PATH] ${r}`,d,o),s}},y=new ni;var Hu;function g(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var rt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},or=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Hu=globalThis).__zod_globalConfig??(Hu.__zod_globalConfig={});var sr=globalThis.__zod_globalConfig;function Oe(t){return t&&Object.assign(sr,t),sr}var U={};Lu(U,{BIGINT_FORMAT_RANGES:()=>Gu,Class:()=>si,NUMBER_FORMAT_RANGES:()=>di,aborted:()=>Tt,allowsEval:()=>ci,assert:()=>vy,assertEqual:()=>gy,assertIs:()=>yy,assertNever:()=>Sy,assertNotEqual:()=>_y,assignProp:()=>$t,base64ToUint8Array:()=>Yu,base64urlToUint8Array:()=>Dy,cached:()=>ar,captureStackTrace:()=>co,cleanEnum:()=>Ny,cleanRegex:()=>Hr,clone:()=>Je,cloneDef:()=>Ey,createTransparentProxy:()=>Ty,defineLazy:()=>H,esc:()=>ao,escapeRegex:()=>ft,explicitlyAborted:()=>pi,extend:()=>Iy,finalizeIssue:()=>je,floatSafeRemainder:()=>ii,getElementAtPath:()=>wy,getEnumValues:()=>Zr,getLengthableOrigin:()=>Wr,getParsedType:()=>Py,getSizableOrigin:()=>Ju,hexToUint8Array:()=>Ly,isObject:()=>Ft,isPlainObject:()=>Pt,issue:()=>cr,joinValues:()=>io,jsonStringifyReplacer:()=>ir,merge:()=>Oy,mergeDefs:()=>pt,normalizeParams:()=>z,nullish:()=>Fr,numKeys:()=>$y,objectClone:()=>by,omit:()=>Ry,optionalKeys:()=>li,parsedType:()=>fi,partial:()=>My,pick:()=>zy,prefixIssues:()=>mt,primitiveTypes:()=>Ku,promiseAllObject:()=>ky,propertyKeyTypes:()=>ui,randomString:()=>xy,required:()=>Cy,safeExtend:()=>Ay,shallowClone:()=>Vu,slugify:()=>ai,stringifyPrimitive:()=>uo,uint8ArrayToBase64:()=>Bu,uint8ArrayToBase64url:()=>jy,uint8ArrayToHex:()=>Uy,unwrapMessage:()=>qr});function gy(t){return t}function _y(t){return t}function yy(t){}function Sy(t){throw new Error("Unexpected value in exhaustive check")}function vy(t){}function Zr(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function io(t,e="|"){return t.map(r=>uo(r)).join(e)}function ir(t,e){return typeof e=="bigint"?e.toString():e}function ar(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Fr(t){return t==null}function Hr(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ii(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)r?.[n],t):t}function ky(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s{};function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ci=ar(()=>{if(sr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Pt(t){if(Ft(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Ft(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Vu(t){return Pt(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function $y(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Py=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ui=new Set(["string","number","symbol"]),Ku=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Ty(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function uo(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function li(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var di={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]},Gu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function zy(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=pt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function Ry(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=pt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function Iy(t,e){if(!Pt(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=pt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return $t(this,"shape",s),s}});return Je(t,o)}function Ay(t,e){if(!Pt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=pt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return $t(this,"shape",n),n}});return Je(t,r)}function Oy(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=pt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return $t(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Je(t,r)}function My(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=pt(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return $t(this,"shape",c),c},checks:[]});return Je(e,i)}function Cy(t,e,r){let n=pt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return $t(this,"shape",s),s}});return Je(e,n)}function Tt(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function qr(t){return typeof t=="string"?t:t?.message}function je(t,e,r){let n=t.message?t.message:qr(t.inst?._zod.def?.error?.(t))??qr(e?.error?.(t))??qr(r.customError?.(t))??qr(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function Ju(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wr(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function fi(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function cr(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ny(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Yu(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var si=class{constructor(...e){}};var Xu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,ir,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},lo=g("$ZodError",Xu),mi=g("$ZodError",Xu,{Parent:Error});function Qu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function el(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new rt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>je(c,s,Oe())));throw co(a,o?.callee),a}return i.value};var fo=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>je(c,s,Oe())));throw co(a,o?.callee),a}return i.value};var Vr=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new rt;return s.issues.length?{success:!1,error:new(t??lo)(s.issues.map(i=>je(i,o,Oe())))}:{success:!0,data:s.value}},Kr=Vr(mi),Gr=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>je(i,o,Oe())))}:{success:!0,data:s.value}},mo=Gr(mi),tl=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return po(t)(e,r,o)};var rl=t=>(e,r,n)=>po(t)(e,r,n);var nl=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return fo(t)(e,r,o)};var ol=t=>async(e,r,n)=>fo(t)(e,r,n);var sl=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Vr(t)(e,r,o)};var il=t=>(e,r,n)=>Vr(t)(e,r,n);var al=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Gr(t)(e,r,o)};var cl=t=>async(e,r,n)=>Gr(t)(e,r,n);var ul=/^[cC][0-9a-z]{6,}$/,ll=/^[0-9a-z]+$/,dl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pl=/^[0-9a-vA-V]{20}$/,fl=/^[A-Za-z0-9]{27}$/,ml=/^[a-zA-Z0-9_-]{21}$/,hl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gl=/^([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})$/,hi=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var _l=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Zy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function yl(){return new RegExp(Zy,"u")}var Sl=/^(?:(?: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])$/,vl=/^(([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}|:))$/;var bl=/^((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])$/,El=/^(([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])$/,wl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gi=/^[A-Za-z0-9_-]*$/;var kl=/^https?$/,xl=/^\+[1-9]\d{6,14}$/,$l="(?:(?:\\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])))",Pl=new RegExp(`^${$l}$`);function Tl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function zl(t){return new RegExp(`^${Tl(t)}$`)}function Rl(t){let e=Tl({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${$l}T(?:${n})$`)}var Il=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Al=/^-?\d+$/,_i=/^-?\d+(?:\.\d+)?$/,Ol=/^(?:true|false)$/i,Ml=/^null$/i;var Cl=/^[^A-Z]*$/,Nl=/^[^a-z]*$/;var fe=g("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Dl={number:"number",bigint:"bigint",object:"date"},yi=g("$ZodCheckLessThan",(t,e)=>{fe.init(t,e);let r=Dl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{fe.init(t,e);let r=Dl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),jl=g("$ZodCheckMultipleOf",(t,e)=>{fe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ii(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ll=g("$ZodCheckNumberFormat",(t,e)=>{fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=di[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Al)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Ul=g("$ZodCheckMaxLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=n.value;if(o.length<=e.maximum)return;let i=Wr(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ql=g("$ZodCheckMinLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Wr(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Zl=g("$ZodCheckLengthEquals",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Wr(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Jr=g("$ZodCheckStringFormat",(t,e)=>{var r,n;fe.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Fl=g("$ZodCheckRegex",(t,e)=>{Jr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hl=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Cl),Jr.init(t,e)}),Wl=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Nl),Jr.init(t,e)}),Vl=g("$ZodCheckIncludes",(t,e)=>{fe.init(t,e);let r=ft(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Kl=g("$ZodCheckStartsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`^${ft(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Gl=g("$ZodCheckEndsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`.*${ft(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Jl=g("$ZodCheckOverwrite",(t,e)=>{fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var go=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(` `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(` -`))}};var ql={major:4,minor:4,patch:3};var Y=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ql;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Tt(i),l;for(let d of a){if(d._zod.def.when){if(si(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new rt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Tt(i,p)))});else{if(i.issues.length===p)continue;u||(u=Tt(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Tt(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new rt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new rt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}F(t,"~standard",()=>({validate:o=>{try{let s=Zr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return oo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),uo=_("$ZodString",(t,e)=>{Y.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??bl(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),B=_("$ZodStringFormat",(t,e)=>{Hr.init(t,e),uo.init(t,e)}),Yl=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=il),B.init(t,e)}),Bl=_("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ci(n))}else e.pattern??(e.pattern=ci());B.init(t,e)}),Xl=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=al),B.init(t,e)}),Ql=_("$ZodURL",(t,e)=>{B.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===ml.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ed=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=cl()),B.init(t,e)}),td=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ol),B.init(t,e)}),rd=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Qu),B.init(t,e)}),nd=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=el),B.init(t,e)}),od=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=tl),B.init(t,e)}),sd=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=rl),B.init(t,e)}),id=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=nl),B.init(t,e)}),ad=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=vl(e)),B.init(t,e)}),cd=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=_l),B.init(t,e)}),ud=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Sl(e)),B.init(t,e)}),ld=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=sl),B.init(t,e)}),dd=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ul),B.init(t,e),t._zod.bag.format="ipv4"}),pd=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ll),B.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var fd=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=dl),B.init(t,e)}),md=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=pl),B.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function hd(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var gd=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=fl),B.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{hd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function xy(t){if(!ui.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return hd(r)}var _d=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=ui),B.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{xy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),yd=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=hl),B.init(t,e)});function Py(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Sd=_("$ZodJWT",(t,e)=>{B.init(t,e),t._zod.check=r=>{Py(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var mi=_("$ZodNumber",(t,e)=>{Y.init(t,e),t._zod.pattern=t._zod.bag.pattern??li,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),vd=_("$ZodNumberFormat",(t,e)=>{zl.init(t,e),mi.init(t,e)}),bd=_("$ZodBoolean",(t,e)=>{Y.init(t,e),t._zod.pattern=wl,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var Ed=_("$ZodNull",(t,e)=>{Y.init(t,e),t._zod.pattern=kl,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var wd=_("$ZodUnknown",(t,e)=>{Y.init(t,e),t._zod.parse=r=>r}),kd=_("$ZodNever",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Zl(t,e,r){t.issues.length&&e.issues.push(...gt(r,t.issues)),e.value[r]=t.value}var $d=_("$ZodArray",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;iZl(u,r,i))):Zl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function co(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...gt(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function xd(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=ni(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Pd(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(m=>co(m,r,p,e,l,d))):co(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var Ty=_("$ZodObject",(t,e)=>{if(Y.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=ir(()=>xd(e));F(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Ft,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],m=f._zod.optin==="optional",g=f._zod.optout==="optional",S=f._zod.run({value:u[p],issues:[]},c);S instanceof Promise?l.push(S.then(v=>co(v,a,p,u,m,g))):co(S,a,p,u,m,g)}return s?Pd(l,u,a,c,n.value,t):l.length?Promise.all(l).then(()=>a):a}}),Td=_("$ZodObjectJIT",(t,e)=>{Ty.init(t,e);let r=t._zod.parse,n=ir(()=>xd(e)),o=p=>{let f=new io(["shape","payload","ctx"]),m=n.value,g=b=>{let x=Xn(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let S=Object.create(null),v=0;for(let b of m.keys)S[b]=`key_${v++}`;f.write("const newResult = {};");for(let b of m.keys){let x=S[b],k=Xn(b),_e=p[b],V=_e?._zod?.optin==="optional",tt=_e?._zod?.optout==="optional";f.write(`const ${x} = ${g(b)};`),V&&tt?f.write(` - if (${x}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${x}.issues.map(iss => ({ +`))}};var Bl={major:4,minor:4,patch:3};var J=g("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Bl;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Tt(i),l;for(let d of a){if(d._zod.def.when){if(pi(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new rt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Tt(i,p)))});else{if(i.issues.length===p)continue;u||(u=Tt(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Tt(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new rt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new rt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}H(t,"~standard",()=>({validate:o=>{try{let s=Kr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return mo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),So=g("$ZodString",(t,e)=>{J.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Il(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Y=g("$ZodStringFormat",(t,e)=>{Jr.init(t,e),So.init(t,e)}),id=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=gl),Y.init(t,e)}),ad=g("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=hi(n))}else e.pattern??(e.pattern=hi());Y.init(t,e)}),cd=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=_l),Y.init(t,e)}),ud=g("$ZodURL",(t,e)=>{Y.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===kl.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ld=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=yl()),Y.init(t,e)}),dd=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ml),Y.init(t,e)}),pd=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ul),Y.init(t,e)}),fd=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ll),Y.init(t,e)}),md=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=dl),Y.init(t,e)}),hd=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pl),Y.init(t,e)}),gd=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=fl),Y.init(t,e)}),_d=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Rl(e)),Y.init(t,e)}),yd=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Pl),Y.init(t,e)}),Sd=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=zl(e)),Y.init(t,e)}),vd=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hl),Y.init(t,e)}),bd=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Sl),Y.init(t,e),t._zod.bag.format="ipv4"}),Ed=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=vl),Y.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var wd=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=bl),Y.init(t,e)}),kd=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=El),Y.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function xd(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var $d=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=wl),Y.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{xd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Wy(t){if(!gi.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return xd(r)}var Pd=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=gi),Y.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{Wy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Td=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=xl),Y.init(t,e)});function Vy(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var zd=g("$ZodJWT",(t,e)=>{Y.init(t,e),t._zod.check=r=>{Vy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var bi=g("$ZodNumber",(t,e)=>{J.init(t,e),t._zod.pattern=t._zod.bag.pattern??_i,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Rd=g("$ZodNumberFormat",(t,e)=>{Ll.init(t,e),bi.init(t,e)}),Id=g("$ZodBoolean",(t,e)=>{J.init(t,e),t._zod.pattern=Ol,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var Ad=g("$ZodNull",(t,e)=>{J.init(t,e),t._zod.pattern=Ml,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var Od=g("$ZodUnknown",(t,e)=>{J.init(t,e),t._zod.parse=r=>r}),Md=g("$ZodNever",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Xl(t,e,r){t.issues.length&&e.issues.push(...mt(r,t.issues)),e.value[r]=t.value}var Cd=g("$ZodArray",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;iXl(u,r,i))):Xl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function yo(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...mt(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Nd(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=li(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Dd(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(m=>yo(m,r,p,e,l,d))):yo(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var Ky=g("$ZodObject",(t,e)=>{if(J.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=ar(()=>Nd(e));H(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Ft,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],m=f._zod.optin==="optional",_=f._zod.optout==="optional",S=f._zod.run({value:u[p],issues:[]},c);S instanceof Promise?l.push(S.then(b=>yo(b,a,p,u,m,_))):yo(S,a,p,u,m,_)}return s?Dd(l,u,a,c,n.value,t):l.length?Promise.all(l).then(()=>a):a}}),jd=g("$ZodObjectJIT",(t,e)=>{Ky.init(t,e);let r=t._zod.parse,n=ar(()=>Nd(e)),o=p=>{let f=new go(["shape","payload","ctx"]),m=n.value,_=v=>{let $=ao(v);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let S=Object.create(null),b=0;for(let v of m.keys)S[v]=`key_${b++}`;f.write("const newResult = {};");for(let v of m.keys){let $=S[v],x=ao(v),Se=p[v],we=Se?._zod?.optin==="optional",Zt=Se?._zod?.optout==="optional";f.write(`const ${$} = ${_(v)};`),we&&Zt?f.write(` + if (${$}.issues.length) { + if (${x} in input) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] + path: iss.path ? [${x}, ...iss.path] : [${x}] }))); } } - if (${x}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + if (${$}.value === undefined) { + if (${x} in input) { + newResult[${x}] = undefined; } } else { - newResult[${k}] = ${x}.value; + newResult[${x}] = ${$}.value; } - `):V?f.write(` - if (${x}.issues.length) { - payload.issues = payload.issues.concat(${x}.issues.map(iss => ({ + `):we?f.write(` + if (${$}.issues.length) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] + path: iss.path ? [${x}, ...iss.path] : [${x}] }))); } - if (${x}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; + if (${$}.value === undefined) { + if (${x} in input) { + newResult[${x}] = undefined; } } else { - newResult[${k}] = ${x}.value; + newResult[${x}] = ${$}.value; } `):f.write(` - const ${x}_present = ${k} in input; - if (${x}.issues.length) { - payload.issues = payload.issues.concat(${x}.issues.map(iss => ({ + const ${$}_present = ${x} in input; + if (${$}.issues.length) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] + path: iss.path ? [${x}, ...iss.path] : [${x}] }))); } - if (!${x}_present && !${x}.issues.length) { + if (!${$}_present && !${$}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, - path: [${k}] + path: [${x}] }); } - if (${x}_present) { - if (${x}.value === undefined) { - newResult[${k}] = undefined; + if (${$}_present) { + if (${$}.value === undefined) { + newResult[${x}] = undefined; } else { - newResult[${k}] = ${x}.value; + newResult[${x}] = ${$}.value; } } - `)}f.write("payload.value = newResult;"),f.write("return payload;");let $=f.compile();return(b,x)=>$(p,b,x)},s,i=Ft,a=!or.jitless,u=a&&ti.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return i(m)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),l?Pd([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function Fl(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Tt(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Ce(i,n,Re())))}),e)}var hi=_("$ZodUnion",(t,e)=>{Y.init(t,e),F(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),F(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),F(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),F(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>Lr(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>Fl(a,n,t,o)):Fl(i,n,t,o)}});var zd=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,hi.init(t,e);let r=t._zod.parse;F(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=ir(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ft(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Rd=_("$ZodIntersection",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Hl(r,c,u)):Hl(r,s,i)}});function fi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Pt(t)&&Pt(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=fi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;na.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Tt(t))return t;let i=fi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Id=_("$ZodRecord",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Pt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>Ce(f,n,Re())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...gt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...gt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&li.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Ce(d,n,Re())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...gt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...gt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Od=_("$ZodEnum",(t,e)=>{Y.init(t,e);let r=Dr(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>ri.has(typeof o)).map(o=>typeof o=="string"?ht(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Ad=_("$ZodLiteral",(t,e)=>{if(Y.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ht(n):n?ht(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var Md=_("$ZodTransform",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new nr(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new rt;return r.value=o,r.fallback=!0,r}});function Wl(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var gi=_("$ZodOptional",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.optout="optional",F(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),F(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Lr(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>Wl(i,o)):Wl(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Cd=_("$ZodExactOptional",(t,e)=>{gi.init(t,e),F(t._zod,"values",()=>e.innerType._zod.values),F(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),Nd=_("$ZodNullable",(t,e)=>{Y.init(t,e),F(t._zod,"optin",()=>e.innerType._zod.optin),F(t._zod,"optout",()=>e.innerType._zod.optout),F(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Lr(r.source)}|null)$`):void 0}),F(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Dd=_("$ZodDefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Vl(s,e)):Vl(o,e)}});function Vl(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var jd=_("$ZodPrefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Ld=_("$ZodNonOptional",(t,e)=>{Y.init(t,e),F(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Kl(s,t)):Kl(o,t)}});function Kl(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Ud=_("$ZodCatch",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"optout",()=>e.innerType._zod.optout),F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Ce(i,n,Re()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Ce(s,n,Re()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var _i=_("$ZodPipe",(t,e)=>{Y.init(t,e),F(t._zod,"values",()=>e.in._zod.values),F(t._zod,"optin",()=>e.in._zod.optin),F(t._zod,"optout",()=>e.out._zod.optout),F(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>ao(i,e.in,n)):ao(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ao(s,e.out,n)):ao(o,e.out,n)}});function ao(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var qd=_("$ZodPreprocess",(t,e)=>{_i.init(t,e)}),Zd=_("$ZodReadonly",(t,e)=>{Y.init(t,e),F(t._zod,"propValues",()=>e.innerType._zod.propValues),F(t._zod,"values",()=>e.innerType._zod.values),F(t._zod,"optin",()=>e.innerType?._zod?.optin),F(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Jl):Jl(o)}});function Jl(t){return t.value=Object.freeze(t.value),t}var Fd=_("$ZodCustom",(t,e)=>{de.init(t,e),Y.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Gl(s,r,n,t));Gl(o,r,n,t)}});function Gl(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(ar(o))}}var zy=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,i=ii(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${eo(o.values[0])}`:`Invalid option: expected one of ${Bn(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Bn(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Hd(){return{localeError:zy()}}var Wd;var yi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ry(){return new yi}(Wd=globalThis).__zod_globalRegistry??(Wd.__zod_globalRegistry=Ry());var Ht=globalThis.__zod_globalRegistry;function Vd(t,e){return new t({type:"string",...z(e)})}function Kd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function Si(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function Jd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function Gd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function Yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function Bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function Xd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function Qd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function ep(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function rp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function np(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function op(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function sp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function ip(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function ap(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function cp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function up(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function lp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function pp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function fp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}function mp(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function hp(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function gp(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function _p(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function yp(t,e){return new t({type:"number",checks:[],...z(e)})}function Sp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function vp(t,e){return new t({type:"boolean",...z(e)})}function bp(t,e){return new t({type:"null",...z(e)})}function Ep(t){return new t({type:"unknown"})}function wp(t,e){return new t({type:"never",...z(e)})}function lo(t,e){return new di({check:"less_than",...z(e),value:t,inclusive:!1})}function Wr(t,e){return new di({check:"less_than",...z(e),value:t,inclusive:!0})}function po(t,e){return new pi({check:"greater_than",...z(e),value:t,inclusive:!1})}function Vr(t,e){return new pi({check:"greater_than",...z(e),value:t,inclusive:!0})}function fo(t,e){return new Tl({check:"multiple_of",...z(e),value:t})}function mo(t,e){return new Rl({check:"max_length",...z(e),maximum:t})}function cr(t,e){return new Il({check:"min_length",...z(e),minimum:t})}function ho(t,e){return new Ol({check:"length_equals",...z(e),length:t})}function vi(t,e){return new Al({check:"string_format",format:"regex",...z(e),pattern:t})}function bi(t){return new Ml({check:"string_format",format:"lowercase",...z(t)})}function Ei(t){return new Cl({check:"string_format",format:"uppercase",...z(t)})}function wi(t,e){return new Nl({check:"string_format",format:"includes",...z(e),includes:t})}function ki(t,e){return new Dl({check:"string_format",format:"starts_with",...z(e),prefix:t})}function $i(t,e){return new jl({check:"string_format",format:"ends_with",...z(e),suffix:t})}function zt(t){return new Ll({check:"overwrite",tx:t})}function xi(t){return zt(e=>e.normalize(t))}function Pi(){return zt(t=>t.trim())}function Ti(){return zt(t=>t.toLowerCase())}function zi(){return zt(t=>t.toUpperCase())}function Ri(){return zt(t=>ei(t))}function kp(t,e,r){return new t({type:"array",element:e,...z(r)})}function $p(t,e,r){let n=z(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function Pp(t,e){let r=Iy(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(ar(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(ar(s))}},t(n.value,n)),e);return r}function Iy(t,e){let r=new de({check:"custom",...z(e)});return r._zod.check=t,r}function Ii(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ht,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function se(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),se(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&be(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Oi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ + `)}f.write("payload.value = newResult;"),f.write("return payload;");let E=f.compile();return(v,$)=>E(p,v,$)},s,i=Ft,a=!sr.jitless,u=a&&ci.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return i(m)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),l?Dd([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function Ql(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Tt(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>je(i,n,Oe())))}),e)}var Ei=g("$ZodUnion",(t,e)=>{J.init(t,e),H(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),H(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),H(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),H(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>Hr(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>Ql(a,n,t,o)):Ql(i,n,t,o)}});var Ld=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ei.init(t,e);let r=t._zod.parse;H(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=ar(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ft(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Ud=g("$ZodIntersection",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ed(r,c,u)):ed(r,s,i)}});function vi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Pt(t)&&Pt(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=vi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;na.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Tt(t))return t;let i=vi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var qd=g("$ZodRecord",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Pt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>je(f,n,Oe())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...mt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...mt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&_i.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>je(d,n,Oe())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...mt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...mt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Zd=g("$ZodEnum",(t,e)=>{J.init(t,e);let r=Zr(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>ui.has(typeof o)).map(o=>typeof o=="string"?ft(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Fd=g("$ZodLiteral",(t,e)=>{if(J.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ft(n):n?ft(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var Hd=g("$ZodTransform",(t,e)=>{J.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new rt;return r.value=o,r.fallback=!0,r}});function td(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var wi=g("$ZodOptional",(t,e)=>{J.init(t,e),t._zod.optin="optional",t._zod.optout="optional",H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Hr(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>td(i,o)):td(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Wd=g("$ZodExactOptional",(t,e)=>{wi.init(t,e),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),Vd=g("$ZodNullable",(t,e)=>{J.init(t,e),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Hr(r.source)}|null)$`):void 0}),H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Kd=g("$ZodDefault",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rd(s,e)):rd(o,e)}});function rd(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Gd=g("$ZodPrefault",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Jd=g("$ZodNonOptional",(t,e)=>{J.init(t,e),H(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>nd(s,t)):nd(o,t)}});function nd(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Yd=g("$ZodCatch",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>je(i,n,Oe()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>je(s,n,Oe()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var ki=g("$ZodPipe",(t,e)=>{J.init(t,e),H(t._zod,"values",()=>e.in._zod.values),H(t._zod,"optin",()=>e.in._zod.optin),H(t._zod,"optout",()=>e.out._zod.optout),H(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>_o(i,e.in,n)):_o(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>_o(s,e.out,n)):_o(o,e.out,n)}});function _o(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var Bd=g("$ZodPreprocess",(t,e)=>{ki.init(t,e)}),Xd=g("$ZodReadonly",(t,e)=>{J.init(t,e),H(t._zod,"propValues",()=>e.innerType._zod.propValues),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"optin",()=>e.innerType?._zod?.optin),H(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(od):od(o)}});function od(t){return t.value=Object.freeze(t.value),t}var Qd=g("$ZodCustom",(t,e)=>{fe.init(t,e),J.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>sd(s,r,n,t));sd(o,r,n,t)}});function sd(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(cr(o))}}var Gy=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,i=fi(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${uo(o.values[0])}`:`Invalid option: expected one of ${io(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${io(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function ep(){return{localeError:Gy()}}var tp;var xi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Jy(){return new xi}(tp=globalThis).__zod_globalRegistry??(tp.__zod_globalRegistry=Jy());var Ht=globalThis.__zod_globalRegistry;function rp(t,e){return new t({type:"string",...z(e)})}function np(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function $i(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function op(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function ip(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function ap(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function cp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function up(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function lp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function dp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function pp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function fp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function mp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function hp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function gp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function _p(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function yp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function Sp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function vp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function bp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function Ep(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function wp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}function kp(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function xp(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function $p(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function Pp(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function Tp(t,e){return new t({type:"number",checks:[],...z(e)})}function zp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function Rp(t,e){return new t({type:"boolean",...z(e)})}function Ip(t,e){return new t({type:"null",...z(e)})}function Ap(t){return new t({type:"unknown"})}function Op(t,e){return new t({type:"never",...z(e)})}function vo(t,e){return new yi({check:"less_than",...z(e),value:t,inclusive:!1})}function Yr(t,e){return new yi({check:"less_than",...z(e),value:t,inclusive:!0})}function bo(t,e){return new Si({check:"greater_than",...z(e),value:t,inclusive:!1})}function Br(t,e){return new Si({check:"greater_than",...z(e),value:t,inclusive:!0})}function Eo(t,e){return new jl({check:"multiple_of",...z(e),value:t})}function wo(t,e){return new Ul({check:"max_length",...z(e),maximum:t})}function ur(t,e){return new ql({check:"min_length",...z(e),minimum:t})}function ko(t,e){return new Zl({check:"length_equals",...z(e),length:t})}function Pi(t,e){return new Fl({check:"string_format",format:"regex",...z(e),pattern:t})}function Ti(t){return new Hl({check:"string_format",format:"lowercase",...z(t)})}function zi(t){return new Wl({check:"string_format",format:"uppercase",...z(t)})}function Ri(t,e){return new Vl({check:"string_format",format:"includes",...z(e),includes:t})}function Ii(t,e){return new Kl({check:"string_format",format:"starts_with",...z(e),prefix:t})}function Ai(t,e){return new Gl({check:"string_format",format:"ends_with",...z(e),suffix:t})}function zt(t){return new Jl({check:"overwrite",tx:t})}function Oi(t){return zt(e=>e.normalize(t))}function Mi(){return zt(t=>t.trim())}function Ci(){return zt(t=>t.toLowerCase())}function Ni(){return zt(t=>t.toUpperCase())}function Di(){return zt(t=>ai(t))}function Mp(t,e,r){return new t({type:"array",element:e,...z(r)})}function Cp(t,e,r){let n=z(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Np(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function Dp(t,e){let r=Yy(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(cr(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(cr(s))}},t(n.value,n)),e);return r}function Yy(t,e){let r=new fe({check:"custom",...z(e)});return r._zod.check=t,r}function ji(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ht,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function se(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),se(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ke(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Li(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Ai(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(m.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let p=a._zod.parent;if(p&&p!==d){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Kr(e,"input",t.processors),output:Kr(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return be(n.element,r);if(n.type==="set")return be(n.valueType,r);if(n.type==="lazy")return be(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return be(n.innerType,r);if(n.type==="intersection")return be(n.left,r)||be(n.right,r);if(n.type==="record"||n.type==="map")return be(n.keyType,r)||be(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:be(n.in,r)||be(n.out,r);if(n.type==="object"){for(let o in n.shape)if(be(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(be(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(be(o,r))return!0;return!!(n.rest&&be(n.rest,r))}return!1}var Tp=(t,e={})=>r=>{let n=Ii({...r,processors:e});return se(t,n),Oi(n,t),Ai(n,t)},Kr=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Ii({...o??{},target:s,io:e,processors:r});return se(t,i),Oi(i,t),Ai(i,t)};var Oy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},zp=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Oy[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Rp=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Ip=(t,e,r,n)=>{r.type="boolean"};var Op=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Ap=(t,e,r,n)=>{r.not={}};var Mp=(t,e,r,n)=>{};var Cp=(t,e,r,n)=>{let o=t._zod.def,s=Dr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Np=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var Dp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var jp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Lp=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=se(s.element,e,{...n,path:[...n.path,"items"]})},Up=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=se(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=se(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},qp=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>se(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Zp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=se(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var Fp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=se(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=se(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=se(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},Hp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Wp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},Vp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Kp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Jp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Gp=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;se(i,e,n);let a=e.seen.get(t);a.ref=i},Yp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var Mi=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function ur(t){return!!t._zod}function Rt(t,e){return ur(t)?Zr(t,e):t.safeParse(e)}function go(t){if(!t)return;let e;if(ur(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bp(t){if(ur(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Gr={};Ru(Gr,{ZodISODate:()=>Qp,ZodISODateTime:()=>Xp,ZodISODuration:()=>tf,ZodISOTime:()=>ef,date:()=>Ni,datetime:()=>Ci,duration:()=>ji,time:()=>Di});var Xp=_("ZodISODateTime",(t,e)=>{ad.init(t,e),te.init(t,e)});function Ci(t){return mp(Xp,t)}var Qp=_("ZodISODate",(t,e)=>{cd.init(t,e),te.init(t,e)});function Ni(t){return hp(Qp,t)}var ef=_("ZodISOTime",(t,e)=>{ud.init(t,e),te.init(t,e)});function Di(t){return gp(ef,t)}var tf=_("ZodISODuration",(t,e)=>{ld.init(t,e),te.init(t,e)});function ji(t){return _p(tf,t)}var qy=(t,e)=>{to.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Hu(t,r)},flatten:{value:r=>Fu(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,sr,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,sr,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Ie=_("ZodError",qy,{Parent:Error});var rf=ro(Ie),nf=no(Ie),of=qr(Ie),sf=Fr(Ie),af=Wu(Ie),cf=Vu(Ie),uf=Ku(Ie),lf=Ju(Ie),df=Gu(Ie),pf=Yu(Ie),ff=Bu(Ie),mf=Xu(Ie);var hf=new WeakMap;function Yr(t,e,r){let n=Object.getPrototypeOf(t),o=hf.get(n);if(o||(o=new Set,hf.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=_("ZodType",(t,e)=>(Y.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Kr(t,"input"),output:Kr(t,"output")}}),t.toJSONSchema=Tp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>rf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>of(t,r,n),t.parseAsync=async(r,n)=>nf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>sf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>af(t,r,n),t.decode=(r,n)=>cf(t,r,n),t.encodeAsync=async(r,n)=>uf(t,r,n),t.decodeAsync=async(r,n)=>lf(t,r,n),t.safeEncode=(r,n)=>df(t,r,n),t.safeDecode=(r,n)=>pf(t,r,n),t.safeEncodeAsync=async(r,n)=>ff(t,r,n),t.safeDecodeAsync=async(r,n)=>mf(t,r,n),Yr(t,"ZodType",{check(...r){let n=this.def;return this.clone(L.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Ke(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(IS(r,n))},superRefine(r,n){return this.check(OS(r,n))},overwrite(r){return this.check(zt(r))},optional(){return ne(this)},exactOptional(){return SS(this)},nullable(){return Sf(this)},nullish(){return ne(Sf(this))},nonoptional(r){return $S(this,r)},array(){return D(this)},or(r){return X([this,r])},and(r){return yo(this,r)},transform(r){return vf(this,xf(r))},default(r){return ES(this,r)},prefault(r){return kS(this,r)},catch(r){return PS(this,r)},pipe(r){return vf(this,r)},readonly(){return RS(this)},describe(r){let n=this.clone();return Ht.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ht.get(this);let n=this.clone();return Ht.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ht.get(t)?.description},configurable:!0}),t)),bf=_("_ZodString",(t,e)=>{uo.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>zp(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Yr(t,"_ZodString",{regex(...n){return this.check(vi(...n))},includes(...n){return this.check(wi(...n))},startsWith(...n){return this.check(ki(...n))},endsWith(...n){return this.check($i(...n))},min(...n){return this.check(cr(...n))},max(...n){return this.check(mo(...n))},length(...n){return this.check(ho(...n))},nonempty(...n){return this.check(cr(1,...n))},lowercase(n){return this.check(bi(n))},uppercase(n){return this.check(Ei(n))},trim(){return this.check(Pi())},normalize(...n){return this.check(xi(...n))},toLowerCase(){return this.check(Ti())},toUpperCase(){return this.check(zi())},slugify(){return this.check(Ri())}})}),Fy=_("ZodString",(t,e)=>{uo.init(t,e),bf.init(t,e),t.email=r=>t.check(Kd(Hy,r)),t.url=r=>t.check(Xd(Wy,r)),t.jwt=r=>t.check(fp(iS,r)),t.emoji=r=>t.check(Qd(Vy,r)),t.guid=r=>t.check(Si(gf,r)),t.uuid=r=>t.check(Jd(_o,r)),t.uuidv4=r=>t.check(Gd(_o,r)),t.uuidv6=r=>t.check(Yd(_o,r)),t.uuidv7=r=>t.check(Bd(_o,r)),t.nanoid=r=>t.check(ep(Ky,r)),t.guid=r=>t.check(Si(gf,r)),t.cuid=r=>t.check(tp(Jy,r)),t.cuid2=r=>t.check(rp(Gy,r)),t.ulid=r=>t.check(np(Yy,r)),t.base64=r=>t.check(lp(nS,r)),t.base64url=r=>t.check(dp(oS,r)),t.xid=r=>t.check(op(By,r)),t.ksuid=r=>t.check(sp(Xy,r)),t.ipv4=r=>t.check(ip(Qy,r)),t.ipv6=r=>t.check(ap(eS,r)),t.cidrv4=r=>t.check(cp(tS,r)),t.cidrv6=r=>t.check(up(rS,r)),t.e164=r=>t.check(pp(sS,r)),t.datetime=r=>t.check(Ci(r)),t.date=r=>t.check(Ni(r)),t.time=r=>t.check(Di(r)),t.duration=r=>t.check(ji(r))});function h(t){return Vd(Fy,t)}var te=_("ZodStringFormat",(t,e)=>{B.init(t,e),bf.init(t,e)}),Hy=_("ZodEmail",(t,e)=>{Xl.init(t,e),te.init(t,e)});var gf=_("ZodGUID",(t,e)=>{Yl.init(t,e),te.init(t,e)});var _o=_("ZodUUID",(t,e)=>{Bl.init(t,e),te.init(t,e)});var Wy=_("ZodURL",(t,e)=>{Ql.init(t,e),te.init(t,e)});var Vy=_("ZodEmoji",(t,e)=>{ed.init(t,e),te.init(t,e)});var Ky=_("ZodNanoID",(t,e)=>{td.init(t,e),te.init(t,e)});var Jy=_("ZodCUID",(t,e)=>{rd.init(t,e),te.init(t,e)});var Gy=_("ZodCUID2",(t,e)=>{nd.init(t,e),te.init(t,e)});var Yy=_("ZodULID",(t,e)=>{od.init(t,e),te.init(t,e)});var By=_("ZodXID",(t,e)=>{sd.init(t,e),te.init(t,e)});var Xy=_("ZodKSUID",(t,e)=>{id.init(t,e),te.init(t,e)});var Qy=_("ZodIPv4",(t,e)=>{dd.init(t,e),te.init(t,e)});var eS=_("ZodIPv6",(t,e)=>{pd.init(t,e),te.init(t,e)});var tS=_("ZodCIDRv4",(t,e)=>{fd.init(t,e),te.init(t,e)});var rS=_("ZodCIDRv6",(t,e)=>{md.init(t,e),te.init(t,e)});var nS=_("ZodBase64",(t,e)=>{gd.init(t,e),te.init(t,e)});var oS=_("ZodBase64URL",(t,e)=>{_d.init(t,e),te.init(t,e)});var sS=_("ZodE164",(t,e)=>{yd.init(t,e),te.init(t,e)});var iS=_("ZodJWT",(t,e)=>{Sd.init(t,e),te.init(t,e)});var Ef=_("ZodNumber",(t,e)=>{mi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Rp(t,n,o,s),Yr(t,"ZodNumber",{gt(n,o){return this.check(po(n,o))},gte(n,o){return this.check(Vr(n,o))},min(n,o){return this.check(Vr(n,o))},lt(n,o){return this.check(lo(n,o))},lte(n,o){return this.check(Wr(n,o))},max(n,o){return this.check(Wr(n,o))},int(n){return this.check(_f(n))},safe(n){return this.check(_f(n))},positive(n){return this.check(po(0,n))},nonnegative(n){return this.check(Vr(0,n))},negative(n){return this.check(lo(0,n))},nonpositive(n){return this.check(Wr(0,n))},multipleOf(n,o){return this.check(fo(n,o))},step(n,o){return this.check(fo(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function H(t){return yp(Ef,t)}var aS=_("ZodNumberFormat",(t,e)=>{vd.init(t,e),Ef.init(t,e)});function _f(t){return Sp(aS,t)}var cS=_("ZodBoolean",(t,e)=>{bd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ip(t,r,n,o)});function le(t){return vp(cS,t)}var uS=_("ZodNull",(t,e)=>{Ed.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Op(t,r,n,o)});function wf(t){return bp(uS,t)}var lS=_("ZodUnknown",(t,e)=>{wd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mp(t,r,n,o)});function re(){return Ep(lS)}var dS=_("ZodNever",(t,e)=>{kd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ap(t,r,n,o)});function pS(t){return wp(dS,t)}var fS=_("ZodArray",(t,e)=>{$d.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Lp(t,r,n,o),t.element=e.element,Yr(t,"ZodArray",{min(r,n){return this.check(cr(r,n))},nonempty(r){return this.check(cr(1,r))},max(r,n){return this.check(mo(r,n))},length(r,n){return this.check(ho(r,n))},unwrap(){return this.element}})});function D(t,e){return kp(fS,t,e)}var kf=_("ZodObject",(t,e)=>{Td.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Up(t,r,n,o),L.defineLazy(t,"shape",()=>e.shape),Yr(t,"ZodObject",{keyof(){return $e(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:re()})},loose(){return this.clone({...this._zod.def,catchall:re()})},strict(){return this.clone({...this._zod.def,catchall:pS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return L.extend(this,r)},safeExtend(r){return L.safeExtend(this,r)},merge(r){return L.merge(this,r)},pick(r){return L.pick(this,r)},omit(r){return L.omit(this,r)},partial(...r){return L.partial(Pf,this,r[0])},required(...r){return L.required(Tf,this,r[0])}})});function w(t,e){let r={type:"object",shape:t??{},...L.normalizeParams(e)};return new kf(r)}function Ee(t,e){return new kf({type:"object",shape:t,catchall:re(),...L.normalizeParams(e)})}var $f=_("ZodUnion",(t,e)=>{hi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qp(t,r,n,o),t.options=e.options});function X(t,e){return new $f({type:"union",options:t,...L.normalizeParams(e)})}var mS=_("ZodDiscriminatedUnion",(t,e)=>{$f.init(t,e),zd.init(t,e)});function Ui(t,e,r){return new mS({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var hS=_("ZodIntersection",(t,e)=>{Rd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zp(t,r,n,o)});function yo(t,e){return new hS({type:"intersection",left:t,right:e})}var yf=_("ZodRecord",(t,e)=>{Id.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fp(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function G(t,e,r){return!e||!e._zod?new yf({type:"record",keyType:h(),valueType:t,...L.normalizeParams(e)}):new yf({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var Li=_("ZodEnum",(t,e)=>{Od.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Cp(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...e,checks:[],...L.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Li({...e,checks:[],...L.normalizeParams(o),entries:s})}});function $e(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Li({type:"enum",entries:r,...L.normalizeParams(e)})}var gS=_("ZodLiteral",(t,e)=>{Ad.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Np(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function P(t,e){return new gS({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var _S=_("ZodTransform",(t,e)=>{Md.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jp(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new nr(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(L.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(L.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function xf(t){return new _S({type:"transform",transform:t})}var Pf=_("ZodOptional",(t,e)=>{gi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ne(t){return new Pf({type:"optional",innerType:t})}var yS=_("ZodExactOptional",(t,e)=>{Cd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function SS(t){return new yS({type:"optional",innerType:t})}var vS=_("ZodNullable",(t,e)=>{Nd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Sf(t){return new vS({type:"nullable",innerType:t})}var bS=_("ZodDefault",(t,e)=>{Dd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function ES(t,e){return new bS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var wS=_("ZodPrefault",(t,e)=>{jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function kS(t,e){return new wS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Tf=_("ZodNonOptional",(t,e)=>{Ld.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function $S(t,e){return new Tf({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var xS=_("ZodCatch",(t,e)=>{Ud.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function PS(t,e){return new xS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var zf=_("ZodPipe",(t,e)=>{_i.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o),t.in=e.in,t.out=e.out});function vf(t,e){return new zf({type:"pipe",in:t,out:e})}var TS=_("ZodPreprocess",(t,e)=>{zf.init(t,e),qd.init(t,e)}),zS=_("ZodReadonly",(t,e)=>{Zd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function RS(t){return new zS({type:"readonly",innerType:t})}var Rf=_("ZodCustom",(t,e)=>{Fd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Dp(t,r,n,o)});function If(t,e){return $p(Rf,t??(()=>!0),e)}function IS(t,e={}){return xp(Rf,t,e)}function OS(t,e){return Pp(t,e)}function qi(t,e){return new TS({type:"pipe",in:xf(t),out:e})}Re(Hd());var Fi="2025-11-25";var Of=[Fi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],It="io.modelcontextprotocol/related-task",vo="2.0",ce=If(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Af=X([h(),H().int()]),Mf=h(),rR=Ee({ttl:H().optional(),pollInterval:H().optional()}),AS=w({ttl:H().optional()}),MS=w({taskId:h()}),Hi=Ee({progressToken:Af.optional(),[It]:MS.optional()}),Oe=w({_meta:Hi.optional()}),Br=Oe.extend({task:AS.optional()}),Cf=t=>Br.safeParse(t).success,pe=w({method:h(),params:Oe.loose().optional()}),Ne=w({_meta:Hi.optional()}),De=w({method:h(),params:Ne.loose().optional()}),fe=Ee({_meta:Hi.optional()}),bo=X([h(),H().int()]),Nf=w({jsonrpc:P(vo),id:bo,...pe.shape}).strict(),Wi=t=>Nf.safeParse(t).success,Df=w({jsonrpc:P(vo),...De.shape}).strict(),jf=t=>Df.safeParse(t).success,Vi=w({jsonrpc:P(vo),id:bo,result:fe}).strict(),Xr=t=>Vi.safeParse(t).success;var N;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));var Ki=w({jsonrpc:P(vo),id:bo.optional(),error:w({code:H().int(),message:h(),data:re().optional()})}).strict();var Lf=t=>Ki.safeParse(t).success;var Uf=X([Nf,Df,Vi,Ki]),nR=X([Vi,Ki]),Eo=fe.strict(),CS=Ne.extend({requestId:bo.optional(),reason:h().optional()}),wo=De.extend({method:P("notifications/cancelled"),params:CS}),NS=w({src:h(),mimeType:h().optional(),sizes:D(h()).optional(),theme:$e(["light","dark"]).optional()}),Qr=w({icons:D(NS).optional()}),lr=w({name:h(),title:h().optional()}),qf=lr.extend({...lr.shape,...Qr.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),DS=yo(w({applyDefaults:le().optional()}),G(h(),re())),jS=qi(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,yo(w({form:DS.optional(),url:ce.optional()}),G(h(),re()).optional())),LS=Ee({list:ce.optional(),cancel:ce.optional(),requests:Ee({sampling:Ee({createMessage:ce.optional()}).optional(),elicitation:Ee({create:ce.optional()}).optional()}).optional()}),US=Ee({list:ce.optional(),cancel:ce.optional(),requests:Ee({tools:Ee({call:ce.optional()}).optional()}).optional()}),qS=w({experimental:G(h(),ce).optional(),sampling:w({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:jS.optional(),roots:w({listChanged:le().optional()}).optional(),tasks:LS.optional(),extensions:G(h(),ce).optional()}),ZS=Oe.extend({protocolVersion:h(),capabilities:qS,clientInfo:qf}),Ji=pe.extend({method:P("initialize"),params:ZS});var FS=w({experimental:G(h(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:w({listChanged:le().optional()}).optional(),resources:w({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:w({listChanged:le().optional()}).optional(),tasks:US.optional(),extensions:G(h(),ce).optional()}),HS=fe.extend({protocolVersion:h(),capabilities:FS,serverInfo:qf,instructions:h().optional()}),Gi=De.extend({method:P("notifications/initialized"),params:Ne.optional()});var ko=pe.extend({method:P("ping"),params:Oe.optional()}),WS=w({progress:H(),total:ne(H()),message:ne(h())}),VS=w({...Ne.shape,...WS.shape,progressToken:Af}),$o=De.extend({method:P("notifications/progress"),params:VS}),KS=Oe.extend({cursor:Mf.optional()}),en=pe.extend({params:KS.optional()}),tn=fe.extend({nextCursor:Mf.optional()}),JS=$e(["working","input_required","completed","failed","cancelled"]),rn=w({taskId:h(),status:JS,ttl:X([H(),wf()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ne(H()),statusMessage:ne(h())}),dr=fe.extend({task:rn}),GS=Ne.merge(rn),nn=De.extend({method:P("notifications/tasks/status"),params:GS}),xo=pe.extend({method:P("tasks/get"),params:Oe.extend({taskId:h()})}),Po=fe.merge(rn),To=pe.extend({method:P("tasks/result"),params:Oe.extend({taskId:h()})}),oR=fe.loose(),zo=en.extend({method:P("tasks/list")}),Ro=tn.extend({tasks:D(rn)}),Io=pe.extend({method:P("tasks/cancel"),params:Oe.extend({taskId:h()})}),Zf=fe.merge(rn),Ff=w({uri:h(),mimeType:ne(h()),_meta:G(h(),re()).optional()}),Hf=Ff.extend({text:h()}),Yi=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wf=Ff.extend({blob:Yi}),on=$e(["user","assistant"]),pr=w({audience:D(on).optional(),priority:H().min(0).max(1).optional(),lastModified:Gr.datetime({offset:!0}).optional()}),Vf=w({...lr.shape,...Qr.shape,uri:h(),description:ne(h()),mimeType:ne(h()),size:ne(H()),annotations:pr.optional(),_meta:ne(Ee({}))}),YS=w({...lr.shape,...Qr.shape,uriTemplate:h(),description:ne(h()),mimeType:ne(h()),annotations:pr.optional(),_meta:ne(Ee({}))}),BS=en.extend({method:P("resources/list")}),XS=tn.extend({resources:D(Vf)}),QS=en.extend({method:P("resources/templates/list")}),ev=tn.extend({resourceTemplates:D(YS)}),Bi=Oe.extend({uri:h()}),tv=Bi,rv=pe.extend({method:P("resources/read"),params:tv}),nv=fe.extend({contents:D(X([Hf,Wf]))}),ov=De.extend({method:P("notifications/resources/list_changed"),params:Ne.optional()}),sv=Bi,iv=pe.extend({method:P("resources/subscribe"),params:sv}),av=Bi,cv=pe.extend({method:P("resources/unsubscribe"),params:av}),uv=Ne.extend({uri:h()}),lv=De.extend({method:P("notifications/resources/updated"),params:uv}),dv=w({name:h(),description:ne(h()),required:ne(le())}),pv=w({...lr.shape,...Qr.shape,description:ne(h()),arguments:ne(D(dv)),_meta:ne(Ee({}))}),fv=en.extend({method:P("prompts/list")}),mv=tn.extend({prompts:D(pv)}),hv=Oe.extend({name:h(),arguments:G(h(),h()).optional()}),gv=pe.extend({method:P("prompts/get"),params:hv}),Xi=w({type:P("text"),text:h(),annotations:pr.optional(),_meta:G(h(),re()).optional()}),Qi=w({type:P("image"),data:Yi,mimeType:h(),annotations:pr.optional(),_meta:G(h(),re()).optional()}),ea=w({type:P("audio"),data:Yi,mimeType:h(),annotations:pr.optional(),_meta:G(h(),re()).optional()}),_v=w({type:P("tool_use"),name:h(),id:h(),input:G(h(),re()),_meta:G(h(),re()).optional()}),yv=w({type:P("resource"),resource:X([Hf,Wf]),annotations:pr.optional(),_meta:G(h(),re()).optional()}),Sv=Vf.extend({type:P("resource_link")}),ta=X([Xi,Qi,ea,Sv,yv]),vv=w({role:on,content:ta}),bv=fe.extend({description:h().optional(),messages:D(vv)}),Ev=De.extend({method:P("notifications/prompts/list_changed"),params:Ne.optional()}),wv=w({title:h().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),kv=w({taskSupport:$e(["required","optional","forbidden"]).optional()}),Kf=w({...lr.shape,...Qr.shape,description:h().optional(),inputSchema:w({type:P("object"),properties:G(h(),ce).optional(),required:D(h()).optional()}).catchall(re()),outputSchema:w({type:P("object"),properties:G(h(),ce).optional(),required:D(h()).optional()}).catchall(re()).optional(),annotations:wv.optional(),execution:kv.optional(),_meta:G(h(),re()).optional()}),ra=en.extend({method:P("tools/list")}),$v=tn.extend({tools:D(Kf)}),Oo=fe.extend({content:D(ta).default([]),structuredContent:G(h(),re()).optional(),isError:le().optional()}),sR=Oo.or(fe.extend({toolResult:re()})),xv=Br.extend({name:h(),arguments:G(h(),re()).optional()}),sn=pe.extend({method:P("tools/call"),params:xv}),Pv=De.extend({method:P("notifications/tools/list_changed"),params:Ne.optional()}),iR=w({autoRefresh:le().default(!0),debounceMs:H().int().nonnegative().default(300)}),an=$e(["debug","info","notice","warning","error","critical","alert","emergency"]),Tv=Oe.extend({level:an}),na=pe.extend({method:P("logging/setLevel"),params:Tv}),zv=Ne.extend({level:an,logger:h().optional(),data:re()}),Rv=De.extend({method:P("notifications/message"),params:zv}),Iv=w({name:h().optional()}),Ov=w({hints:D(Iv).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Av=w({mode:$e(["auto","required","none"]).optional()}),Mv=w({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:D(ta).default([]),structuredContent:w({}).loose().optional(),isError:le().optional(),_meta:G(h(),re()).optional()}),Cv=Ui("type",[Xi,Qi,ea]),So=Ui("type",[Xi,Qi,ea,_v,Mv]),Nv=w({role:on,content:X([So,D(So)]),_meta:G(h(),re()).optional()}),Dv=Br.extend({messages:D(Nv),modelPreferences:Ov.optional(),systemPrompt:h().optional(),includeContext:$e(["none","thisServer","allServers"]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:D(h()).optional(),metadata:ce.optional(),tools:D(Kf).optional(),toolChoice:Av.optional()}),jv=pe.extend({method:P("sampling/createMessage"),params:Dv}),cn=fe.extend({model:h(),stopReason:ne($e(["endTurn","stopSequence","maxTokens"]).or(h())),role:on,content:Cv}),oa=fe.extend({model:h(),stopReason:ne($e(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:on,content:X([So,D(So)])}),Lv=w({type:P("boolean"),title:h().optional(),description:h().optional(),default:le().optional()}),Uv=w({type:P("string"),title:h().optional(),description:h().optional(),minLength:H().optional(),maxLength:H().optional(),format:$e(["email","uri","date","date-time"]).optional(),default:h().optional()}),qv=w({type:$e(["number","integer"]),title:h().optional(),description:h().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),Zv=w({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),default:h().optional()}),Fv=w({type:P("string"),title:h().optional(),description:h().optional(),oneOf:D(w({const:h(),title:h()})),default:h().optional()}),Hv=w({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),enumNames:D(h()).optional(),default:h().optional()}),Wv=X([Zv,Fv]),Vv=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:H().optional(),maxItems:H().optional(),items:w({type:P("string"),enum:D(h())}),default:D(h()).optional()}),Kv=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:H().optional(),maxItems:H().optional(),items:w({anyOf:D(w({const:h(),title:h()}))}),default:D(h()).optional()}),Jv=X([Vv,Kv]),Gv=X([Hv,Wv,Jv]),Yv=X([Gv,Lv,Uv,qv]),Bv=Br.extend({mode:P("form").optional(),message:h(),requestedSchema:w({type:P("object"),properties:G(h(),Yv),required:D(h()).optional()})}),Xv=Br.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),Qv=X([Bv,Xv]),eb=pe.extend({method:P("elicitation/create"),params:Qv}),tb=Ne.extend({elicitationId:h()}),rb=De.extend({method:P("notifications/elicitation/complete"),params:tb}),fr=fe.extend({action:$e(["accept","decline","cancel"]),content:qi(t=>t===null?void 0:t,G(h(),X([h(),H(),le(),D(h())])).optional())}),nb=w({type:P("ref/resource"),uri:h()});var ob=w({type:P("ref/prompt"),name:h()}),sb=Oe.extend({ref:X([ob,nb]),argument:w({name:h(),value:h()}),context:w({arguments:G(h(),h()).optional()}).optional()}),ib=pe.extend({method:P("completion/complete"),params:sb});var ab=fe.extend({completion:Ee({values:D(h()).max(100),total:ne(H().int()),hasMore:ne(le())})}),cb=w({uri:h().startsWith("file://"),name:h().optional(),_meta:G(h(),re()).optional()}),ub=pe.extend({method:P("roots/list"),params:Oe.optional()}),sa=fe.extend({roots:D(cb)}),lb=De.extend({method:P("notifications/roots/list_changed"),params:Ne.optional()}),aR=X([ko,Ji,ib,na,gv,fv,BS,QS,rv,iv,cv,sn,ra,xo,To,zo,Io]),cR=X([wo,$o,Gi,lb,nn]),uR=X([Eo,cn,oa,fr,sa,Po,Ro,dr]),lR=X([ko,jv,eb,ub,xo,To,zo,Io]),dR=X([wo,$o,Rv,lv,ov,Pv,Ev,nn,rb]),pR=X([Eo,HS,ab,bv,mv,XS,ev,nv,Oo,$v,Po,Ro,dr]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Zi(o.elicitations,r)}return new t(e,r,n)}},Zi=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Ot(t){return t==="completed"||t==="failed"||t==="cancelled"}var WR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ia(t){let r=go(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Bp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function aa(t,e){let r=Rt(t,e);if(!r.success)throw r.error;return r.data}var gb=6e4,Ao=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(wo,r=>{this._oncancel(r)}),this.setNotificationHandler($o,r=>{this._onprogress(r)}),this.setRequestHandler(ko,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(To,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new I(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(N.InvalidParams,`Task not found: ${s}`);if(!Ot(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ot(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[It]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(zo,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Io,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ot(o.status))throw new I(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Xr(s)||Lf(s)?this._onresponse(s):Wi(s)?this._onrequest(s,i):jf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[It]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Cf(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new I(N.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xr(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Xr(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Xr(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,dr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Ot(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch($){d($);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[It]:c}});let m=$=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String($)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let b=$ instanceof I?$:new I(N.RequestTimeout,String($));l(b)};this._responseHandlers.set(p,$=>{if(!n?.signal?.aborted){if($ instanceof Error)return l($);try{let b=Rt(r,$.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??gb,S=()=>m(I.fromError(N.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let $=b=>{let x=this._responseHandlers.get(p);x?x(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,$),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>{this._cleanupTimeout(p),l($)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Po,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ro,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Zf,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[It]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[It]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[It]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=ia(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=aa(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ia(e);this._notificationHandlers.set(n,o=>{let s=aa(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Wi(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=nn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ot(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ot(a.status))throw new I(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=nn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ot(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Jf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Gf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Jf(i)&&Jf(s)?r[o]={...i,...s}:r[o]=s}return r}var Cg=$t(Vc(),1),Ng=$t(Mg(),1);function ix(){let t=new Cg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ng.default)(t),t}var gs=class{constructor(e){this._ajv=e??ix()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var _s=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},cn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},fr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Dg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function jg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ys=class extends Ao{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(an.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(Gi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(na,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=an.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new _s(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Gf(this._capabilities,e)}setRequestHandler(e,r){let o=go(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(ur(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Rt(sn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(N.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Rt(dr,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new I(N.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=Rt(Oo,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(N.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){jg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Dg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Of.includes(r)?r:Fi,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"},Eo)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},oa,r):this.request({method:"sampling/createMessage",params:e},cn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},fr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},fr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},sa,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var eu=$t(require("node:process"),1);var Ss=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` -`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ax(r)}clear(){this._buffer=void 0}};function ax(t){return Uf.parse(JSON.parse(t))}function Lg(t){return JSON.stringify(t)+` -`}var vs=class{constructor(e=eu.default.stdin,r=eu.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ss,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Lg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var As=$t(require("path"),1),Or=require("fs");var Ug=require("node:child_process");function bs(t,e,r){return(0,Ug.spawn)(t,e??[],{windowsHide:!0,...r})}var ue={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function qt(t){return process.platform==="win32"?Math.round(t*ue.WINDOWS_MULTIPLIER):t}var ut=require("fs"),Ln=require("path"),tu=require("os");var wt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(qt(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,Ln.join)((0,tu.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Ln.join)((0,tu.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,ut.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,Ln.dirname)(e);(0,ut.existsSync)(c)||(0,ut.mkdirSync)(c,{recursive:!0}),(0,ut.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,ut.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{(0,ut.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var Es=null;function ws(){return Es!==null||(Es=wt.loadFromFile(Ou)),Es}var tr=require("fs");var iu=require("child_process");var dt=require("fs"),ou=$t(require("path"),1);var cx=["CLAUDECODE_","CLAUDE_CODE_"],ux=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),lx=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Un(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(lx.has(r)){e[r]=n;continue}ux.has(r)||cx.some(o=>r.startsWith(o))||(e[r]=n)}return e}var dx=5e3,px=1e3,fx=Me.supervisorRegistry();function lt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function ks(t,e){let r=Date.now()+e;for(;Date.now()!lt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var mx=5e3,qg=new Map;function hx(t){let e=(0,iu.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Un(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function gx(t){let e=qg.get(t);if(e&&Date.now()-e.capturedAtMs0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function au(t){if(!t||!lt(t.pid))return!1;if(!t.startToken)return!0;let e=Zg(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var su=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=fx){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,dt.mkdirSync)(ou.default.dirname(this.registryPath),{recursive:!0}),!(0,dt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,dt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&nu()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)lt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;ni.pid)});let o=r.filter(i=>lt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await ks(o,dx);let s=o.filter(i=>lt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+px;for(;Date.now()lt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&nu();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,dt.mkdirSync)(ou.default.dirname(this.registryPath),{recursive:!0}),(0,dt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},ru=null;function $s(){return ru||(ru=new su),ru}var _x=[];function nu(){let t=_x.shift();t&&t()}var Hg=require("child_process"),Rr=require("fs"),Wg=require("util");var yx=(0,Wg.promisify)(Hg.execFile),Sx=Me.workerPid();async function Vg(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Sx,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!lt(i.pid)){t.registry.unregister(i.id);continue}try{await Fg(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await ks(o,5e3);let s=o.filter(i=>lt(i.pid));for(let i of s)try{await Fg(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await ks(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);Kg(r,e),t.registry.pruneDeadEntries()}function Kg(t,e,r=!1){if(!(0,Rr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Rr.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){y.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let o=e!==null&&n===e,s=n===null||!lt(n);if(!o&&!(r&&s)){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Rr.rmSync)(t,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):y.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}async function Fg(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await yx("taskkill",o,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}var Jg=3e4,Ir=null;function vx(){let e=$s().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Gg(){Ir===null&&(Ir=setInterval(vx,Jg),Ir.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:Jg}))}function Yg(){Ir!==null&&(clearInterval(Ir),Ir=null,y.debug("SYSTEM","Health checker stopped"))}var bx=Me.workerPid(),cu=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),xs({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Gg()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Yg(),this.stopPromise=Vg({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Ex=new cu($s());function uu(){return Ex}function xs(t={}){let e=t.pidFilePath??bx;if(!(0,tr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,tr.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,tr.rmSync)(e,{force:!0}),"invalid"}return au(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,tr.rmSync)(e,{force:!0}),"stale")}var rr=$t(require("path"),1),Qg=require("os"),Ze=require("fs"),Ps=require("child_process");var bN=Me.dataDir(),Bg=Me.workerPid();function Xg(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function wx(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Ps.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var lu;function e_(t={}){let e=Object.keys(t).length===0;if(e&&lu!==void 0)return lu;let r=kx(t);return e&&r!==null&&(lu=r),r}function kx(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Xg(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,Qg.homedir)(),s=t.pathExists??Ze.existsSync,i=t.lookupInPath??wx,a=e==="win32"?[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun.exe"),rr.default.join(o,".bun","bin","bun"),n.USERPROFILE?rr.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(Xg(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function Zt(t){return process.platform==="win32"?Math.round(t*2):t}function t_(t,e,r={}){uu().assertCanSpawn("worker daemon");let n=Un({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=e_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=`Start-Process -FilePath '${o.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Ps.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){let f=p instanceof Error?p:new Error(String(p));y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},f);return}}let s="/usr/bin/setsid",i=(0,Ze.existsSync)(s),u=bs(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function r_(){try{if(!(0,Ze.existsSync)(Bg))return;let t=new Date;(0,Ze.utimesSync)(Bg,t,t)}catch{}}function n_(){return xs({logAlive:!1})}var o_=$t(require("net"),1);async function $x(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function s_(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=o_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function i_(t,e,r,n){let o=Date.now();for(;Date.now()-osetTimeout(s,500))}return!1}function qn(t,e=3e4){return i_(t,"/api/health",e,"Service not ready yet, will retry")}function Zn(t,e=3e4){return i_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Ts=require("path"),Fe=require("fs");var xx=6e4;function a_(){return(0,Ts.join)(Yn(),"spawn.lock")}function du(){let t=a_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Fe.mkdirSync)((0,Ts.dirname)(t),{recursive:!0}),(0,Fe.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return y.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:s},o),!0;if(r>0)return!1;let i;try{i=(0,Fe.statSync)(t).mtimeMs}catch{continue}if(Date.now()-i<=xx)return!1;let a;try{a=(0,Fe.statSync)(t).mtimeMs}catch{continue}if(a!==i)return!1;try{(0,Fe.unlinkSync)(t)}catch{return!1}}return!1}function pu(){let t=a_();try{if(JSON.parse((0,Fe.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,Fe.unlinkSync)(t)}catch{}}function u_(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var XN=u_("CLAUDE_MEM_HEALTH_TIMEOUT_MS",qt(ue.HEALTH_CHECK),{min:500,max:3e5}),QN=u_("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",qt(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),Px={min:500,max:3e5};async function fu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var zs=null,Rs=null,Is=null,Os=null;function Tx(){return As.default.join(wt.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function mu(){return Is!==null||(Is=wt.loadFromFile(Tx())),Is}function c_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function zx(t,e,r){let n=process.env[t];if(n!==void 0){let i=c_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=mu()[t],s=c_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function hu(){if(zs!==null)return zs;let t=mu();return zs=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),zs}function Rx(){return Rs!==null||(Rs=mu().CLAUDE_MEM_WORKER_HOST),Rs}function Ix(){return Os!==null||(Os=zx("CLAUDE_MEM_API_TIMEOUT_MS",qt(ue.API_REQUEST),Px)),Os}function Ox(t){return`http://${Rx()}:${hu()}${t}`}function Ms(t,e={}){let r=e.method??"GET",n=e.timeoutMs??Ix(),o=Ox(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?fu(o,s,n):fetch(o,s)}function l_(){let t=[As.default.join(Vs,"plugin","scripts","worker-service.cjs"),As.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Or.existsSync)(e))return e;return null}var gu=$t(require("path"),1),He=require("fs");var Ax=120*1e3;function _u(){return gu.default.join(wt.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function Mx(){if(process.platform!=="win32")return!1;let t=_u();if(!(0,He.existsSync)(t))return!1;try{let e=(0,He.statSync)(t).mtimeMs;return Date.now()-e1&&t.reused==="ref"){s(i);continue}}}function Ui(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(m.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let p=a._zod.parent;if(p&&p!==d){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Xr(e,"input",t.processors),output:Xr(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ke(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ke(n.element,r);if(n.type==="set")return ke(n.valueType,r);if(n.type==="lazy")return ke(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ke(n.innerType,r);if(n.type==="intersection")return ke(n.left,r)||ke(n.right,r);if(n.type==="record"||n.type==="map")return ke(n.keyType,r)||ke(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ke(n.in,r)||ke(n.out,r);if(n.type==="object"){for(let o in n.shape)if(ke(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ke(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ke(o,r))return!0;return!!(n.rest&&ke(n.rest,r))}return!1}var jp=(t,e={})=>r=>{let n=ji({...r,processors:e});return se(t,n),Li(n,t),Ui(n,t)},Xr=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ji({...o??{},target:s,io:e,processors:r});return se(t,i),Li(i,t),Ui(i,t)};var By={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Lp=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=By[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Up=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},qp=(t,e,r,n)=>{r.type="boolean"};var Zp=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Fp=(t,e,r,n)=>{r.not={}};var Hp=(t,e,r,n)=>{};var Wp=(t,e,r,n)=>{let o=t._zod.def,s=Zr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Vp=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var Kp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Gp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Jp=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=se(s.element,e,{...n,path:[...n.path,"items"]})},Yp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=se(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=se(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Bp=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>se(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Xp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=se(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var Qp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=se(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=se(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=se(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},ef=(t,e,r,n)=>{let o=t._zod.def,s=se(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},tf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},rf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},nf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},of=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},sf=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;se(i,e,n);let a=e.seen.get(t);a.ref=i},af=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var qi=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function lr(t){return!!t._zod}function Rt(t,e){return lr(t)?Kr(t,e):t.safeParse(e)}function xo(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function cf(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var en={};Lu(en,{ZodISODate:()=>lf,ZodISODateTime:()=>uf,ZodISODuration:()=>pf,ZodISOTime:()=>df,date:()=>Fi,datetime:()=>Zi,duration:()=>Wi,time:()=>Hi});var uf=g("ZodISODateTime",(t,e)=>{_d.init(t,e),te.init(t,e)});function Zi(t){return kp(uf,t)}var lf=g("ZodISODate",(t,e)=>{yd.init(t,e),te.init(t,e)});function Fi(t){return xp(lf,t)}var df=g("ZodISOTime",(t,e)=>{Sd.init(t,e),te.init(t,e)});function Hi(t){return $p(df,t)}var pf=g("ZodISODuration",(t,e)=>{vd.init(t,e),te.init(t,e)});function Wi(t){return Pp(pf,t)}var iS=(t,e)=>{lo.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>el(t,r)},flatten:{value:r=>Qu(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ir,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ir,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Me=g("ZodError",iS,{Parent:Error});var ff=po(Me),mf=fo(Me),hf=Vr(Me),gf=Gr(Me),_f=tl(Me),yf=rl(Me),Sf=nl(Me),vf=ol(Me),bf=sl(Me),Ef=il(Me),wf=al(Me),kf=cl(Me);var xf=new WeakMap;function tn(t,e,r){let n=Object.getPrototypeOf(t),o=xf.get(n);if(o||(o=new Set,xf.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=g("ZodType",(t,e)=>(J.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Xr(t,"input"),output:Xr(t,"output")}}),t.toJSONSchema=jp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>ff(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>hf(t,r,n),t.parseAsync=async(r,n)=>mf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>gf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>_f(t,r,n),t.decode=(r,n)=>yf(t,r,n),t.encodeAsync=async(r,n)=>Sf(t,r,n),t.decodeAsync=async(r,n)=>vf(t,r,n),t.safeEncode=(r,n)=>bf(t,r,n),t.safeDecode=(r,n)=>Ef(t,r,n),t.safeEncodeAsync=async(r,n)=>wf(t,r,n),t.safeDecodeAsync=async(r,n)=>kf(t,r,n),tn(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Je(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(YS(r,n))},superRefine(r,n){return this.check(BS(r,n))},overwrite(r){return this.check(zt(r))},optional(){return ne(this)},exactOptional(){return jS(this)},nullable(){return zf(this)},nullish(){return ne(zf(this))},nonoptional(r){return HS(this,r)},array(){return D(this)},or(r){return B([this,r])},and(r){return Po(this,r)},transform(r){return Rf(this,Nf(r))},default(r){return qS(this,r)},prefault(r){return FS(this,r)},catch(r){return VS(this,r)},pipe(r){return Rf(this,r)},readonly(){return JS(this)},describe(r){let n=this.clone();return Ht.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ht.get(this);let n=this.clone();return Ht.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ht.get(t)?.description},configurable:!0}),t)),If=g("_ZodString",(t,e)=>{So.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Lp(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,tn(t,"_ZodString",{regex(...n){return this.check(Pi(...n))},includes(...n){return this.check(Ri(...n))},startsWith(...n){return this.check(Ii(...n))},endsWith(...n){return this.check(Ai(...n))},min(...n){return this.check(ur(...n))},max(...n){return this.check(wo(...n))},length(...n){return this.check(ko(...n))},nonempty(...n){return this.check(ur(1,...n))},lowercase(n){return this.check(Ti(n))},uppercase(n){return this.check(zi(n))},trim(){return this.check(Mi())},normalize(...n){return this.check(Oi(...n))},toLowerCase(){return this.check(Ci())},toUpperCase(){return this.check(Ni())},slugify(){return this.check(Di())}})}),cS=g("ZodString",(t,e)=>{So.init(t,e),If.init(t,e),t.email=r=>t.check(np(uS,r)),t.url=r=>t.check(cp(lS,r)),t.jwt=r=>t.check(wp(xS,r)),t.emoji=r=>t.check(up(dS,r)),t.guid=r=>t.check($i($f,r)),t.uuid=r=>t.check(op($o,r)),t.uuidv4=r=>t.check(sp($o,r)),t.uuidv6=r=>t.check(ip($o,r)),t.uuidv7=r=>t.check(ap($o,r)),t.nanoid=r=>t.check(lp(pS,r)),t.guid=r=>t.check($i($f,r)),t.cuid=r=>t.check(dp(fS,r)),t.cuid2=r=>t.check(pp(mS,r)),t.ulid=r=>t.check(fp(hS,r)),t.base64=r=>t.check(vp(ES,r)),t.base64url=r=>t.check(bp(wS,r)),t.xid=r=>t.check(mp(gS,r)),t.ksuid=r=>t.check(hp(_S,r)),t.ipv4=r=>t.check(gp(yS,r)),t.ipv6=r=>t.check(_p(SS,r)),t.cidrv4=r=>t.check(yp(vS,r)),t.cidrv6=r=>t.check(Sp(bS,r)),t.e164=r=>t.check(Ep(kS,r)),t.datetime=r=>t.check(Zi(r)),t.date=r=>t.check(Fi(r)),t.time=r=>t.check(Hi(r)),t.duration=r=>t.check(Wi(r))});function h(t){return rp(cS,t)}var te=g("ZodStringFormat",(t,e)=>{Y.init(t,e),If.init(t,e)}),uS=g("ZodEmail",(t,e)=>{cd.init(t,e),te.init(t,e)});var $f=g("ZodGUID",(t,e)=>{id.init(t,e),te.init(t,e)});var $o=g("ZodUUID",(t,e)=>{ad.init(t,e),te.init(t,e)});var lS=g("ZodURL",(t,e)=>{ud.init(t,e),te.init(t,e)});var dS=g("ZodEmoji",(t,e)=>{ld.init(t,e),te.init(t,e)});var pS=g("ZodNanoID",(t,e)=>{dd.init(t,e),te.init(t,e)});var fS=g("ZodCUID",(t,e)=>{pd.init(t,e),te.init(t,e)});var mS=g("ZodCUID2",(t,e)=>{fd.init(t,e),te.init(t,e)});var hS=g("ZodULID",(t,e)=>{md.init(t,e),te.init(t,e)});var gS=g("ZodXID",(t,e)=>{hd.init(t,e),te.init(t,e)});var _S=g("ZodKSUID",(t,e)=>{gd.init(t,e),te.init(t,e)});var yS=g("ZodIPv4",(t,e)=>{bd.init(t,e),te.init(t,e)});var SS=g("ZodIPv6",(t,e)=>{Ed.init(t,e),te.init(t,e)});var vS=g("ZodCIDRv4",(t,e)=>{wd.init(t,e),te.init(t,e)});var bS=g("ZodCIDRv6",(t,e)=>{kd.init(t,e),te.init(t,e)});var ES=g("ZodBase64",(t,e)=>{$d.init(t,e),te.init(t,e)});var wS=g("ZodBase64URL",(t,e)=>{Pd.init(t,e),te.init(t,e)});var kS=g("ZodE164",(t,e)=>{Td.init(t,e),te.init(t,e)});var xS=g("ZodJWT",(t,e)=>{zd.init(t,e),te.init(t,e)});var Af=g("ZodNumber",(t,e)=>{bi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Up(t,n,o,s),tn(t,"ZodNumber",{gt(n,o){return this.check(bo(n,o))},gte(n,o){return this.check(Br(n,o))},min(n,o){return this.check(Br(n,o))},lt(n,o){return this.check(vo(n,o))},lte(n,o){return this.check(Yr(n,o))},max(n,o){return this.check(Yr(n,o))},int(n){return this.check(Pf(n))},safe(n){return this.check(Pf(n))},positive(n){return this.check(bo(0,n))},nonnegative(n){return this.check(Br(0,n))},negative(n){return this.check(vo(0,n))},nonpositive(n){return this.check(Yr(0,n))},multipleOf(n,o){return this.check(Eo(n,o))},step(n,o){return this.check(Eo(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function W(t){return Tp(Af,t)}var $S=g("ZodNumberFormat",(t,e)=>{Rd.init(t,e),Af.init(t,e)});function Pf(t){return zp($S,t)}var PS=g("ZodBoolean",(t,e)=>{Id.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qp(t,r,n,o)});function de(t){return Rp(PS,t)}var TS=g("ZodNull",(t,e)=>{Ad.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zp(t,r,n,o)});function Of(t){return Ip(TS,t)}var zS=g("ZodUnknown",(t,e)=>{Od.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hp(t,r,n,o)});function re(){return Ap(zS)}var RS=g("ZodNever",(t,e)=>{Md.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fp(t,r,n,o)});function IS(t){return Op(RS,t)}var AS=g("ZodArray",(t,e)=>{Cd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o),t.element=e.element,tn(t,"ZodArray",{min(r,n){return this.check(ur(r,n))},nonempty(r){return this.check(ur(1,r))},max(r,n){return this.check(wo(r,n))},length(r,n){return this.check(ko(r,n))},unwrap(){return this.element}})});function D(t,e){return Mp(AS,t,e)}var Mf=g("ZodObject",(t,e)=>{jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),tn(t,"ZodObject",{keyof(){return Te(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:re()})},loose(){return this.clone({...this._zod.def,catchall:re()})},strict(){return this.clone({...this._zod.def,catchall:IS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(Df,this,r[0])},required(...r){return U.required(jf,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new Mf(r)}function xe(t,e){return new Mf({type:"object",shape:t,catchall:re(),...U.normalizeParams(e)})}var Cf=g("ZodUnion",(t,e)=>{Ei.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bp(t,r,n,o),t.options=e.options});function B(t,e){return new Cf({type:"union",options:t,...U.normalizeParams(e)})}var OS=g("ZodDiscriminatedUnion",(t,e)=>{Cf.init(t,e),Ld.init(t,e)});function Ki(t,e,r){return new OS({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var MS=g("ZodIntersection",(t,e)=>{Ud.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xp(t,r,n,o)});function Po(t,e){return new MS({type:"intersection",left:t,right:e})}var Tf=g("ZodRecord",(t,e)=>{qd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qp(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function G(t,e,r){return!e||!e._zod?new Tf({type:"record",keyType:h(),valueType:t,...U.normalizeParams(e)}):new Tf({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var Vi=g("ZodEnum",(t,e)=>{Zd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Wp(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Vi({...e,checks:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Vi({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Te(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Vi({type:"enum",entries:r,...U.normalizeParams(e)})}var CS=g("ZodLiteral",(t,e)=>{Fd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function P(t,e){return new CS({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var NS=g("ZodTransform",(t,e)=>{Hd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Nf(t){return new NS({type:"transform",transform:t})}var Df=g("ZodOptional",(t,e)=>{wi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ne(t){return new Df({type:"optional",innerType:t})}var DS=g("ZodExactOptional",(t,e)=>{Wd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function jS(t){return new DS({type:"optional",innerType:t})}var LS=g("ZodNullable",(t,e)=>{Vd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function zf(t){return new LS({type:"nullable",innerType:t})}var US=g("ZodDefault",(t,e)=>{Kd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function qS(t,e){return new US({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var ZS=g("ZodPrefault",(t,e)=>{Gd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function FS(t,e){return new ZS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var jf=g("ZodNonOptional",(t,e)=>{Jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function HS(t,e){return new jf({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var WS=g("ZodCatch",(t,e)=>{Yd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>of(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function VS(t,e){return new WS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Lf=g("ZodPipe",(t,e)=>{ki.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sf(t,r,n,o),t.in=e.in,t.out=e.out});function Rf(t,e){return new Lf({type:"pipe",in:t,out:e})}var KS=g("ZodPreprocess",(t,e)=>{Lf.init(t,e),Bd.init(t,e)}),GS=g("ZodReadonly",(t,e)=>{Xd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>af(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function JS(t){return new GS({type:"readonly",innerType:t})}var Uf=g("ZodCustom",(t,e)=>{Qd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o)});function qf(t,e){return Cp(Uf,t??(()=>!0),e)}function YS(t,e={}){return Np(Uf,t,e)}function BS(t,e){return Dp(t,e)}function Gi(t,e){return new KS({type:"pipe",in:Nf(t),out:e})}Oe(ep());var Yi="2025-11-25";var Zf=[Yi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],It="io.modelcontextprotocol/related-task",zo="2.0",le=qf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ff=B([h(),W().int()]),Hf=h(),wR=xe({ttl:W().optional(),pollInterval:W().optional()}),XS=k({ttl:W().optional()}),QS=k({taskId:h()}),Bi=xe({progressToken:Ff.optional(),[It]:QS.optional()}),Ce=k({_meta:Bi.optional()}),rn=Ce.extend({task:XS.optional()}),Wf=t=>rn.safeParse(t).success,me=k({method:h(),params:Ce.loose().optional()}),Le=k({_meta:Bi.optional()}),Ue=k({method:h(),params:Le.loose().optional()}),he=xe({_meta:Bi.optional()}),Ro=B([h(),W().int()]),Vf=k({jsonrpc:P(zo),id:Ro,...me.shape}).strict(),Xi=t=>Vf.safeParse(t).success,Kf=k({jsonrpc:P(zo),...Ue.shape}).strict(),Gf=t=>Kf.safeParse(t).success,Qi=k({jsonrpc:P(zo),id:Ro,result:he}).strict(),nn=t=>Qi.safeParse(t).success;var N;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));var ea=k({jsonrpc:P(zo),id:Ro.optional(),error:k({code:W().int(),message:h(),data:re().optional()})}).strict();var Jf=t=>ea.safeParse(t).success;var Yf=B([Vf,Kf,Qi,ea]),kR=B([Qi,ea]),Io=he.strict(),ev=Le.extend({requestId:Ro.optional(),reason:h().optional()}),Ao=Ue.extend({method:P("notifications/cancelled"),params:ev}),tv=k({src:h(),mimeType:h().optional(),sizes:D(h()).optional(),theme:Te(["light","dark"]).optional()}),on=k({icons:D(tv).optional()}),dr=k({name:h(),title:h().optional()}),Bf=dr.extend({...dr.shape,...on.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),rv=Po(k({applyDefaults:de().optional()}),G(h(),re())),nv=Gi(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Po(k({form:rv.optional(),url:le.optional()}),G(h(),re()).optional())),ov=xe({list:le.optional(),cancel:le.optional(),requests:xe({sampling:xe({createMessage:le.optional()}).optional(),elicitation:xe({create:le.optional()}).optional()}).optional()}),sv=xe({list:le.optional(),cancel:le.optional(),requests:xe({tools:xe({call:le.optional()}).optional()}).optional()}),iv=k({experimental:G(h(),le).optional(),sampling:k({context:le.optional(),tools:le.optional()}).optional(),elicitation:nv.optional(),roots:k({listChanged:de().optional()}).optional(),tasks:ov.optional(),extensions:G(h(),le).optional()}),av=Ce.extend({protocolVersion:h(),capabilities:iv,clientInfo:Bf}),ta=me.extend({method:P("initialize"),params:av});var cv=k({experimental:G(h(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:k({listChanged:de().optional()}).optional(),resources:k({subscribe:de().optional(),listChanged:de().optional()}).optional(),tools:k({listChanged:de().optional()}).optional(),tasks:sv.optional(),extensions:G(h(),le).optional()}),uv=he.extend({protocolVersion:h(),capabilities:cv,serverInfo:Bf,instructions:h().optional()}),ra=Ue.extend({method:P("notifications/initialized"),params:Le.optional()});var Oo=me.extend({method:P("ping"),params:Ce.optional()}),lv=k({progress:W(),total:ne(W()),message:ne(h())}),dv=k({...Le.shape,...lv.shape,progressToken:Ff}),Mo=Ue.extend({method:P("notifications/progress"),params:dv}),pv=Ce.extend({cursor:Hf.optional()}),sn=me.extend({params:pv.optional()}),an=he.extend({nextCursor:Hf.optional()}),fv=Te(["working","input_required","completed","failed","cancelled"]),cn=k({taskId:h(),status:fv,ttl:B([W(),Of()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ne(W()),statusMessage:ne(h())}),pr=he.extend({task:cn}),mv=Le.merge(cn),un=Ue.extend({method:P("notifications/tasks/status"),params:mv}),Co=me.extend({method:P("tasks/get"),params:Ce.extend({taskId:h()})}),No=he.merge(cn),Do=me.extend({method:P("tasks/result"),params:Ce.extend({taskId:h()})}),xR=he.loose(),jo=sn.extend({method:P("tasks/list")}),Lo=an.extend({tasks:D(cn)}),Uo=me.extend({method:P("tasks/cancel"),params:Ce.extend({taskId:h()})}),Xf=he.merge(cn),Qf=k({uri:h(),mimeType:ne(h()),_meta:G(h(),re()).optional()}),em=Qf.extend({text:h()}),na=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),tm=Qf.extend({blob:na}),ln=Te(["user","assistant"]),fr=k({audience:D(ln).optional(),priority:W().min(0).max(1).optional(),lastModified:en.datetime({offset:!0}).optional()}),rm=k({...dr.shape,...on.shape,uri:h(),description:ne(h()),mimeType:ne(h()),size:ne(W()),annotations:fr.optional(),_meta:ne(xe({}))}),hv=k({...dr.shape,...on.shape,uriTemplate:h(),description:ne(h()),mimeType:ne(h()),annotations:fr.optional(),_meta:ne(xe({}))}),gv=sn.extend({method:P("resources/list")}),_v=an.extend({resources:D(rm)}),yv=sn.extend({method:P("resources/templates/list")}),Sv=an.extend({resourceTemplates:D(hv)}),oa=Ce.extend({uri:h()}),vv=oa,bv=me.extend({method:P("resources/read"),params:vv}),Ev=he.extend({contents:D(B([em,tm]))}),wv=Ue.extend({method:P("notifications/resources/list_changed"),params:Le.optional()}),kv=oa,xv=me.extend({method:P("resources/subscribe"),params:kv}),$v=oa,Pv=me.extend({method:P("resources/unsubscribe"),params:$v}),Tv=Le.extend({uri:h()}),zv=Ue.extend({method:P("notifications/resources/updated"),params:Tv}),Rv=k({name:h(),description:ne(h()),required:ne(de())}),Iv=k({...dr.shape,...on.shape,description:ne(h()),arguments:ne(D(Rv)),_meta:ne(xe({}))}),Av=sn.extend({method:P("prompts/list")}),Ov=an.extend({prompts:D(Iv)}),Mv=Ce.extend({name:h(),arguments:G(h(),h()).optional()}),Cv=me.extend({method:P("prompts/get"),params:Mv}),sa=k({type:P("text"),text:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),ia=k({type:P("image"),data:na,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),aa=k({type:P("audio"),data:na,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),Nv=k({type:P("tool_use"),name:h(),id:h(),input:G(h(),re()),_meta:G(h(),re()).optional()}),Dv=k({type:P("resource"),resource:B([em,tm]),annotations:fr.optional(),_meta:G(h(),re()).optional()}),jv=rm.extend({type:P("resource_link")}),ca=B([sa,ia,aa,jv,Dv]),Lv=k({role:ln,content:ca}),Uv=he.extend({description:h().optional(),messages:D(Lv)}),qv=Ue.extend({method:P("notifications/prompts/list_changed"),params:Le.optional()}),Zv=k({title:h().optional(),readOnlyHint:de().optional(),destructiveHint:de().optional(),idempotentHint:de().optional(),openWorldHint:de().optional()}),Fv=k({taskSupport:Te(["required","optional","forbidden"]).optional()}),nm=k({...dr.shape,...on.shape,description:h().optional(),inputSchema:k({type:P("object"),properties:G(h(),le).optional(),required:D(h()).optional()}).catchall(re()),outputSchema:k({type:P("object"),properties:G(h(),le).optional(),required:D(h()).optional()}).catchall(re()).optional(),annotations:Zv.optional(),execution:Fv.optional(),_meta:G(h(),re()).optional()}),ua=sn.extend({method:P("tools/list")}),Hv=an.extend({tools:D(nm)}),qo=he.extend({content:D(ca).default([]),structuredContent:G(h(),re()).optional(),isError:de().optional()}),$R=qo.or(he.extend({toolResult:re()})),Wv=rn.extend({name:h(),arguments:G(h(),re()).optional()}),dn=me.extend({method:P("tools/call"),params:Wv}),Vv=Ue.extend({method:P("notifications/tools/list_changed"),params:Le.optional()}),PR=k({autoRefresh:de().default(!0),debounceMs:W().int().nonnegative().default(300)}),pn=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),Kv=Ce.extend({level:pn}),la=me.extend({method:P("logging/setLevel"),params:Kv}),Gv=Le.extend({level:pn,logger:h().optional(),data:re()}),Jv=Ue.extend({method:P("notifications/message"),params:Gv}),Yv=k({name:h().optional()}),Bv=k({hints:D(Yv).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),Xv=k({mode:Te(["auto","required","none"]).optional()}),Qv=k({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:D(ca).default([]),structuredContent:k({}).loose().optional(),isError:de().optional(),_meta:G(h(),re()).optional()}),eb=Ki("type",[sa,ia,aa]),To=Ki("type",[sa,ia,aa,Nv,Qv]),tb=k({role:ln,content:B([To,D(To)]),_meta:G(h(),re()).optional()}),rb=rn.extend({messages:D(tb),modelPreferences:Bv.optional(),systemPrompt:h().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:D(h()).optional(),metadata:le.optional(),tools:D(nm).optional(),toolChoice:Xv.optional()}),nb=me.extend({method:P("sampling/createMessage"),params:rb}),fn=he.extend({model:h(),stopReason:ne(Te(["endTurn","stopSequence","maxTokens"]).or(h())),role:ln,content:eb}),da=he.extend({model:h(),stopReason:ne(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:ln,content:B([To,D(To)])}),ob=k({type:P("boolean"),title:h().optional(),description:h().optional(),default:de().optional()}),sb=k({type:P("string"),title:h().optional(),description:h().optional(),minLength:W().optional(),maxLength:W().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:h().optional()}),ib=k({type:Te(["number","integer"]),title:h().optional(),description:h().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),ab=k({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),default:h().optional()}),cb=k({type:P("string"),title:h().optional(),description:h().optional(),oneOf:D(k({const:h(),title:h()})),default:h().optional()}),ub=k({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),enumNames:D(h()).optional(),default:h().optional()}),lb=B([ab,cb]),db=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({type:P("string"),enum:D(h())}),default:D(h()).optional()}),pb=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({anyOf:D(k({const:h(),title:h()}))}),default:D(h()).optional()}),fb=B([db,pb]),mb=B([ub,lb,fb]),hb=B([mb,ob,sb,ib]),gb=rn.extend({mode:P("form").optional(),message:h(),requestedSchema:k({type:P("object"),properties:G(h(),hb),required:D(h()).optional()})}),_b=rn.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),yb=B([gb,_b]),Sb=me.extend({method:P("elicitation/create"),params:yb}),vb=Le.extend({elicitationId:h()}),bb=Ue.extend({method:P("notifications/elicitation/complete"),params:vb}),mr=he.extend({action:Te(["accept","decline","cancel"]),content:Gi(t=>t===null?void 0:t,G(h(),B([h(),W(),de(),D(h())])).optional())}),Eb=k({type:P("ref/resource"),uri:h()});var wb=k({type:P("ref/prompt"),name:h()}),kb=Ce.extend({ref:B([wb,Eb]),argument:k({name:h(),value:h()}),context:k({arguments:G(h(),h()).optional()}).optional()}),xb=me.extend({method:P("completion/complete"),params:kb});var $b=he.extend({completion:xe({values:D(h()).max(100),total:ne(W().int()),hasMore:ne(de())})}),Pb=k({uri:h().startsWith("file://"),name:h().optional(),_meta:G(h(),re()).optional()}),Tb=me.extend({method:P("roots/list"),params:Ce.optional()}),pa=he.extend({roots:D(Pb)}),zb=Ue.extend({method:P("notifications/roots/list_changed"),params:Le.optional()}),TR=B([Oo,ta,xb,la,Cv,Av,gv,yv,bv,xv,Pv,dn,ua,Co,Do,jo,Uo]),zR=B([Ao,Mo,ra,zb,un]),RR=B([Io,fn,da,mr,pa,No,Lo,pr]),IR=B([Oo,nb,Sb,Tb,Co,Do,jo,Uo]),AR=B([Ao,Mo,Jv,zv,wv,Vv,qv,un,bb]),OR=B([Io,uv,$b,Uv,Ov,_v,Sv,Ev,qo,Hv,No,Lo,pr]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ji(o.elicitations,r)}return new t(e,r,n)}},Ji=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function At(t){return t==="completed"||t==="failed"||t==="cancelled"}var pI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function fa(t){let r=xo(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ma(t,e){let r=Rt(t,e);if(!r.success)throw r.error;return r.data}var Cb=6e4,Zo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ao,r=>{this._oncancel(r)}),this.setNotificationHandler(Mo,r=>{this._onprogress(r)}),this.setRequestHandler(Oo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Co,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Do,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new I(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(N.InvalidParams,`Task not found: ${s}`);if(!At(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(At(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[It]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(jo,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Uo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(At(o.status))throw new I(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),nn(s)||Jf(s)?this._onresponse(s):Xi(s)?this._onrequest(s,i):Gf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[It]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Wf(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new I(N.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),nn(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(nn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),nn(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,pr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},At(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=E=>{l(E)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(E){d(E);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[It]:c}});let m=E=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(E)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let v=E instanceof I?E:new I(N.RequestTimeout,String(E));l(v)};this._responseHandlers.set(p,E=>{if(!n?.signal?.aborted){if(E instanceof Error)return l(E);try{let v=Rt(r,E.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let _=n?.timeout??Cb,S=()=>m(I.fromError(N.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let E=v=>{let $=this._responseHandlers.get(p);$?$(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,E),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(E=>{this._cleanupTimeout(p),l(E)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},No,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Lo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Xf,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[It]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[It]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[It]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=fa(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ma(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=fa(e);this._notificationHandlers.set(n,o=>{let s=ma(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Xi(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=un.parse({method:"notifications/tasks/status",params:a});await this.notification(c),At(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(At(a.status))throw new I(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=un.parse({method:"notifications/tasks/status",params:c});await this.notification(u),At(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function om(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function sm(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];om(i)&&om(s)?r[o]={...i,...s}:r[o]=s}return r}var Wg=xt(Qc(),1),Vg=xt(Hg(),1);function $$(){let t=new Wg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Vg.default)(t),t}var ks=class{constructor(e){this._ajv=e??$$()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var xs=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},fn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},mr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Kg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Gg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var $s=class extends Zo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(pn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(ra,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(la,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=pn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=sm(this._capabilities,e)}setRequestHandler(e,r){let o=xo(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(lr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Rt(dn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(N.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Rt(pr,p);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new I(N.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}let f=Rt(qo,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(N.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Gg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Kg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Zf.includes(r)?r:Yi,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"},Io)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},da,r):this.request({method:"sampling/createMessage",params:e},fn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},mr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},mr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},pa,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var au=xt(require("node:process"),1);var Ps=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` +`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),P$(r)}clear(){this._buffer=void 0}};function P$(t){return Yf.parse(JSON.parse(t))}function Jg(t){return JSON.stringify(t)+` +`}var Ts=class{constructor(e=au.default.stdin,r=au.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ps,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Jg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var qs=xt(require("path"),1),Mr=require("fs");var Yg=require("node:child_process");function zs(t,e,r){return(0,Yg.spawn)(t,e??[],{windowsHide:!0,...r})}var ue={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function bt(t){return process.platform==="win32"?Math.round(t*ue.WINDOWS_MULTIPLIER):t}var ut=require("fs"),Hn=require("path"),cu=require("os");var Et=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(bt(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Hn.join)((0,cu.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Hn.join)((0,cu.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,ut.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,Hn.dirname)(e);(0,ut.existsSync)(c)||(0,ut.mkdirSync)(c,{recursive:!0}),(0,ut.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,ut.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{(0,ut.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var Rs=null;function Is(){return Rs!==null||(Rs=Et.loadFromFile(qu)),Rs}var tr=require("fs");var fu=require("child_process");var lt=require("fs"),du=xt(require("path"),1);var T$=["CLAUDECODE_","CLAUDE_CODE_"],z$=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),R$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Wn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(R$.has(r)){e[r]=n;continue}z$.has(r)||T$.some(o=>r.startsWith(o))||(e[r]=n)}return e}var I$=5e3,A$=1e3,O$=De.supervisorRegistry();function wt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function As(t,e){let r=Date.now()+e;for(;Date.now()!wt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var M$=5e3,Bg=new Map;function C$(t){let e=Bg.get(t);if(e&&Date.now()-e.capturedAtMs0?o:null}}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return Bg.set(t,{token:r,capturedAtMs:Date.now()}),r}function Xg(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,lt.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let o=e.slice(r+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return C$(t);try{let e=(0,fu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Wn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function mu(t){if(!t||!wt(t.pid))return!1;if(!t.startToken)return!0;let e=Xg(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var pu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=O$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,lt.mkdirSync)(du.default.dirname(this.registryPath),{recursive:!0}),!(0,lt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,lt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&lu()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)wt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;ni.pid)});let o=r.filter(i=>wt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await As(o,I$);let s=o.filter(i=>wt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+A$;for(;Date.now()wt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&lu();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,lt.mkdirSync)(du.default.dirname(this.registryPath),{recursive:!0}),(0,lt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},uu=null;function Os(){return uu||(uu=new pu),uu}var N$=[];function lu(){let t=N$.shift();t&&t()}var e_=require("child_process"),Ar=require("fs"),t_=require("util");var D$=(0,t_.promisify)(e_.execFile),j$=De.workerPid();async function r_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??j$,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!wt(i.pid)){t.registry.unregister(i.id);continue}try{await Qg(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await As(o,5e3);let s=o.filter(i=>wt(i.pid));for(let i of s)try{await Qg(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await As(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);L$(r,e),t.registry.pruneDeadEntries()}function L$(t,e){if(!(0,Ar.existsSync)(t))return;let r=null;try{let n=JSON.parse((0,Ar.readFileSync)(t,"utf-8"));r=typeof n.pid=="number"?n.pid:null}catch(n){y.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:n instanceof Error?n.message:String(n)});return}if(r!==e){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ar.rmSync)(t,{force:!0})}catch(n){n instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},n):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(n)})}}async function Qg(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=await U$();if(o){await new Promise((i,a)=>{o(r,e,c=>{if(!c){i();return}if(c.code==="ESRCH"){i();return}a(c)})});return}let s=["/PID",String(r),"/T"];e==="SIGKILL"&&s.push("/F"),await D$("taskkill",s,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}async function U$(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var n_=3e4,Or=null;function q$(){let e=Os().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function o_(){Or===null&&(Or=setInterval(q$,n_),Or.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:n_}))}function s_(){Or!==null&&(clearInterval(Or),Or=null,y.debug("SYSTEM","Health checker stopped"))}var Z$=De.workerPid(),hu=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ms({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,o_()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}s_(),this.stopPromise=r_({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},F$=new hu(Os());function gu(){return F$}function Ms(t={}){let e=t.pidFilePath??Z$;if(!(0,tr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,tr.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,tr.rmSync)(e,{force:!0}),"invalid"}return mu(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,tr.rmSync)(e,{force:!0}),"stale")}var rr=xt(require("path"),1),u_=require("os"),Ne=require("fs"),Cs=require("child_process");function i_(t){return t instanceof Error?t:new Error(String(t))}var qN=De.dataDir(),a_=De.workerPid();function c_(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function H$(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Cs.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var _u;function l_(t={}){let e=Object.keys(t).length===0;if(e&&_u!==void 0)return _u;let r=W$(t);return e&&r!==null&&(_u=r),r}function W$(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(c_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,u_.homedir)(),s=t.pathExists??Ne.existsSync,i=t.lookupInPath??H$,a=e==="win32"?[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun.exe"),rr.default.join(o,".bun","bin","bun"),n.USERPROFILE?rr.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(c_(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function qt(t){return process.platform==="win32"?Math.round(t*2):t}function d_(t,e,r={}){gu().assertCanSpawn("worker daemon");let n=Wn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=l_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=`Start-Process -FilePath '${o.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Cs.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},i_(p));return}}let s="/usr/bin/setsid",i=(0,Ne.existsSync)(s),u=zs(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function p_(){try{if(!(0,Ne.existsSync)(a_))return;let t=new Date;(0,Ne.utimesSync)(a_,t,t)}catch{}}function f_(){return Ms({logAlive:!1})}var m_=xt(require("net"),1);async function V$(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function h_(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=m_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function g_(t,e,r,n){let o=Date.now();for(;Date.now()-osetTimeout(s,500))}return!1}function Vn(t,e=3e4){return g_(t,"/api/health",e,"Service not ready yet, will retry")}function Kn(t,e=3e4){return g_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Ns=require("path"),We=require("fs");var K$=6e4;function __(){return(0,Ns.join)(oo(),"spawn.lock")}function yu(){let t=__(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,We.mkdirSync)((0,Ns.dirname)(t),{recursive:!0}),(0,We.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){if(n?.code!=="EEXIST")return!0;if(r>0)return!1;let s;try{s=(0,We.statSync)(t).mtimeMs}catch{continue}if(Date.now()-s<=K$)return!1;let i;try{i=(0,We.statSync)(t).mtimeMs}catch{continue}if(i!==s)return!1;try{(0,We.unlinkSync)(t)}catch{return!1}}return!1}function Su(){let t=__();try{if(JSON.parse((0,We.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,We.unlinkSync)(t)}catch{}}function vu(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var _D=vu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",bt(ue.HEALTH_CHECK),{min:500,max:3e5}),yD=vu("CLAUDE_MEM_API_TIMEOUT_MS",bt(ue.API_REQUEST),{min:500,max:3e5}),SD=vu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",bt(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),G$={min:500,max:3e5};async function bu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ds=null,js=null,Ls=null,Us=null;function J$(){return qs.default.join(Et.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Eu(){return Ls!==null||(Ls=Et.loadFromFile(J$())),Ls}function y_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Y$(t,e,r){let n=process.env[t];if(n!==void 0){let i=y_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=Eu()[t],s=y_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function wu(){if(Ds!==null)return Ds;let t=Eu();return Ds=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ds}function B$(){return js!==null||(js=Eu().CLAUDE_MEM_WORKER_HOST),js}function X$(){return Us!==null||(Us=Y$("CLAUDE_MEM_API_TIMEOUT_MS",bt(ue.API_REQUEST),G$)),Us}function Q$(t){return`http://${B$()}:${wu()}${t}`}function Gn(t,e={}){let r=e.method??"GET",n=e.timeoutMs??X$(),o=Q$(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?bu(o,s,n):fetch(o,s)}function S_(){let t=[qs.default.join(Qs,"plugin","scripts","worker-service.cjs"),qs.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Mr.existsSync)(e))return e;return null}var ku=xt(require("path"),1),Ve=require("fs");var eP=120*1e3;function xu(){return ku.default.join(Et.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function tP(){if(process.platform!=="win32")return!1;let t=xu();if(!(0,Ve.existsSync)(t))return!1;try{let e=(0,Ve.statSync)(t).mtimeMs;return Date.now()-etypeof d=="string")){o.grammars[s]={package:c,extensions:u,query:typeof l=="string"?l:void 0};for(let d of u)Iu[d]||(o.extensionToLanguage[d]=s);if(typeof l=="string"){let d=(0,ae.join)(t,l);try{let p=(0,pe.readFileSync)(d,"utf-8"),f=`user_${s}`;T_[f]=p,o.languageToQueryKey[s]=f}catch{y.warn("PARSER","Custom query file not found, falling back to generic",{fullQueryPath:d}),o.languageToQueryKey[s]="generic"}}else o.languageToQueryKey[s]="generic"}}return Jn.set(t,o),o}var $_={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},nP={markdown:"tree-sitter-markdown"};function oP(t){let e=$_[t];if(!e)return null;let r=nP[t];if(r){try{let n=Ru.resolve(e+"/package.json"),o=(0,ae.join)((0,ae.dirname)(n),r);if((0,pe.existsSync)((0,ae.join)(o,"src")))return o}catch{}return null}try{let n=Ru.resolve(e+"/package.json");return(0,ae.dirname)(n)}catch{return null}}function P_(t,e){let r=oP(t);if(r)return r;if(!e)return null;let o=Bn(e).grammars[t];if(!o)return null;try{let s=(0,ae.join)(e,"node_modules",o.package,"package.json");if((0,pe.existsSync)(s)){let i=(0,ae.dirname)(s);if((0,pe.existsSync)((0,ae.join)(i,"src")))return i}}catch{}return y.warn("PARSER","Grammar package not found",{language:t,package:o.package}),null}var T_={jsts:` (function_declaration name: (identifier) @name) @func (lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func (class_declaration name: (type_identifier) @name) @cls @@ -201,25 +201,25 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. (class_definition name: (identifier) @name) @cls (import_statement) @imp (import_declaration) @imp -`};function __(t){switch(t){case"javascript":return"js";case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var yu=null,Su=new Map;function y_(t){if(Su.has(t))return Su.get(t);yu||(yu=(0,Qe.mkdtempSync)((0,We.join)((0,Eu.tmpdir)(),"smart-read-queries-")));let e=(0,We.join)(yu,`${t}.scm`);return(0,Qe.writeFileSync)(e,Lx[t]),Su.set(t,e),e}var Fn=null;function Ux(){if(Fn)return Fn;try{let t=bu.resolve("tree-sitter-cli/package.json"),e=(0,We.join)((0,We.dirname)(t),"tree-sitter");if((0,Qe.existsSync)(e))return Fn=e,e}catch{}return Fn="tree-sitter",Fn}function qx(t,e,r){return S_(t,[e],r).get(e)||[]}function S_(t,e,r){if(e.length===0)return new Map;let n=Ux(),o=["query","-p",r,t,...e],s;try{s=(0,m_.execFileSync)(n,o,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return Zx(s)}function Zx(t){let e=new Map,r=null,n=null;for(let o of t.split(` -`)){if(o.length>0&&!o.startsWith(" ")&&!o.startsWith(" ")){r=o.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let s=o.match(/^\s+pattern:\s+(\d+)/);if(s){n={pattern:parseInt(s[1]),captures:[]},e.get(r).push(n);continue}let i=o.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var p_={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},Fx=new Set(["class","struct","impl","trait"]);function Hx(t,e,r,n=200){let s=t[e]||"";if(!s.trimEnd().endsWith("{")&&!s.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(` -`),a=i.indexOf("{");a!==-1&&a<500&&(s=i.slice(0,a).replace(/\n/g," ").replace(/\s+/g," ").trim())}return s=s.replace(/\s*[{:]\s*$/,"").trim(),s.length>n&&(s=s.slice(0,n-3)+"..."),s}function Wx(t,e){let r=[],n=!1;for(let o=e-1;o>=0;o--){let s=t[o].trim();if(s===""){if(n)break;continue}if(s.startsWith("/**")||s.startsWith("*")||s.startsWith("*/")||s.startsWith("//")||s.startsWith("///")||s.startsWith("//!")||s.startsWith("#")||s.startsWith("@"))r.unshift(t[o]),n=!0;else break}return r.length>0?r.join(` -`).trim():void 0}function Vx(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let o=t[n]?.trim();if(o){if(o.startsWith('"""')||o.startsWith("'''"))return o;break}}}function Kx(t,e,r,n,o,s){switch(s){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return o[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function v_(t,e,r){let n=[],o=[],s=[],i=[];for(let c of t)for(let u of c.captures)u.tag==="exp"&&s.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&o.push(u.text||e[u.startRow]?.trim()||"");for(let c of t){let u=c.captures.find(b=>p_[b.tag]),l=c.captures.find(b=>b.tag==="name");if(!u)continue;let d=u.startRow,p=u.endRow,f=p_[u.tag],m=l?.text||"anonymous",g;if(r==="markdown"&&f==="section"){let x=(e[d]||"").match(/^(#{1,6})\s/),k=x?x[1].length:1;g=`${"#".repeat(k)} ${m}`}else if(r==="markdown"&&f==="code"){let b=m!=="anonymous"?m:"";g=b?"```"+b:"```"}else r==="markdown"&&f==="metadata"?g="---frontmatter---":r==="markdown"&&f==="reference"?g=e[d]?.trim()||m:g=Hx(e,d,p);let S=r==="markdown"?void 0:Wx(e,d),v=r==="python"?Vx(e,d,p):void 0,$={name:m,kind:f,signature:g,jsdoc:S||v,lineStart:d,lineEnd:p,exported:Kx(m,d,p,s,e,r)};Fx.has(f)&&($.children=[],i.push({sym:$,startRow:d,endRow:p})),n.push($)}if(r==="markdown"){let c=new Map,u=new Set;for(let l of n){if(l.kind!=="code")continue;let d=`${l.lineStart}:${l.lineEnd}`,p=c.get(d);p?l.name!=="anonymous"?(u.add(p),c.set(d,l)):u.add(l):c.set(d,l)}if(u.size>0){let l=n.filter(d=>!u.has(d));n.length=0,n.push(...l)}}let a=new Set;for(let c of i)for(let u of n)u!==c.sym&&u.lineStart>c.startRow&&u.lineEnd<=c.endRow&&(u.kind==="function"&&(u.kind="method"),c.sym.children.push(u),a.add(u));return{symbols:n.filter(c=>!a.has(c)),imports:o}}function Ns(t,e){let r=h_(e),n=t.split(` -`),o=g_(r);if(!o)return{filePath:e,language:r,symbols:[],imports:[],totalLines:n.length,foldedTokenEstimate:50};let s=y_(__(r)),i=e.slice(e.lastIndexOf("."))||".txt",a=(0,Qe.mkdtempSync)((0,We.join)((0,Eu.tmpdir)(),"smart-src-")),c=(0,We.join)(a,`source${i}`);(0,Qe.writeFileSync)(c,t);try{let u=qx(s,c,o),l=v_(u,n,r),d=Ar({filePath:e,language:r,symbols:l.symbols,imports:l.imports,totalLines:n.length,foldedTokenEstimate:0});return{filePath:e,language:r,symbols:l.symbols,imports:l.imports,totalLines:n.length,foldedTokenEstimate:Math.ceil(d.length/4)}}finally{(0,Qe.rmSync)(a,{recursive:!0,force:!0})}}function b_(t){let e=new Map,r=new Map;for(let n of t){let o=h_(n.relativePath);r.has(o)||r.set(o,[]),r.get(o).push(n)}for(let[n,o]of r){let s=g_(n);if(!s){for(let u of o){let l=u.content.split(` -`);e.set(u.relativePath,{filePath:u.relativePath,language:n,symbols:[],imports:[],totalLines:l.length,foldedTokenEstimate:50})}continue}let i=y_(__(n)),a=o.map(u=>u.absolutePath),c=S_(i,a,s);for(let u of o){let l=u.content.split(` -`),d=c.get(u.absolutePath)||[],p=v_(d,l,n),f=Ar({filePath:u.relativePath,language:n,symbols:p.symbols,imports:p.imports,totalLines:l.length,foldedTokenEstimate:0});e.set(u.relativePath,{filePath:u.relativePath,language:n,symbols:p.symbols,imports:p.imports,totalLines:l.length,foldedTokenEstimate:Math.ceil(f.length/4)})}}return e}function Ar(t){if(t.language==="markdown")return Jx(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(E_(r," "));return e.join(` -`)}function Jx(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let o=n.signature.match(/^(#{1,6})\s/),s=o?o[1].length:1,i=" ".repeat(s),a=`L${n.lineStart+1}`,c=`${i}${n.signature}`;e.push(`${c.padEnd(56)}${a}`)}else if(n.kind==="code"){let o=f_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,a=`${s}${n.signature}`;e.push(`${a.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let o=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,s=` ${n.signature}`;e.push(`${s.padEnd(56)}${o}`)}else if(n.kind==="reference"){let o=f_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=`L${n.lineStart+1}`,a=`${s}\u2197 ${n.name}`;e.push(`${a.padEnd(56)}${i}`)}return e.join(` -`)}function f_(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart{let u=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(a){let c=a.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();c&&r.push(`${e} \u{1F4AC} ${c}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(E_(i,e+" "));return r.join(` -`)}function Gx(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function w_(t,e,r){let n=Ns(t,e),o=u=>{for(let l of u){if(l.name===r)return l;if(l.children){let d=o(l.children);if(d)return d}}return null},s=o(n.symbols);if(!s)return null;let i=t.split(` -`);if(n.language==="markdown"&&s.kind==="section"){let u=s.signature.match(/^(#{1,6})\s/),l=u?u[1].length:1,d=s.lineStart,p=i.length-1;for(let m of n.symbols)if(m.kind==="section"&&m.lineStart>d){let g=m.signature.match(/^(#{1,6})\s/);if((g?g[1].length:1)<=l){for(p=m.lineStart-1;p>d&&i[p].trim()==="";)p--;break}}let f=i.slice(d,p+1).join(` -`);return` -${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l===""||l.startsWith("*")||l.startsWith("/**")||l.startsWith("///")||l.startsWith("//")||l.startsWith("#")||l.startsWith("@")||l==="*/")a=u;else break}let c=i.slice(a,s.lineEnd+1).join(` -`);return`// \u{1F4CD} ${e} L${a+1}-${s.lineEnd+1} -${c}`}var Bx=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),Xx=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),Qx=512*1024;async function*k_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Mr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||Xx.has(o.name))continue;let s=(0,Hn.join)(t,o.name);if(o.isDirectory())yield*k_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));Bx.has(i)&&(yield s)}}}async function eP(t){try{let e=await(0,Mr.stat)(t);if(e.size>Qx||e.size===0)return null;let r=await(0,Mr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function $_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of k_(t,t,20)){if(r.filePattern&&!(0,Hn.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await eP(g);S&&i.push({absolutePath:g,relativePath:(0,Hn.relative)(t,g),content:S})}let a=b_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=tP(S);let $=Ds(g.toLowerCase(),s)>0,b=[],x=(k,_e)=>{for(let V of k){let tt=0,Ae="",kt=Ds(V.name.toLowerCase(),s);kt>0&&(tt+=kt*3,Ae="name match"),V.signature.toLowerCase().includes(o)&&(tt+=2,Ae=Ae?`${Ae} + signature`:"signature match"),V.jsdoc&&V.jsdoc.toLowerCase().includes(o)&&(tt+=1,Ae=Ae?`${Ae} + jsdoc`:"jsdoc match"),tt>0&&($=!0,b.push({filePath:g,symbolName:_e?`${_e}.${V.name}`:V.name,kind:V.kind,signature:V.signature,jsdoc:V.jsdoc,lineStart:V.lineStart,lineEnd:V.lineEnd,matchReason:Ae})),V.children&&x(V.children,V.name)}};x(S.symbols),$&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Ds(g.symbolName.toLowerCase(),s);return Ds(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Ds(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function tP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function x_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` +`};function sP(t){switch(t){case"javascript":return"js";case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"elixir":return"generic";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var $u=null,Pu=new Map;function z_(t){if(Pu.has(t))return Pu.get(t);$u||($u=(0,pe.mkdtempSync)((0,ae.join)((0,Fs.tmpdir)(),"smart-read-queries-")));let e=(0,ae.join)($u,`${t}.scm`);return(0,pe.writeFileSync)(e,T_[t]),Pu.set(t,e),e}var Yn=null,Tu=null;function iP(){if(Yn)return Yn;try{let t=Ru.resolve("tree-sitter-cli/package.json"),e=(0,ae.dirname)(t),r=process.platform==="win32"?["tree-sitter.exe","tree-sitter"]:["tree-sitter"];for(let n of r){let o=(0,ae.join)(e,n);if((0,pe.existsSync)(o))return Yn=o,o}}catch{}return Yn="tree-sitter",Yn}function aP(){return Tu||(Tu=(0,pe.mkdtempSync)((0,ae.join)((0,Fs.tmpdir)(),"claude-mem-tree-sitter-cache-"))),Tu}function cP(t,e,r){return R_(t,[e],r).get(e)||[]}function R_(t,e,r){if(e.length===0)return new Map;let n=iP(),o=["query","-p",r,t,...e],s;try{s=(0,w_.execFileSync)(n,o,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"],env:{...process.env,XDG_CACHE_HOME:aP()}})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return uP(s)}function uP(t){let e=new Map,r=null,n=null;for(let o of t.split(` +`)){if(o.length>0&&!o.startsWith(" ")&&!o.startsWith(" ")){r=o.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let s=o.match(/^\s+pattern:\s+(\d+)/);if(s){n={pattern:parseInt(s[1]),captures:[]},e.get(r).push(n);continue}let i=o.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var b_={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},lP=new Set(["class","struct","impl","trait"]);function dP(t,e,r,n=200){let s=t[e]||"";if(!s.trimEnd().endsWith("{")&&!s.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(` +`),a=i.indexOf("{");a!==-1&&a<500&&(s=i.slice(0,a).replace(/\n/g," ").replace(/\s+/g," ").trim())}return s=s.replace(/\s*[{:]\s*$/,"").trim(),s.length>n&&(s=s.slice(0,n-3)+"..."),s}function pP(t,e){let r=[],n=!1;for(let o=e-1;o>=0;o--){let s=t[o].trim();if(s===""){if(n)break;continue}if(s.startsWith("/**")||s.startsWith("*")||s.startsWith("*/")||s.startsWith("//")||s.startsWith("///")||s.startsWith("//!")||s.startsWith("#")||s.startsWith("@"))r.unshift(t[o]),n=!0;else break}return r.length>0?r.join(` +`).trim():void 0}function fP(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let o=t[n]?.trim();if(o){if(o.startsWith('"""')||o.startsWith("'''"))return o;break}}}function mP(t,e,r,n,o,s){switch(s){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return o[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function I_(t,e,r){let n=[],o=[],s=[],i=[];for(let c of t)for(let u of c.captures)u.tag==="exp"&&s.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&o.push(u.text||e[u.startRow]?.trim()||"");for(let c of t){let u=c.captures.find(v=>b_[v.tag]),l=c.captures.find(v=>v.tag==="name");if(!u)continue;let d=u.startRow,p=u.endRow,f=b_[u.tag],m=l?.text||"anonymous",_;if(r==="markdown"&&f==="section"){let $=(e[d]||"").match(/^(#{1,6})\s/),x=$?$[1].length:1;_=`${"#".repeat(x)} ${m}`}else if(r==="markdown"&&f==="code"){let v=m!=="anonymous"?m:"";_=v?"```"+v:"```"}else r==="markdown"&&f==="metadata"?_="---frontmatter---":r==="markdown"&&f==="reference"?_=e[d]?.trim()||m:_=dP(e,d,p);let S=r==="markdown"?void 0:pP(e,d),b=r==="python"?fP(e,d,p):void 0,E={name:m,kind:f,signature:_,jsdoc:S||b,lineStart:d,lineEnd:p,exported:mP(m,d,p,s,e,r)};lP.has(f)&&(E.children=[],i.push({sym:E,startRow:d,endRow:p})),n.push(E)}if(r==="markdown"){let c=new Map,u=new Set;for(let l of n){if(l.kind!=="code")continue;let d=`${l.lineStart}:${l.lineEnd}`,p=c.get(d);p?l.name!=="anonymous"?(u.add(p),c.set(d,l)):u.add(l):c.set(d,l)}if(u.size>0){let l=n.filter(d=>!u.has(d));n.length=0,n.push(...l)}}let a=new Set;for(let c of i)for(let u of n)u!==c.sym&&u.lineStart>c.startRow&&u.lineEnd<=c.endRow&&(u.kind==="function"&&(u.kind="method"),c.sym.children.push(u),a.add(u));return{symbols:n.filter(c=>!a.has(c)),imports:o}}function Au(t){let e=(0,ae.dirname)(t);for(;;){if((0,pe.existsSync)((0,ae.join)(e,".claude-mem.json")))return e;let r=(0,ae.dirname)(e);if(r===e)return;e=r}}function Hs(t,e,r){let n=r?Bn(r):Cr,o=k_(e,n),s=t.split(` +`),i=P_(o,r);if(!i)return{filePath:e,language:o,symbols:[],imports:[],totalLines:s.length,foldedTokenEstimate:50};let a=x_(o,n),c=z_(a),u=e.slice(e.lastIndexOf("."))||".txt",l=(0,pe.mkdtempSync)((0,ae.join)((0,Fs.tmpdir)(),"smart-src-")),d=(0,ae.join)(l,`source${u}`);(0,pe.writeFileSync)(d,t);try{let p=cP(c,d,i),f=I_(p,s,o),m=Nr({filePath:e,language:o,symbols:f.symbols,imports:f.imports,totalLines:s.length,foldedTokenEstimate:0});return{filePath:e,language:o,symbols:f.symbols,imports:f.imports,totalLines:s.length,foldedTokenEstimate:Math.ceil(m.length/4)}}finally{(0,pe.rmSync)(l,{recursive:!0,force:!0})}}function A_(t,e){let r=new Map,n=e?Bn(e):Cr,o=new Map;for(let s of t){let i=k_(s.relativePath,n);o.has(i)||o.set(i,[]),o.get(i).push(s)}for(let[s,i]of o){let a=P_(s,e);if(!a){for(let p of i){let f=p.content.split(` +`);r.set(p.relativePath,{filePath:p.relativePath,language:s,symbols:[],imports:[],totalLines:f.length,foldedTokenEstimate:50})}continue}let c=x_(s,n),u=z_(c),l=i.map(p=>p.absolutePath),d=R_(u,l,a);for(let p of i){let f=p.content.split(` +`),m=d.get(p.absolutePath)||[],_=I_(m,f,s),S=Nr({filePath:p.relativePath,language:s,symbols:_.symbols,imports:_.imports,totalLines:f.length,foldedTokenEstimate:0});r.set(p.relativePath,{filePath:p.relativePath,language:s,symbols:_.symbols,imports:_.imports,totalLines:f.length,foldedTokenEstimate:Math.ceil(S.length/4)})}}return r}function Nr(t){if(t.language==="markdown")return hP(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(O_(r," "));return e.join(` +`)}function hP(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let o=n.signature.match(/^(#{1,6})\s/),s=o?o[1].length:1,i=" ".repeat(s),a=`L${n.lineStart+1}`,c=`${i}${n.signature}`;e.push(`${c.padEnd(56)}${a}`)}else if(n.kind==="code"){let o=E_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,a=`${s}${n.signature}`;e.push(`${a.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let o=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,s=` ${n.signature}`;e.push(`${s.padEnd(56)}${o}`)}else if(n.kind==="reference"){let o=E_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=`L${n.lineStart+1}`,a=`${s}\u2197 ${n.name}`;e.push(`${a.padEnd(56)}${i}`)}return e.join(` +`)}function E_(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart{let u=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(a){let c=a.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();c&&r.push(`${e} \u{1F4AC} ${c}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(O_(i,e+" "));return r.join(` +`)}function gP(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function M_(t,e,r,n){let o=Hs(t,e,n),s=l=>{for(let d of l){if(d.name===r)return d;if(d.children){let p=s(d.children);if(p)return p}}return null},i=s(o.symbols);if(!i)return null;let a=t.split(` +`);if(o.language==="markdown"&&i.kind==="section"){let l=i.signature.match(/^(#{1,6})\s/),d=l?l[1].length:1,p=i.lineStart,f=a.length-1;for(let _ of o.symbols)if(_.kind==="section"&&_.lineStart>p){let S=_.signature.match(/^(#{1,6})\s/);if((S?S[1].length:1)<=d){for(f=_.lineStart-1;f>p&&a[f].trim()==="";)f--;break}}let m=a.slice(p,f+1).join(` +`);return` +${m}`}let c=i.lineStart;for(let l=i.lineStart-1;l>=0;l--){let d=a[l].trim();if(d===""||d.startsWith("*")||d.startsWith("/**")||d.startsWith("///")||d.startsWith("//")||d.startsWith("#")||d.startsWith("@")||d==="*/")c=l;else break}let u=a.slice(c,i.lineEnd+1).join(` +`);return`// \u{1F4CD} ${e} L${c+1}-${i.lineEnd+1} +${u}`}var C_=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),yP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),SP=512*1024;async function*N_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Dr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||yP.has(s.name))continue;let i=(0,Xn.join)(t,s.name);if(s.isDirectory())yield*N_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(C_.has(a)||n&&n.has(a))&&(yield i)}}}async function vP(t){try{let e=await(0,Dr.stat)(t);if(e.size>SP||e.size===0)return null;let r=await(0,Dr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function D_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=Bn(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)C_.has(v)||c.add(v);let u=[];for await(let E of N_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Xn.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await vP(E);v&&u.push({absolutePath:E,relativePath:(0,Xn.relative)(t,E),content:v})}let l=A_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=bP(v);let x=Ws(E.toLowerCase(),s)>0,Se=[],we=(Zt,nr)=>{for(let ce of Zt){let kt=0,Ge="",Lr=Ws(ce.name.toLowerCase(),s);Lr>0&&(kt+=Lr*3,Ge="name match"),ce.signature.toLowerCase().includes(o)&&(kt+=2,Ge=Ge?`${Ge} + signature`:"signature match"),ce.jsdoc&&ce.jsdoc.toLowerCase().includes(o)&&(kt+=1,Ge=Ge?`${Ge} + jsdoc`:"jsdoc match"),kt>0&&(x=!0,Se.push({filePath:E,symbolName:nr?`${nr}.${ce.name}`:ce.name,kind:ce.kind,signature:ce.signature,jsdoc:ce.jsdoc,lineStart:ce.lineStart,lineEnd:ce.lineEnd,matchReason:Ge})),ce.children&&we(ce.children,ce.name)}};we(v.symbols),x&&(d.push(v),p.push(...Se))}p.sort((E,v)=>{let $=Ws(E.symbolName.toLowerCase(),s);return Ws(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Ws(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function bP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function j_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(` -`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ar(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` -`)}var $u=require("node:fs/promises"),Us=require("node:fs"),et=require("node:path"),I_=require("node:os"),O_=require("node:url");var P_="claude";function rP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function js(t){if(!t)return P_;let e=rP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:P_}var nP=qt(ue.API_REQUEST),Ve=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ls=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=oP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??nP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ve("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await fu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server ${e} ${r} returned ${i.status}: ${sP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ve("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function T_(t){return t instanceof Ve}function oP(t){return t.replace(/\/+$/,"")}function wu(t){return typeof t=="string"?js(t):null}function sP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function ku(){let e=(ws().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function z_(){let t=ws(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ls(s),projectId:o,serverBaseUrl:r}}var xP={},iP="13.10.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var A_=!1,M_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,O_.fileURLToPath)(xP.url))}catch(t){return A_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),xu=l_()??(0,et.resolve)(M_,"worker-service.cjs");function aP(){A_&&((0,Us.existsSync)(xu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:xu,mcpServerDir:M_}))}async function pt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ms(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ms(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function cP(){try{return(await Ms("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function uP(){if(ku()!=="server")return null;let e=z_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function lP(t){return T_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Vn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Kn(t){let e=uP();if(!e)throw new Ve("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ve("missing_api_key",`${t}: ${e.reason}`);return e}function Jn(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),lP(n)}}}var dP=Jn("observation_add",async t=>{let e=Kn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Vn(o)});function Zs(t){return typeof t=="string"?js(t):null}var pP=Jn("observation_record_event",async t=>{let e=Kn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Vn(o)}),fP=Jn("observation_search",async t=>{let e=Kn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Vn(o)}),mP=Jn("observation_context",async t=>{let e=Kn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Vn(o)});function hP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function gP(t){let e=hP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:pt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var _P=Jn("observation_generation_status",async t=>{let e=Kn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Vn(n)});async function yP(){if(await cP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),aP();try{let t=hu(),e=await d_(t,xu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var C_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Nr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` +`)}var Nu=require("node:fs/promises"),Gs=require("node:fs"),tt=require("node:path"),K_=require("node:os"),G_=require("node:url");var L_="claude";function EP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Vs(t){if(!t)return L_;let e=EP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:L_}var wP=bt(ue.API_REQUEST),Ke=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ks=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=kP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??wP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ke("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ke("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ke("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await bu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ke(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ke("http_error",`Server ${e} ${r} returned ${i.status}: ${xP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Ke("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:c})}}};function U_(t){return t instanceof Ke}function kP(t){return t.replace(/\/+$/,"")}function Ou(t){return typeof t=="string"?Vs(t):null}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mu(){let e=(Is().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function q_(){let t=Is(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ks(s),projectId:o,serverBaseUrl:r}}var FP={},$P="13.9.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var J_=!1,Y_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,G_.fileURLToPath)(FP.url))}catch{return J_=!0,process.cwd()}})(),Du=S_()??(0,tt.resolve)(Y_,"worker-service.cjs");function PP(){J_&&((0,Gs.existsSync)(Du)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Du,mcpServerDir:Y_}))}var Z_={search:"/api/search",timeline:"/api/timeline"};async function Cu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Gn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function TP(t,e){y.debug("SYSTEM","\u2192 Worker API text",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Gn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.text();return y.debug("SYSTEM","\u2190 Worker API text success",void 0,{endpoint:t}),{content:[{type:"text",text:s}]}}catch(o){return y.error("SYSTEM","\u2190 Worker API text error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function zP(t,e){let r=await Gn(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function jr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function RP(){try{return(await Gn("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){if(Mu()!=="server")return null;let e=q_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function eo(t){return U_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function to(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=IP();if(!e)throw new Ke("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ke("missing_api_key",`${t}: ${e.reason}`);return e}async function F_(t){try{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return to(o)}catch(e){return eo(e)}}function Ys(t){return typeof t=="string"?Vs(t):null}async function AP(t){try{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return to(o)}catch(e){return eo(e)}}async function H_(t){try{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.searchObservations(n);return to(o)}catch(e){return eo(e)}}async function W_(t){try{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.contextObservations(n);return to(o)}catch(e){return eo(e)}}function OP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function MP(t){let e=OP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:TP("/api/context/inject",{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}})}async function CP(t){try{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return to(n)}catch(e){return eo(e)}}async function NP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),PP();try{let t=wu(),e=await v_(t,Du);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var B_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs @@ -239,8 +239,8 @@ NEVER fetch full details without filtering first. 10x token savings.`,inputSchem \`get_observations(ids=[...])\` # ALWAYS batch for 2+ items Returns: Complete details (~500-1000 tokens/result) -**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, platformSource, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},platformSource:{type:"string",description:"Filter by platform source (e.g. claude, codex, cursor) \u2014 restricts results to that agent's own memory"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>await pt("/api/search",{query:t})},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>await pt("/api/timeline",{query:t})},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await pt("/api/observations/batch",{body:t})},{name:"session_start_context",description:"Render the exact worker-mode SessionStart context for a project. Calls /api/context/inject and returns the same text hooks inject at startup. Params: project OR projects, platformSource, full, colors.",inputSchema:{type:"object",properties:{project:{type:"string",description:"Project name, e.g. claude-mem/night-parsnip"},projects:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}],description:"Project chain for context injection. Array or comma-separated string; last project is treated as primary."},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},full:{type:"boolean",description:"When true, request full context instead of configured limits"},colors:{type:"boolean",description:"When true, request human terminal-color formatting"}},additionalProperties:!1},handler:async t=>gP(t??{})},{name:"observation_add",description:"Insert a manual observation directly into server storage. Calls /v1/memories \u2014 does NOT enqueue generation. Server runtime only. Params: content (required), projectId (optional, falls back to settings), serverSessionId, kind, metadata.",inputSchema:{type:"object",properties:{projectId:{type:"string",description:"Project id (falls back to CLAUDE_MEM_SERVER_PROJECT_ID)"},serverSessionId:{type:"string",description:"Optional server_session_id to attach the observation to"},kind:{type:"string",description:"Observation kind (default: manual)"},content:{type:"string",description:"Observation content (required)"},metadata:{type:"object",description:"Free-form metadata object",additionalProperties:!0}},required:["content"],additionalProperties:!1},handler:async t=>dP(t??{})},{name:"observation_record_event",description:"Record an agent event into the server. Calls /v1/events \u2014 server inserts the event row, the outbox row, and enqueues a generation job atomically. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},eventType:{type:"string",description:"Event type (required), e.g. PostToolUse, UserPromptSubmit"},sourceType:{type:"string",enum:["hook","worker","provider","server","api"]},serverSessionId:{type:"string"},contentSessionId:{type:"string"},memorySessionId:{type:"string"},platformSource:{type:"string",description:"Optional platform source for session linkage and event scoping"},payload:{description:"Event payload (any JSON value)"},occurredAtEpoch:{type:"number",description:"Unix epoch millis (defaults to now)"},generate:{type:"boolean",description:"If false, skip generation job (default: true)"}},required:["eventType"],additionalProperties:!1},handler:async t=>pP(t??{})},{name:"observation_search",description:"Full-text search across generated observations using the server's GIN tsvector index (Phase 1). Calls /v1/search. Server runtime only. Params: query (required), projectId (optional), platformSource, limit (default 20, max 100).",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max results (default 20, max 100)"}},required:["query"],additionalProperties:!1},handler:async t=>fP(t??{})},{name:"observation_context",description:"Get top-N relevant observations for context injection. Returns matched observations AND a pre-joined context string suitable for prompt injection. Calls /v1/context. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max observations (default 10, max 50)"}},required:["query"],additionalProperties:!1},handler:async t=>mP(t??{})},{name:"observation_generation_status",description:"Look up the status of an observation generation job by id. Calls /v1/jobs/:id. Server runtime only. Returns the same payload as REST.",inputSchema:{type:"object",properties:{jobId:{type:"string",description:"Generation job id (required)"}},required:["jobId"],additionalProperties:!1},handler:async t=>_P(t??{})},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,et.resolve)(t.path||process.cwd()),r=await $_(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:x_(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,et.resolve)(t.file_path),r=await(0,$u.readFile)(e,"utf-8"),n=w_(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let o=Ns(r,e);if(o.symbols.length>0){let s=o.symbols.map(i=>` - ${i.name} (${i.kind})`).join(` +**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, platformSource, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},platformSource:{type:"string",description:"Filter by platform source (e.g. claude, codex, cursor) \u2014 restricts results to that agent's own memory"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>{let e=Z_.search;return await Cu(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>{let e=Z_.timeline;return await Cu(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await jr("/api/observations/batch",t)},{name:"session_start_context",description:"Render the exact worker-mode SessionStart context for a project. Calls /api/context/inject and returns the same text hooks inject at startup. Params: project OR projects, platformSource, full, colors.",inputSchema:{type:"object",properties:{project:{type:"string",description:"Project name, e.g. claude-mem/night-parsnip"},projects:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}],description:"Project chain for context injection. Array or comma-separated string; last project is treated as primary."},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},full:{type:"boolean",description:"When true, request full context instead of configured limits"},colors:{type:"boolean",description:"When true, request human terminal-color formatting"}},additionalProperties:!1},handler:async t=>MP(t??{})},{name:"observation_add",description:"Insert a manual observation directly into server storage. Calls /v1/memories \u2014 does NOT enqueue generation. Server runtime only. Params: content (required), projectId (optional, falls back to settings), serverSessionId, kind, metadata.",inputSchema:{type:"object",properties:{projectId:{type:"string",description:"Project id (falls back to CLAUDE_MEM_SERVER_PROJECT_ID)"},serverSessionId:{type:"string",description:"Optional server_session_id to attach the observation to"},kind:{type:"string",description:"Observation kind (default: manual)"},content:{type:"string",description:"Observation content (required)"},metadata:{type:"object",description:"Free-form metadata object",additionalProperties:!0}},required:["content"],additionalProperties:!1},handler:async t=>F_(t??{})},{name:"observation_record_event",description:"Record an agent event into the server. Calls /v1/events \u2014 server inserts the event row, the outbox row, and enqueues a generation job atomically. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},eventType:{type:"string",description:"Event type (required), e.g. PostToolUse, UserPromptSubmit"},sourceType:{type:"string",enum:["hook","worker","provider","server","api"]},serverSessionId:{type:"string"},contentSessionId:{type:"string"},memorySessionId:{type:"string"},platformSource:{type:"string",description:"Optional platform source for session linkage and event scoping"},payload:{description:"Event payload (any JSON value)"},occurredAtEpoch:{type:"number",description:"Unix epoch millis (defaults to now)"},generate:{type:"boolean",description:"If false, skip generation job (default: true)"}},required:["eventType"],additionalProperties:!1},handler:async t=>AP(t??{})},{name:"observation_search",description:"Full-text search across generated observations using the server's GIN tsvector index (Phase 1). Calls /v1/search. Server runtime only. Params: query (required), projectId (optional), platformSource, limit (default 20, max 100).",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max results (default 20, max 100)"}},required:["query"],additionalProperties:!1},handler:async t=>H_(t??{})},{name:"observation_context",description:"Get top-N relevant observations for context injection. Returns matched observations AND a pre-joined context string suitable for prompt injection. Calls /v1/context. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max observations (default 10, max 50)"}},required:["query"],additionalProperties:!1},handler:async t=>W_(t??{})},{name:"observation_generation_status",description:"Look up the status of an observation generation job by id. Calls /v1/jobs/:id. Server runtime only. Returns the same payload as REST.",inputSchema:{type:"object",properties:{jobId:{type:"string",description:"Generation job id (required)"}},required:["jobId"],additionalProperties:!1},handler:async t=>CP(t??{})},{name:"memory_add",description:"Compatibility alias for observation_add. Same behavior; same schema modulo the legacy field names.",inputSchema:{type:"object",properties:{projectId:{type:"string"},kind:{type:"string"},content:{type:"string"},narrative:{type:"string",description:"Legacy alias for content; mapped to content if content is missing"},title:{type:"string",description:"Legacy field; appended to metadata.title"},metadata:{type:"object",additionalProperties:!0}},required:["projectId"],additionalProperties:!0},handler:async t=>{let e={projectId:t?.projectId,content:t?.content??t?.narrative??"",kind:t?.kind,metadata:{...t?.metadata??{},...t?.title?{title:t.title}:{}}};return F_(e)}},{name:"memory_search",description:"Compatibility alias for observation_search. Same FTS path; same /v1/search REST endpoint.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string"},platformSource:{type:"string"},limit:{type:"number"}},required:["projectId","query"],additionalProperties:!0},handler:async t=>H_(t??{})},{name:"memory_context",description:"Compatibility alias for observation_context. Same /v1/context REST endpoint.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string"},platformSource:{type:"string"},limit:{type:"number"}},required:["projectId","query"],additionalProperties:!0},handler:async t=>W_(t??{})},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,tt.resolve)(t.path||process.cwd()),r=await D_(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:j_(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,tt.resolve)(t.file_path),r=await(0,Nu.readFile)(e,"utf-8"),n=Au(e)??process.cwd(),o=M_(r,e,t.symbol_name,n);if(o)return{content:[{type:"text",text:o}]};let s=Hs(r,e,n);if(s.symbols.length>0){let i=s.symbols.map(a=>` - ${a.name} (${a.kind})`).join(` `);return{content:[{type:"text",text:`Symbol "${t.symbol_name}" not found in ${t.file_path}. Available symbols: -${s}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,et.resolve)(t.file_path),r=await(0,$u.readFile)(e,"utf-8"),n=Ns(r,e);return n.symbols.length>0?{content:[{type:"text",text:Ar(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await pt("/api/corpus",{body:t})},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await pt("/api/corpus",{query:t})},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/prime`,{body:r})}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/query`,{body:r})}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/rebuild`,{body:r})}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/reprime`,{body:r})}}],Pu=new ys({name:"claude-mem",version:iP},{capabilities:{tools:{}}});Pu.setRequestHandler(ra,async()=>({tools:C_.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Pu.setRequestHandler(sn,async t=>{let e=C_.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var SP=3e4,Wn=null,R_=!1;function qs(){Gn("stdio-closed")}function N_(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Gn("stdio-error")}function vP(){process.stdin.on("end",qs),process.stdin.on("close",qs),process.stdin.on("error",N_)}function bP(){process.stdin.off("end",qs),process.stdin.off("close",qs),process.stdin.off("error",N_)}function EP(){if(process.platform==="win32")return;let t=process.ppid;Wn=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),Gn())},SP),Wn.unref&&Wn.unref()}function Gn(t="shutdown"){R_||(R_=!0,Wn&&clearInterval(Wn),bP(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Gn);process.on("SIGINT",Gn);function wP(){let t=(0,I_.homedir)(),e=[(0,et.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,et.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,Us.existsSync)(i)),n=[(0,et.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,et.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],o=n.some(i=>i&&(0,Us.existsSync)(i)),s=n[0];!r&&o&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:s})}function kP(){try{wP()}catch(t){y.warn("SYSTEM","checkMarketplaceMarker failed (non-fatal startup check)",void 0,t instanceof Error?t:new Error(String(t)))}}async function $P(){let t=new vs;vP(),await Pu.connect(t),y.info("SYSTEM","Claude-mem search server started"),kP(),EP(),setTimeout(async()=>{if(ku()==="server"){y.info("SYSTEM","MCP runtime=server \u2014 skipping worker auto-start",void 0,{});return}await yP()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}$P().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)}); +${i}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,tt.resolve)(t.file_path),r=await(0,Nu.readFile)(e,"utf-8"),n=Hs(r,e,Au(e)??process.cwd());return n.symbols.length>0?{content:[{type:"text",text:Nr(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await jr("/api/corpus",t)},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await Cu("/api/corpus",t)},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/prime`,r)}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/query`,r)}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/rebuild`,r)}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],ju=new $s({name:"claude-mem",version:$P},{capabilities:{tools:{}}});ju.setRequestHandler(ua,async()=>({tools:B_.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));ju.setRequestHandler(dn,async t=>{let e=B_.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var DP=3e4,Qn=null,V_=!1;function Js(){no("stdio-closed")}function X_(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),no("stdio-error")}function jP(){process.stdin.on("end",Js),process.stdin.on("close",Js),process.stdin.on("error",X_)}function LP(){process.stdin.off("end",Js),process.stdin.off("close",Js),process.stdin.off("error",X_)}function UP(){if(process.platform==="win32")return;let t=process.ppid;Qn=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),no())},DP),Qn.unref&&Qn.unref()}function no(t="shutdown"){V_||(V_=!0,Qn&&clearInterval(Qn),LP(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",no);process.on("SIGINT",no);function qP(){try{let t=(0,K_.homedir)(),e=[(0,tt.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,tt.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,Gs.existsSync)(i)),n=[(0,tt.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,tt.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],o=n.some(i=>i&&(0,Gs.existsSync)(i)),s=n[0];!r&&o&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:s})}catch{}}async function ZP(){let t=new Ts;jP(),await ju.connect(t),y.info("SYSTEM","Claude-mem search server started"),qP(),UP(),setTimeout(async()=>{if(Mu()==="server"){y.info("SYSTEM","MCP runtime=server \u2014 skipping worker auto-start",void 0,{});return}await NP()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}ZP().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)}); diff --git a/src/npx-cli/install/setup-runtime.ts b/src/npx-cli/install/setup-runtime.ts index f1a933b29..23d319aca 100644 --- a/src/npx-cli/install/setup-runtime.ts +++ b/src/npx-cli/install/setup-runtime.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync, writeFileSync } from 'fs'; -import { exec, execSync, spawnSync } from 'child_process'; +import { exec, execFile, execSync, spawnSync } from 'child_process'; import { createRequire } from 'module'; import { join } from 'path'; import { homedir } from 'os'; @@ -92,7 +92,7 @@ function isBunInstalled(): boolean { return getBunPath() !== null; } -function getBunVersion(): string | null { +export function getBunVersion(): string | null { const bunPath = getBunPath(); if (!bunPath) return null; @@ -129,7 +129,7 @@ function isUvInstalled(): boolean { return getUvPath() !== null; } -function getUvVersion(): string | null { +export function getUvVersion(): string | null { const uvPath = getUvPath(); if (!uvPath) return null; @@ -246,6 +246,66 @@ function installUv(): void { * we resolve subpaths, never a pinned version. */ const ZOD_REQUIRED_SUBPATHS = ['zod/v3', 'zod/v4', 'zod/v4-mini'] as const; +const TREE_SITTER_VERSION_TIMEOUT_MS = 10_000; + +export function treeSitterCliBinaryPath(targetDir: string): string { + return join( + targetDir, + 'node_modules', + 'tree-sitter-cli', + IS_WINDOWS ? 'tree-sitter.exe' : 'tree-sitter', + ); +} + +export function isTreeSitterCliBinaryUsable(targetDir: string): boolean { + const result = spawnSync(treeSitterCliBinaryPath(targetDir), ['--version'], { + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'pipe'], + timeout: TREE_SITTER_VERSION_TIMEOUT_MS, + windowsHide: true, + }); + return result.status === 0 + && /^tree-sitter \d+\.\d+\.\d+(?:\s|$)/.test((result.stdout ?? '').trim()); +} + +/** + * Runtime installs suppress all dependency lifecycle scripts to avoid running + * unbounded transitive postinstalls. tree-sitter-cli is the one intentional + * exception: its install script downloads the platform CLI used by smart-explore. + * Run only that top-level script, with the installer's existing timeout. + */ +export async function ensureTreeSitterCliBinary( + targetDir: string, + isUsable: (targetDir: string) => boolean = isTreeSitterCliBinaryUsable, +): Promise { + const binaryPath = treeSitterCliBinaryPath(targetDir); + if (isUsable(targetDir)) return; + + const cliDir = join(targetDir, 'node_modules', 'tree-sitter-cli'); + const installScript = join(cliDir, 'install.js'); + if (!existsSync(installScript)) { + throw new Error(`tree-sitter-cli install script not found: ${installScript}`); + } + + await new Promise((resolve, reject) => { + execFile(process.execPath, [installScript], { + cwd: cliDir, + timeout: INSTALL_TIMEOUT_MS, + maxBuffer: 16 * 1024 * 1024, + windowsHide: true, + }, (error, stdout, stderr) => { + if (error) { + reject(Object.assign(error, { stdout, stderr })); + return; + } + resolve(); + }); + }); + + if (!isUsable(targetDir)) { + throw new Error(`tree-sitter-cli install completed without creating a working executable ${binaryPath}`); + } +} export function verifyCriticalModules(targetDir: string): void { const pkg = JSON.parse(readFileSync(join(targetDir, 'package.json'), 'utf-8')); @@ -297,6 +357,10 @@ export function verifyCriticalModules(targetDir: string): void { } } + if (dependencies.includes('tree-sitter-cli') && !isTreeSitterCliBinaryUsable(targetDir)) { + unresolvable.push('tree-sitter-cli executable'); + } + if (unresolvable.length > 0) { throw new Error( `Post-install check failed: unresolvable modules: ${unresolvable.join(', ')}`, @@ -460,6 +524,12 @@ export async function installPluginDependencies(targetDir: string, bunPath: stri throw new Error(`bun install failed in ${targetDir}\n${describeExecError(err)}`); } + try { + await ensureTreeSitterCliBinary(targetDir); + } catch (error) { + throw new Error(`tree-sitter-cli setup failed in ${targetDir}\n${describeExecError(error)}`); + } + verifyCriticalModules(targetDir); } diff --git a/src/services/integrations/CodexCliInstaller.ts b/src/services/integrations/CodexCliInstaller.ts index 6bb529f88..3cf973a1a 100644 --- a/src/services/integrations/CodexCliInstaller.ts +++ b/src/services/integrations/CodexCliInstaller.ts @@ -10,6 +10,12 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; import { fileURLToPath } from 'url'; import { logger } from '../../utils/logger.js'; import { paths } from '../../shared/paths.js'; +import { + ensureTreeSitterCliBinary, + getBunVersion, + getUvVersion, + writeInstallMarker, +} from '../../npx-cli/install/setup-runtime.js'; const CODEX_DIR = path.join(homedir(), '.codex'); const CODEX_AGENTS_MD_PATH = path.join(CODEX_DIR, 'AGENTS.md'); @@ -94,6 +100,69 @@ function resolvePluginMarketplaceRoot(preferredRoot?: string): string { throw new Error('Could not locate a Codex marketplace root with .agents/plugins/marketplace.json and plugin/.codex-plugin/plugin.json. Run npx claude-mem@latest install from the package or repo root.'); } +function readCodexPluginVersion(marketplaceRoot: string): string { + const manifestPath = path.join(marketplaceRoot, 'plugin', '.codex-plugin', 'plugin.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as { version?: unknown }; + if (typeof manifest.version !== 'string' || manifest.version.length === 0) { + throw new Error(`Codex plugin manifest has no version: ${manifestPath}`); + } + return manifest.version; +} + +export function resolveCodexPluginCacheDirectory( + marketplaceRoot: string, + codexDir: string = CODEX_DIR, +): string { + return path.join( + codexDir, + 'plugins', + 'cache', + MARKETPLACE_NAME, + 'claude-mem', + readCodexPluginVersion(marketplaceRoot), + ); +} + +type CodexPluginCacheInstallOptions = { + codexDir?: string; + runBestEffort?: typeof runCodexBestEffort; + ensureRuntime?: typeof ensureTreeSitterCliBinary; +}; + +export async function installCodexPluginCache( + marketplaceRoot: string, + options: CodexPluginCacheInstallOptions = {}, +): Promise { + const runBestEffort = options.runBestEffort ?? runCodexBestEffort; + const ensureRuntime = options.ensureRuntime ?? ensureTreeSitterCliBinary; + const installed = runBestEffort( + ['plugin', 'add', CODEX_PLUGIN_ID], + 'Installed plugin from the local Codex marketplace.', + 'Could not install claude-mem from the local Codex marketplace', + ); + if (!installed) { + throw new Error('Codex plugin cache could not be installed'); + } + + const codexCacheDir = resolveCodexPluginCacheDirectory( + marketplaceRoot, + options.codexDir, + ); + await ensureRuntime(codexCacheDir); + + // Write the install marker only after the runtime is provisioned, so + // `.install-version` is a truthful "runtime ready" signal rather than an + // optimistic one copied before `plugin add`. Without it, version-check.js + // emits a misleading "runtime not yet set up" hint for a working Codex cache. + writeInstallMarker( + codexCacheDir, + readCodexPluginVersion(marketplaceRoot), + getBunVersion() ?? '', + getUvVersion() ?? '', + ); + console.log(' Smart-explore Tree-sitter runtime ready.'); +} + function lookupCodexOnWindows(): string | null { let stdout: string; try { @@ -481,7 +550,7 @@ export async function installCodexCli(marketplaceRootOverride?: string): Promise } try { - return performCodexInstall(marketplaceRootOverride); + return await performCodexInstall(marketplaceRootOverride); } catch (error) { const message = error instanceof Error ? error.message : String(error); console.error(`\nInstallation failed: ${message}`); @@ -489,18 +558,14 @@ export async function installCodexCli(marketplaceRootOverride?: string): Promise } } -function performCodexInstall(marketplaceRootOverride?: string): number { +async function performCodexInstall(marketplaceRootOverride?: string): Promise { assertCodexMarketplaceSupported(); const marketplaceRoot = resolvePluginMarketplaceRoot(marketplaceRootOverride); console.log(` Registering Codex plugin marketplace: ${marketplaceRoot}`); registerCodexMarketplace(marketplaceRoot); enableCodexPluginConfig(); - runCodexBestEffort( - ['plugin', 'marketplace', 'upgrade', MARKETPLACE_NAME], - 'Refreshed Codex marketplace and installed plugin cache.', - 'Could not refresh Codex marketplace cache; reinstall or upgrade claude-mem from /plugins if Codex still uses old MCP config', - ); + await installCodexPluginCache(marketplaceRoot); if (!cleanupLegacyCodexAgentsMdContext()) { console.warn(` Native Codex hooks registered, but failed to remove legacy AGENTS.md context from ${CODEX_AGENTS_MD_PATH}.`); } diff --git a/src/services/smart-file-read/parser.ts b/src/services/smart-file-read/parser.ts index 3cb196d5c..82bbe3c0a 100644 --- a/src/services/smart-file-read/parser.ts +++ b/src/services/smart-file-read/parser.ts @@ -353,16 +353,27 @@ function getQueryFile(queryKey: string): string { } let cachedBinPath: string | null = null; +let treeSitterCacheDir: string | null = null; function getTreeSitterBin(): string { if (cachedBinPath) return cachedBinPath; try { const pkgPath = _require.resolve("tree-sitter-cli/package.json"); - const binPath = join(dirname(pkgPath), "tree-sitter"); - if (existsSync(binPath)) { - cachedBinPath = binPath; - return binPath; + const pkgDir = dirname(pkgPath); + // tree-sitter-cli's install.js writes `tree-sitter.exe` on Windows and an + // extensionless `tree-sitter` elsewhere. Checking only the extensionless + // name discards a valid Windows binary and falls through to a bare-PATH + // lookup that usually fails, producing silent 0-symbol results (#2910 / #1247). + const candidates = process.platform === "win32" + ? ["tree-sitter.exe", "tree-sitter"] + : ["tree-sitter"]; + for (const name of candidates) { + const binPath = join(pkgDir, name); + if (existsSync(binPath)) { + cachedBinPath = binPath; + return binPath; + } } } catch { // [ANTI-PATTERN IGNORED]: tree-sitter-cli not in node_modules is expected; falls back to PATH @@ -372,6 +383,13 @@ function getTreeSitterBin(): string { return cachedBinPath; } +function getTreeSitterCacheDir(): string { + if (!treeSitterCacheDir) { + treeSitterCacheDir = mkdtempSync(join(tmpdir(), "claude-mem-tree-sitter-cache-")); + } + return treeSitterCacheDir; +} + interface RawCapture { tag: string; startRow: number; @@ -399,7 +417,15 @@ function runBatchQuery(queryFile: string, sourceFiles: string[], grammarPath: st let output: string; try { - output = execFileSync(bin, execArgs, { encoding: "utf-8", timeout: 30000, stdio: ["pipe", "pipe", "pipe"] }); + output = execFileSync(bin, execArgs, { + encoding: "utf-8", + timeout: 30000, + stdio: ["pipe", "pipe", "pipe"], + // `tree-sitter query -p` compiles grammars and writes lock/library files + // below XDG_CACHE_HOME. Agent sandboxes commonly make the user's home + // read-only, so use a process-local writable cache instead. + env: { ...process.env, XDG_CACHE_HOME: getTreeSitterCacheDir() }, + }); } catch (error) { logger.debug('WORKER', `tree-sitter query failed for ${sourceFiles.length} file(s)`, undefined, error instanceof Error ? error : undefined); return new Map(); diff --git a/tests/cli/verify-critical-modules.test.ts b/tests/cli/verify-critical-modules.test.ts index b4965b73b..07c11aa11 100644 --- a/tests/cli/verify-critical-modules.test.ts +++ b/tests/cli/verify-critical-modules.test.ts @@ -1,8 +1,12 @@ import { describe, it, expect, beforeEach, afterEach } from 'bun:test'; -import { mkdirSync, writeFileSync, rmSync } from 'fs'; +import { chmodSync, existsSync, mkdirSync, writeFileSync, rmSync } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; -import { verifyCriticalModules } from '../../src/npx-cli/install/setup-runtime'; +import { + ensureTreeSitterCliBinary, + treeSitterCliBinaryPath, + verifyCriticalModules, +} from '../../src/npx-cli/install/setup-runtime'; /** * Write a fake installed package into /node_modules/. @@ -111,4 +115,66 @@ describe('verifyCriticalModules', () => { expect(() => verifyCriticalModules(tempDir)).not.toThrow(); }); + + it('rejects tree-sitter-cli when its downloaded executable is missing', () => { + writeRootPackage(tempDir, { 'tree-sitter-cli': '^0.26.0' }); + writeFakeBinOnlyPackage(tempDir, 'tree-sitter-cli', 'tree-sitter'); + + expect(() => verifyCriticalModules(tempDir)).toThrow(/tree-sitter-cli executable/); + }); + + it('rejects tree-sitter-cli when its downloaded file is not executable', () => { + if (process.platform === 'win32') return; + + writeRootPackage(tempDir, { 'tree-sitter-cli': '^0.26.0' }); + writeFakeBinOnlyPackage(tempDir, 'tree-sitter-cli', 'tree-sitter'); + const binaryPath = treeSitterCliBinaryPath(tempDir); + writeFileSync(binaryPath, 'not executable'); + chmodSync(binaryPath, 0o644); + + expect(() => verifyCriticalModules(tempDir)).toThrow(/tree-sitter-cli executable/); + }); + + it('rejects tree-sitter-cli when an executable returns invalid version output', () => { + if (process.platform === 'win32') return; + + writeRootPackage(tempDir, { 'tree-sitter-cli': '^0.26.0' }); + writeFakeBinOnlyPackage(tempDir, 'tree-sitter-cli', 'tree-sitter'); + const binaryPath = treeSitterCliBinaryPath(tempDir); + writeFileSync(binaryPath, '#!/bin/sh\necho corrupt-binary\n'); + chmodSync(binaryPath, 0o755); + + expect(() => verifyCriticalModules(tempDir)).toThrow(/tree-sitter-cli executable/); + }); + + it('runs the top-level tree-sitter-cli installer when its executable is missing', async () => { + writeRootPackage(tempDir, { 'tree-sitter-cli': '^0.26.0' }); + writeFakeBinOnlyPackage(tempDir, 'tree-sitter-cli', 'tree-sitter'); + const cliDir = join(tempDir, 'node_modules', 'tree-sitter-cli'); + writeFileSync( + join(cliDir, 'install.js'), + [ + `const fs = require('fs');`, + `const binary = ${JSON.stringify(treeSitterCliBinaryPath(tempDir))};`, + `const contents = process.platform === 'win32' ? 'fixture' : '#!/bin/sh\\necho tree-sitter 0.0.0\\n';`, + `fs.writeFileSync(binary, contents);`, + `if (process.platform !== 'win32') fs.chmodSync(binary, 0o755);`, + '', + ].join('\n'), + ); + + if (process.platform === 'win32') { + await ensureTreeSitterCliBinary( + tempDir, + (targetDir) => existsSync(treeSitterCliBinaryPath(targetDir)), + ); + } else { + await ensureTreeSitterCliBinary(tempDir); + } + + expect(existsSync(treeSitterCliBinaryPath(tempDir))).toBe(true); + if (process.platform !== 'win32') { + expect(() => verifyCriticalModules(tempDir)).not.toThrow(); + } + }); }); diff --git a/tests/install-non-tty.test.ts b/tests/install-non-tty.test.ts index 660c4f331..b07f200e2 100644 --- a/tests/install-non-tty.test.ts +++ b/tests/install-non-tty.test.ts @@ -147,13 +147,18 @@ describe('Install Non-TTY Support', () => { expect(installSource).toContain('installCodexCli(marketplaceDirectory())'); }); - it('refreshes Codex marketplace cache after registration', () => { + it('installs the Codex plugin cache from the registered local marketplace', () => { const installRegion = codexInstallerSource.slice( codexInstallerSource.indexOf('export async function installCodexCli'), codexInstallerSource.indexOf('export function uninstallCodexCli'), ); - expect(installRegion).toContain("['plugin', 'marketplace', 'upgrade', MARKETPLACE_NAME]"); - expect(installRegion).toContain('installed plugin cache'); + const cacheInstallRegion = codexInstallerSource.slice( + codexInstallerSource.indexOf('export async function installCodexPluginCache'), + codexInstallerSource.indexOf('function lookupCodexOnWindows'), + ); + expect(installRegion).toContain('await installCodexPluginCache(marketplaceRoot)'); + expect(cacheInstallRegion).toContain("['plugin', 'add', CODEX_PLUGIN_ID]"); + expect(cacheInstallRegion).not.toContain("['plugin', 'marketplace', 'upgrade', MARKETPLACE_NAME]"); }); it('replaces stale Codex marketplace registrations from a different source', () => { diff --git a/tests/integration/codex-cli-installer.test.ts b/tests/integration/codex-cli-installer.test.ts index e7d7a368c..47f13c3a8 100644 --- a/tests/integration/codex-cli-installer.test.ts +++ b/tests/integration/codex-cli-installer.test.ts @@ -1,10 +1,23 @@ -import { describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, it } from 'bun:test'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; import { + installCodexPluginCache, removeLegacyCodexMcpSearchConfig, + resolveCodexPluginCacheDirectory, setTomlFeatureEnabled, setTomlPluginEnabled, } from '../../src/services/integrations/CodexCliInstaller.js'; +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + describe('Codex CLI installer config repair', () => { it('adds claude-mem plugin enablement when missing', () => { const result = setTomlPluginEnabled('model = "gpt-5.5"\n', 'claude-mem@claude-mem-local', true); @@ -131,4 +144,76 @@ describe('Codex CLI installer config repair', () => { expect(removeLegacyCodexMcpSearchConfig(input)).toBe(input); }); + + it('resolves the Codex cache from the marketplace manifest version', () => { + const root = join(tmpdir(), `codex-marketplace-${Date.now()}-${Math.random()}`); + const codexDir = join(root, 'codex-home'); + const manifestDir = join(root, 'plugin', '.codex-plugin'); + tempDirs.push(root); + mkdirSync(manifestDir, { recursive: true }); + writeFileSync(join(manifestDir, 'plugin.json'), JSON.stringify({ version: '13.9.1+codex.test' })); + + expect(resolveCodexPluginCacheDirectory(root, codexDir)).toBe( + join( + codexDir, + 'plugins', + 'cache', + 'claude-mem-local', + 'claude-mem', + '13.9.1+codex.test', + ), + ); + }); + + it('installs directly from the local marketplace and provisions its runtime', async () => { + const root = join(tmpdir(), `codex-marketplace-${Date.now()}-${Math.random()}`); + const codexDir = join(root, 'codex-home'); + const manifestDir = join(root, 'plugin', '.codex-plugin'); + tempDirs.push(root); + mkdirSync(manifestDir, { recursive: true }); + writeFileSync(join(manifestDir, 'plugin.json'), JSON.stringify({ version: '13.9.1' })); + const cacheDir = join(codexDir, 'plugins', 'cache', 'claude-mem-local', 'claude-mem', '13.9.1'); + const commands: string[][] = []; + const provisioned: string[] = []; + + await installCodexPluginCache(root, { + codexDir, + runBestEffort: (args) => { + commands.push(args); + // `codex plugin add` creates the plugin cache directory by copying the plugin. + mkdirSync(cacheDir, { recursive: true }); + return true; + }, + ensureRuntime: async (targetDir) => { + provisioned.push(targetDir); + }, + }); + + expect(commands).toEqual([ + ['plugin', 'add', 'claude-mem@claude-mem-local'], + ]); + expect(provisioned).toEqual([cacheDir]); + // The install marker is written only after provisioning succeeds, into the + // Codex cache dir — a truthful "runtime ready" signal for version-check.js. + const marker = join(cacheDir, '.install-version'); + expect(existsSync(marker)).toBe(true); + expect(JSON.parse(readFileSync(marker, 'utf-8')).version).toBe('13.9.1'); + }); + + it('fails without provisioning when Codex cannot install the local plugin', async () => { + const root = join(tmpdir(), `codex-marketplace-${Date.now()}-${Math.random()}`); + const manifestDir = join(root, 'plugin', '.codex-plugin'); + tempDirs.push(root); + mkdirSync(manifestDir, { recursive: true }); + writeFileSync(join(manifestDir, 'plugin.json'), JSON.stringify({ version: '13.9.1' })); + let provisioned = false; + + await expect(installCodexPluginCache(root, { + runBestEffort: () => false, + ensureRuntime: async () => { + provisioned = true; + }, + })).rejects.toThrow(/cache could not be installed/); + expect(provisioned).toBe(false); + }); }); diff --git a/tests/services/smart-file-read/parser.test.ts b/tests/services/smart-file-read/parser.test.ts new file mode 100644 index 000000000..e46d444b2 --- /dev/null +++ b/tests/services/smart-file-read/parser.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'bun:test'; +import { parseFile } from '../../../src/services/smart-file-read/parser.js'; + +describe('smart file parser', () => { + it('extracts TypeScript symbols when the user cache is not writable', () => { + const previousCacheHome = process.env.XDG_CACHE_HOME; + process.env.XDG_CACHE_HOME = '/dev/null/claude-mem-unwritable-cache'; + + try { + const parsed = parseFile( + [ + 'export function smartExploreProbe(value: string): string {', + ' return value;', + '}', + '', + 'export class ProbeClass {', + ' run(): boolean {', + ' return true;', + ' }', + '}', + ].join('\n'), + 'smart-explore-fixture.ts', + process.cwd(), + ); + + expect(parsed.symbols.map((symbol) => symbol.name)).toEqual([ + 'smartExploreProbe', + 'ProbeClass', + ]); + expect(parsed.symbols[1]?.children?.map((symbol) => symbol.name)).toEqual(['run']); + } finally { + if (previousCacheHome === undefined) delete process.env.XDG_CACHE_HOME; + else process.env.XDG_CACHE_HOME = previousCacheHome; + } + }); +}); From 65b90cb586fb819caaec96b793dd146922e863c1 Mon Sep 17 00:00:00 2001 From: Ryan Malia Date: Tue, 30 Jun 2026 20:00:25 -0700 Subject: [PATCH 2/2] fix(install): repair stale-cache bypass and add Windows resolver tests Address review feedback on #3095: - isInstallCurrent treated a cache as current from node_modules + marker + version + Bun state alone, so a same-version cache with .install-version but a missing or broken tree-sitter-cli executable skipped installPluginDependencies and left smart-explore broken. Fail the fast path when the plugin declares tree-sitter-cli but its binary is unusable, forcing re-provisioning. (Reported by greptile.) - Make getTreeSitterBin injectable and port #2918's Windows resolver tests so the tree-sitter.exe / bare-PATH / non-Windows branches are actually covered. Regenerate the MCP server bundle. Co-authored-by: Alex V. <119082209+Retengart@users.noreply.github.com> --- plugin/scripts/mcp-server.cjs | 104 +++++++++--------- src/npx-cli/install/setup-runtime.ts | 24 +++- src/services/smart-file-read/parser.ts | 61 +++++++--- .../smart-file-read/tree-sitter-bin.test.ts | 62 +++++++++++ tests/setup-runtime.test.ts | 17 +++ 5 files changed, 198 insertions(+), 70 deletions(-) create mode 100644 tests/services/smart-file-read/tree-sitter-bin.test.ts diff --git a/plugin/scripts/mcp-server.cjs b/plugin/scripts/mcp-server.cjs index 908314232..f7d1e9518 100755 --- a/plugin/scripts/mcp-server.cjs +++ b/plugin/scripts/mcp-server.cjs @@ -1,61 +1,61 @@ #!/usr/bin/env node -"use strict";var ey=Object.create;var Bs=Object.defineProperty;var ty=Object.getOwnPropertyDescriptor;var ry=Object.getOwnPropertyNames;var ny=Object.getPrototypeOf,oy=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Lu=(t,e)=>{for(var r in e)Bs(t,r,{get:e[r],enumerable:!0})},sy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ry(e))!oy.call(t,o)&&o!==r&&Bs(t,o,{get:()=>e[o],enumerable:!(n=ty(e,o))||n.enumerable});return t};var xt=(t,e,r)=>(r=t!=null?ey(ny(t)):{},sy(e||!t||!t.__esModule?Bs(r,"default",{value:t,enumerable:!0}):r,t));var _n=w(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.regexpCode=F.getEsmExportName=F.getProperty=F.safeStringify=F.stringify=F.strConcat=F.addCodeArg=F.str=F._=F.nil=F._Code=F.Name=F.IDENTIFIER=F._CodeOrName=void 0;var hn=class{};F._CodeOrName=hn;F.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wt=class extends hn{constructor(e){if(super(),!F.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};F.Name=Wt;var qe=class extends hn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Wt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};F._Code=qe;F.nil=new qe("");function im(t,...e){let r=[t[0]],n=0;for(;n{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.ValueScope=Re.ValueScopeName=Re.Scope=Re.varKinds=Re.UsedValueState=void 0;var ze=_n(),_a=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Fo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Fo||(Re.UsedValueState=Fo={}));Re.varKinds={const:new ze.Name("const"),let:new ze.Name("let"),var:new ze.Name("var")};var Ho=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ze.Name?e:this.name(e)}name(e){return new ze.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Re.Scope=Ho;var Wo=class extends ze.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ze._)`.${new ze.Name(r)}[${n}]`}};Re.ValueScopeName=Wo;var Hb=(0,ze._)`\n`,ya=class extends Ho{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Hb:ze.nil}}get(){return this._scope}name(e){return new Wo(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ze._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=ze.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Fo.Started);let l=r(u);if(l){let d=this.opts.es5?Re.varKinds.var:Re.varKinds.const;s=(0,ze._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,ze._)`${s}${l}${this.opts._n}`;else throw new _a(u);c.set(u,Fo.Completed)})}return s}};Re.ValueScope=ya});var O=w(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var j=_n(),Ye=Sa(),Ot=_n();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Ot._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Ot.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return Ot.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Ot.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return Ot.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Ot.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return Ot.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Ot.Name}});var Jo=Sa();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return Jo.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return Jo.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return Jo.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return Jo.varKinds}});M.operators={GT:new j._Code(">"),GTE:new j._Code(">="),LT:new j._Code("<"),LTE:new j._Code("<="),EQ:new j._Code("==="),NEQ:new j._Code("!=="),NOT:new j._Code("!"),OR:new j._Code("||"),AND:new j._Code("&&"),ADD:new j._Code("+")};var gt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},va=class extends gt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ye.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=gr(this.rhs,e,r)),this}get names(){return this.rhs instanceof j._CodeOrName?this.rhs.names:{}}},Vo=class extends gt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof j.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=gr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof j.Name?{}:{...this.lhs.names};return Go(e,this.rhs)}},ba=class extends Vo{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ea=class extends gt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wa=class extends gt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ka=class extends gt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},xa=class extends gt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=gr(this.code,e,r),this}get names(){return this.code instanceof j._CodeOrName?this.code.names:{}}},yn=class extends gt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Wb(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Gt(e,r.names),{})}},_t=class extends yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$a=class extends yn{},hr=class extends _t{};hr.kind="else";var Vt=class t extends _t{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new hr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(cm(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=gr(this.condition,e,r),this}get names(){let e=super.names;return Go(e,this.condition),this.else&&Gt(e,this.else.names),e}};Vt.kind="if";var Kt=class extends _t{};Kt.kind="for";var Pa=class extends Kt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=gr(this.iteration,e,r),this}get names(){return Gt(super.names,this.iteration.names)}},Ta=class extends Kt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ye.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Go(super.names,this.from);return Go(e,this.to)}},Ko=class extends Kt{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=gr(this.iterable,e,r),this}get names(){return Gt(super.names,this.iterable.names)}},Sn=class extends _t{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Sn.kind="func";var vn=class extends yn{render(e){return"return "+super.render(e)}};vn.kind="return";var za=class extends _t{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Gt(e,this.catch.names),this.finally&&Gt(e,this.finally.names),e}},bn=class extends _t{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};bn.kind="catch";var En=class extends _t{render(e){return"finally"+super.render(e)}};En.kind="finally";var Ra=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` -`:""},this._extScope=e,this._scope=new Ye.Scope({parent:e}),this._nodes=[new $a]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new va(e,s,n)),s}const(e,r,n){return this._def(Ye.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ye.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ye.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Vo(e,r,n))}add(e,r){return this._leafNode(new ba(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==j.nil&&this._leafNode(new xa(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,j.addCodeArg)(r,o));return r.push("}"),new j._Code(r)}if(e,r,n){if(this._blockNode(new Vt(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vt(e))}else(){return this._elseNode(new hr)}endIf(){return this._endBlockNode(Vt,hr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Pa(e),r)}forRange(e,r,n,o,s=this.opts.es5?Ye.varKinds.var:Ye.varKinds.let){let i=this._scope.toName(e);return this._for(new Ta(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Ye.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof j.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,j._)`${i}.length`,a=>{this.var(s,(0,j._)`${i}[${a}]`),n(s)})}return this._for(new Ko("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,j._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ko("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kt)}label(e){return this._leafNode(new Ea(e))}break(e){return this._leafNode(new wa(e))}return(e){let r=new vn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(vn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new za;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new bn(s),r(s)}return n&&(this._currNode=o.finally=new En,this.code(n)),this._endBlockNode(bn,En)}throw(e){return this._leafNode(new ka(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=j.nil,n,o){return this._blockNode(new Sn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Sn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=Ra;function Gt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Go(t,e){return e instanceof j._CodeOrName?Gt(t,e.names):t}function gr(t,e,r){if(t instanceof j.Name)return n(t);if(!o(t))return t;return new j._Code(t._items.reduce((s,i)=>(i instanceof j.Name&&(i=n(i)),i instanceof j._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof j._Code&&s._items.some(i=>i instanceof j.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Wb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function cm(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,j._)`!${Ia(t)}`}M.not=cm;var Vb=um(M.operators.AND);function Kb(...t){return t.reduce(Vb)}M.and=Kb;var Gb=um(M.operators.OR);function Jb(...t){return t.reduce(Gb)}M.or=Jb;function um(t){return(e,r)=>e===j.nil?r:r===j.nil?e:(0,j._)`${Ia(e)} ${t} ${Ia(r)}`}function Ia(t){return t instanceof j.Name?t:(0,j._)`(${t})`}});var q=w(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var K=O(),Yb=_n();function Bb(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=Bb;function Xb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pm(t,e),!fm(e,t.self.RULES.all))}C.alwaysValidSchema=Xb;function pm(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||gm(t,`unknown keyword: "${s}"`)}C.checkUnknownRules=pm;function fm(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=fm;function Qb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Qb;function eE({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${t}${e}${(0,K.getProperty)(n)}`}C.schemaRefOrVal=eE;function tE(t){return mm(decodeURIComponent(t))}C.unescapeFragment=tE;function rE(t){return encodeURIComponent(Oa(t))}C.escapeFragment=rE;function Oa(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Oa;function mm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=mm;function nE(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=nE;function lm({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof K.Name?(s instanceof K.Name?t(o,s,i):e(o,s,i),i):s instanceof K.Name?(e(o,i,s),s):r(s,i);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}C.mergeEvaluated={props:lm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,K._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,K._)`${r} || {}`),Ma(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:hm}),items:lm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,K._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,K._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function hm(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,K._)`{}`);return e!==void 0&&Ma(t,r,e),r}C.evaluatedPropsToName=hm;function Ma(t,e,r){Object.keys(r).forEach(n=>t.assign((0,K._)`${e}${(0,K.getProperty)(n)}`,!0))}C.setEvaluated=Ma;var dm={};function oE(t,e){return t.scopeValue("func",{ref:e,code:dm[e.code]||(dm[e.code]=new Yb._Code(e.code))})}C.useFunc=oE;var Aa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Aa||(C.Type=Aa={}));function sE(t,e,r){if(t instanceof K.Name){let n=e===Aa.Num;return r?n?(0,K._)`"[" + ${t} + "]"`:(0,K._)`"['" + ${t} + "']"`:n?(0,K._)`"/" + ${t}`:(0,K._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(t).toString():"/"+Oa(t)}C.getErrorPath=sE;function gm(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=gm});var yt=w(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var ve=O(),iE={data:new ve.Name("data"),valCxt:new ve.Name("valCxt"),instancePath:new ve.Name("instancePath"),parentData:new ve.Name("parentData"),parentDataProperty:new ve.Name("parentDataProperty"),rootData:new ve.Name("rootData"),dynamicAnchors:new ve.Name("dynamicAnchors"),vErrors:new ve.Name("vErrors"),errors:new ve.Name("errors"),this:new ve.Name("this"),self:new ve.Name("self"),scope:new ve.Name("scope"),json:new ve.Name("json"),jsonPos:new ve.Name("jsonPos"),jsonLen:new ve.Name("jsonLen"),jsonPart:new ve.Name("jsonPart")};Ca.default=iE});var wn=w(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.extendErrors=be.resetErrorsCount=be.reportExtraError=be.reportError=be.keyword$DataError=be.keywordError=void 0;var Z=O(),Yo=q(),$e=yt();be.keywordError={message:({keyword:t})=>(0,Z.str)`must pass "${t}" keyword validation`};be.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Z.str)`"${t}" keyword must be ${e} ($data)`:(0,Z.str)`"${t}" keyword is invalid ($data)`};function aE(t,e=be.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Sm(t,e,r);n??(i||a)?_m(s,c):ym(o,(0,Z._)`[${c}]`)}be.reportError=aE;function cE(t,e=be.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Sm(t,e,r);_m(o,a),s||i||ym(n,$e.default.vErrors)}be.reportExtraError=cE;function uE(t,e){t.assign($e.default.errors,e),t.if((0,Z._)`${$e.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Z._)`${$e.default.vErrors}.length`,e),()=>t.assign($e.default.vErrors,null)))}be.resetErrorsCount=uE;function lE({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,$e.default.errors,a=>{t.const(i,(0,Z._)`${$e.default.vErrors}[${a}]`),t.if((0,Z._)`${i}.instancePath === undefined`,()=>t.assign((0,Z._)`${i}.instancePath`,(0,Z.strConcat)($e.default.instancePath,s.errorPath))),t.assign((0,Z._)`${i}.schemaPath`,(0,Z.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Z._)`${i}.schema`,r),t.assign((0,Z._)`${i}.data`,n))})}be.extendErrors=lE;function _m(t,e){let r=t.const("err",e);t.if((0,Z._)`${$e.default.vErrors} === null`,()=>t.assign($e.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${$e.default.vErrors}.push(${r})`),t.code((0,Z._)`${$e.default.errors}++`)}function ym(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Z._)`new ${t.ValidationError}(${e})`):(r.assign((0,Z._)`${n}.errors`,e),r.return(!1))}var Jt={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Sm(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Z._)`{}`:dE(t,e,r)}function dE(t,e,r={}){let{gen:n,it:o}=t,s=[pE(o,r),fE(t,r)];return mE(t,e,s),n.object(...s)}function pE({errorPath:t},{instancePath:e}){let r=e?(0,Z.str)`${t}${(0,Yo.getErrorPath)(e,Yo.Type.Str)}`:t;return[$e.default.instancePath,(0,Z.strConcat)($e.default.instancePath,r)]}function fE({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Z.str)`${e}/${t}`;return r&&(o=(0,Z.str)`${o}${(0,Yo.getErrorPath)(r,Yo.Type.Str)}`),[Jt.schemaPath,o]}function mE(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Jt.keyword,o],[Jt.params,typeof e=="function"?e(t):e||(0,Z._)`{}`]),c.messages&&n.push([Jt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Jt.schema,i],[Jt.parentSchema,(0,Z._)`${l}${d}`],[$e.default.data,s]),u&&n.push([Jt.propertyName,u])}});var bm=w(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.boolOrEmptySchema=_r.topBoolOrEmptySchema=void 0;var hE=wn(),gE=O(),_E=yt(),yE={message:"boolean schema is false"};function SE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?vm(t,!1):typeof r=="object"&&r.$async===!0?e.return(_E.default.data):(e.assign((0,gE._)`${n}.errors`,null),e.return(!0))}_r.topBoolOrEmptySchema=SE;function vE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),vm(t)):r.var(e,!0)}_r.boolOrEmptySchema=vE;function vm(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,hE.reportError)(o,yE,void 0,e)}});var Na=w(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.getRules=yr.isJSONType=void 0;var bE=["string","number","integer","boolean","null","object","array"],EE=new Set(bE);function wE(t){return typeof t=="string"&&EE.has(t)}yr.isJSONType=wE;function kE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}yr.getRules=kE});var Da=w(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.shouldUseRule=Mt.shouldUseGroup=Mt.schemaHasRulesForType=void 0;function xE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Em(t,n)}Mt.schemaHasRulesForType=xE;function Em(t,e){return e.rules.some(r=>wm(t,r))}Mt.shouldUseGroup=Em;function wm(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mt.shouldUseRule=wm});var kn=w(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.reportTypeError=Ee.checkDataTypes=Ee.checkDataType=Ee.coerceAndCheckDataType=Ee.getJSONTypes=Ee.getSchemaTypes=Ee.DataType=void 0;var $E=Na(),PE=Da(),TE=wn(),A=O(),km=q(),Sr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Sr||(Ee.DataType=Sr={}));function zE(t){let e=xm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ee.getSchemaTypes=zE;function xm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($E.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ee.getJSONTypes=xm;function RE(t,e){let{gen:r,data:n,opts:o}=t,s=IE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,PE.schemaHasRulesForType)(t,e[0]));if(i){let a=La(e,n,o.strictNumbers,Sr.Wrong);r.if(a,()=>{s.length?AE(t,e,s):Ua(t)})}return i}Ee.coerceAndCheckDataType=RE;var $m=new Set(["string","number","integer","boolean","null"]);function IE(t,e){return e?t.filter(r=>$m.has(r)||e==="array"&&r==="array"):[]}function AE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,A._)`typeof ${o}`),a=n.let("coerced",(0,A._)`undefined`);s.coerceTypes==="array"&&n.if((0,A._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,A._)`${o}[0]`).assign(i,(0,A._)`typeof ${o}`).if(La(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,A._)`${a} !== undefined`);for(let u of r)($m.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ua(t),n.endIf(),n.if((0,A._)`${a} !== undefined`,()=>{n.assign(o,a),OE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,A._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":n.elseIf((0,A._)`${i} == "boolean" || ${o} === null - || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":n.elseIf((0,A._)`${i} === "boolean" || ${o} === null - || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":n.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,A._)`${i} === "string" || ${i} === "number" - || ${i} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function OE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,A._)`${e} !== undefined`,()=>t.assign((0,A._)`${e}[${r}]`,n))}function ja(t,e,r,n=Sr.Correct){let o=n===Sr.Correct?A.operators.EQ:A.operators.NEQ,s;switch(t){case"null":return(0,A._)`${e} ${o} null`;case"array":s=(0,A._)`Array.isArray(${e})`;break;case"object":s=(0,A._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,A._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,A._)`typeof ${e} ${o} ${t}`}return n===Sr.Correct?s:(0,A.not)(s);function i(a=A.nil){return(0,A.and)((0,A._)`typeof ${e} == "number"`,a,r?(0,A._)`isFinite(${e})`:A.nil)}}Ee.checkDataType=ja;function La(t,e,r,n){if(t.length===1)return ja(t[0],e,r,n);let o,s=(0,km.toHash)(t);if(s.array&&s.object){let i=(0,A._)`typeof ${e} != "object"`;o=s.null?i:(0,A._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=A.nil;s.number&&delete s.integer;for(let i in s)o=(0,A.and)(o,ja(i,e,r,n));return o}Ee.checkDataTypes=La;var ME={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,A._)`{type: ${t}}`:(0,A._)`{type: ${e}}`};function Ua(t){let e=CE(t);(0,TE.reportError)(e,ME)}Ee.reportTypeError=Ua;function CE(t){let{gen:e,data:r,schema:n}=t,o=(0,km.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Tm=w(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.assignDefaults=void 0;var vr=O(),NE=q();function DE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Pm(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Pm(t,s,o.default))}Bo.assignDefaults=DE;function Pm(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vr._)`${s}${(0,vr.getProperty)(e)}`;if(o){(0,NE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vr._)`${a} = ${(0,vr.stringify)(r)}`)}});var Ze=w(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.validateUnion=V.validateArray=V.usePattern=V.callValidateCode=V.schemaProperties=V.allSchemaProperties=V.noPropertyInData=V.propertyInData=V.isOwnProperty=V.hasPropFunc=V.reportMissingProp=V.checkMissingProp=V.checkReportMissingProp=void 0;var X=O(),qa=q(),Ct=yt(),jE=q();function LE(t,e){let{gen:r,data:n,it:o}=t;r.if(Fa(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,X._)`${e}`},!0),t.error()})}V.checkReportMissingProp=LE;function UE({gen:t,data:e,it:{opts:r}},n,o){return(0,X.or)(...n.map(s=>(0,X.and)(Fa(t,e,s,r.ownProperties),(0,X._)`${o} = ${s}`)))}V.checkMissingProp=UE;function qE(t,e){t.setParams({missingProperty:e},!0),t.error()}V.reportMissingProp=qE;function zm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}V.hasPropFunc=zm;function Za(t,e,r){return(0,X._)`${zm(t)}.call(${e}, ${r})`}V.isOwnProperty=Za;function ZE(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Za(t,e,r)}`:o}V.propertyInData=ZE;function Fa(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Za(t,e,r))):o}V.noPropertyInData=Fa;function Rm(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}V.allSchemaProperties=Rm;function FE(t,e){return Rm(e).filter(r=>!(0,qa.alwaysValidSchema)(t,e[r]))}V.schemaProperties=FE;function HE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,X._)`${t}, ${e}, ${n}${o}`:e,d=[[Ct.default.instancePath,(0,X.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let p=(0,X._)`${l}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${p})`:(0,X._)`${a}(${p})`}V.callValidateCode=HE;var WE=(0,X._)`new RegExp`;function VE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,X._)`${o.code==="new RegExp"?WE:(0,jE.useFunc)(t,o)}(${r}, ${n})`})}V.usePattern=VE;function KE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,X._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:qa.Type.Num},s),e.if((0,X.not)(s),a)})}}V.validateArray=KE;function GE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,qa.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,X._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,X.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}V.validateUnion=GE});var Om=w(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.validateKeywordUsage=nt.validSchemaType=nt.funcKeywordCode=nt.macroKeywordCode=void 0;var Pe=O(),Yt=yt(),JE=Ze(),YE=wn();function BE(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Am(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Pe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}nt.macroKeywordCode=BE;function XE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;ew(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Am(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)_(),e.modifying&&Im(t),S(()=>t.error());else{let b=e.async?f():m();e.modifying&&Im(t),S(()=>QE(t,b))}}function f(){let b=n.let("ruleErrs",null);return n.try(()=>_((0,Pe._)`await `),E=>n.assign(d,!1).if((0,Pe._)`${E} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,Pe._)`${E}.errors`),()=>n.throw(E))),b}function m(){let b=(0,Pe._)`${l}.errors`;return n.assign(b,null),_(Pe.nil),b}function _(b=e.async?(0,Pe._)`await `:Pe.nil){let E=c.opts.passContext?Yt.default.this:Yt.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Pe._)`${b}${(0,JE.callValidateCode)(t,l,E,v)}`,e.modifying)}function S(b){var E;n.if((0,Pe.not)((E=e.valid)!==null&&E!==void 0?E:d),b)}}nt.funcKeywordCode=XE;function Im(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Pe._)`${n.parentData}[${n.parentDataProperty}]`))}function QE(t,e){let{gen:r}=t;r.if((0,Pe._)`Array.isArray(${e})`,()=>{r.assign(Yt.default.vErrors,(0,Pe._)`${Yt.default.vErrors} === null ? ${e} : ${Yt.default.vErrors}.concat(${e})`).assign(Yt.default.errors,(0,Pe._)`${Yt.default.vErrors}.length`),(0,YE.extendErrors)(t)},()=>t.error())}function ew({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Am(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Pe.stringify)(r)})}function tw(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}nt.validSchemaType=tw;function rw({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}nt.validateKeywordUsage=rw});var Cm=w(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var ot=O(),Mm=q();function nw(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}${(0,ot.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Mm.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Nt.getSubschema=nw;function ow(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,ot._)`${e.data}${(0,ot.getProperty)(r)}`,!0);c(p),t.errorPath=(0,ot.str)`${u}${(0,Mm.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,ot._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof ot.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Nt.extendSubschemaData=ow;function sw(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Nt.extendSubschemaMode=sw});var Ha=w((xM,Nm)=>{"use strict";Nm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var jm=w(($M,Dm)=>{"use strict";var Dt=Dm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Xo(e,n,o,t,"",t)};Dt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Dt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Dt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Dt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Xo(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Dt.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.getSchemaRefs=Ie.resolveUrl=Ie.normalizeId=Ie._getFullPath=Ie.getFullPath=Ie.inlineRef=void 0;var aw=q(),cw=Ha(),uw=jm(),lw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function dw(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wa(t):e?Lm(t)<=e:!1}Ie.inlineRef=dw;var pw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wa(t){for(let e in t){if(pw.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Wa)||typeof r=="object"&&Wa(r))return!0}return!1}function Lm(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!lw.has(r)&&(typeof t[r]=="object"&&(0,aw.eachItem)(t[r],n=>e+=Lm(n)),e===1/0))return 1/0}return e}function Um(t,e="",r){r!==!1&&(e=br(e));let n=t.parse(e);return qm(t,n)}Ie.getFullPath=Um;function qm(t,e){return t.serialize(e).split("#")[0]+"#"}Ie._getFullPath=qm;var fw=/#\/?$/;function br(t){return t?t.replace(fw,""):""}Ie.normalizeId=br;function mw(t,e,r){return r=br(r),t.resolve(e,r)}Ie.resolveUrl=mw;var hw=/^[a-z_][-a-z0-9._]*$/i;function gw(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=br(t[r]||e),s={"":o},i=Um(n,o,!1),a={},c=new Set;return uw(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let _=i+p,S=s[m];typeof d[r]=="string"&&(S=b.call(this,d[r])),E.call(this,d.$anchor),E.call(this,d.$dynamicAnchor),s[p]=S;function b(v){let $=this.opts.uriResolver.resolve;if(v=br(S?$(S,v):v),c.has(v))throw l(v);c.add(v);let x=this.refs[v];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,v):v!==br(_)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=_),v}function E(v){if(typeof v=="string"){if(!hw.test(v))throw new Error(`invalid anchor "${v}"`);b.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!cw(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ie.getSchemaRefs=gw});var Tn=w(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.getData=jt.KeywordCxt=jt.validateFunctionCode=void 0;var Vm=bm(),Zm=kn(),Ka=Da(),Qo=kn(),_w=Tm(),Pn=Om(),Va=Cm(),T=O(),R=yt(),yw=xn(),St=q(),$n=wn();function Sw(t){if(Jm(t)&&(Ym(t),Gm(t))){Ew(t);return}Km(t,()=>(0,Vm.topBoolOrEmptySchema)(t))}jt.validateFunctionCode=Sw;function Km({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${R.default.data}, ${R.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Fm(r,o)}`),bw(t,o),t.code(s)}):t.func(e,(0,T._)`${R.default.data}, ${vw(o)}`,n.$async,()=>t.code(Fm(r,o)).code(s))}function vw(t){return(0,T._)`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${t.dynamicRef?(0,T._)`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function bw(t,e){t.if(R.default.valCxt,()=>{t.var(R.default.instancePath,(0,T._)`${R.default.valCxt}.${R.default.instancePath}`),t.var(R.default.parentData,(0,T._)`${R.default.valCxt}.${R.default.parentData}`),t.var(R.default.parentDataProperty,(0,T._)`${R.default.valCxt}.${R.default.parentDataProperty}`),t.var(R.default.rootData,(0,T._)`${R.default.valCxt}.${R.default.rootData}`),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{t.var(R.default.instancePath,(0,T._)`""`),t.var(R.default.parentData,(0,T._)`undefined`),t.var(R.default.parentDataProperty,(0,T._)`undefined`),t.var(R.default.rootData,R.default.data),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`{}`)})}function Ew(t){let{schema:e,opts:r,gen:n}=t;Km(t,()=>{r.$comment&&e.$comment&&Xm(t),Pw(t),n.let(R.default.vErrors,null),n.let(R.default.errors,0),r.unevaluated&&ww(t),Bm(t),Rw(t)})}function ww(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function Fm(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function kw(t,e){if(Jm(t)&&(Ym(t),Gm(t))){xw(t,e);return}(0,Vm.boolOrEmptySchema)(t,e)}function Gm({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Jm(t){return typeof t.schema!="boolean"}function xw(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Xm(t),Tw(t),zw(t);let s=n.const("_errs",R.default.errors);Bm(t,s),n.var(e,(0,T._)`${s} === ${R.default.errors}`)}function Ym(t){(0,St.checkUnknownRules)(t),$w(t)}function Bm(t,e){if(t.opts.jtd)return Hm(t,[],!1,e);let r=(0,Zm.getSchemaTypes)(t.schema),n=(0,Zm.coerceAndCheckDataType)(t,r);Hm(t,r,!n,e)}function $w(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,St.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Pw(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,St.checkStrictMode)(t,"default is ignored in the schema root")}function Tw(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,yw.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zw(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Xm({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${R.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${R.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Rw(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${R.default.errors} === 0`,()=>e.return(R.default.data),()=>e.throw((0,T._)`new ${o}(${R.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,R.default.vErrors),s.unevaluated&&Iw(t),e.return((0,T._)`${R.default.errors} === 0`))}function Iw({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function Hm(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,St.schemaHasRulesButRef)(s,l))){o.block(()=>eh(t,"$ref",l.all.$ref.definition));return}c.jtd||Aw(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Ka.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Qo.checkDataType)(p.type,i,c.strictNumbers)),Wm(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Qo.reportTypeError)(t)),o.endIf()):Wm(t,p),a||o.if((0,T._)`${R.default.errors} === ${n||0}`))}}function Wm(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,_w.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ka.shouldUseRule)(n,s)&&eh(t,s.keyword,s.definition,e.type)})}function Aw(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ow(t,e),t.opts.allowUnionTypes||Mw(t,e),Cw(t,t.dataTypes))}function Ow(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Qm(t.dataTypes,r)||Ga(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dw(t,e)}}function Mw(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ga(t,"use allowUnionTypes to allow union type keyword")}function Cw(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ka.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Nw(e,i))&&Ga(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Nw(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Qm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dw(t,e){let r=[];for(let n of t.dataTypes)Qm(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ga(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,St.checkStrictMode)(t,e,t.opts.strictTypes)}var es=class{constructor(e,r,n){if((0,Pn.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,St.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",th(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Pn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",R.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?$n.reportExtraError:$n.reportError)(this,this.def.error,r)}$dataError(){(0,$n.reportError)(this,this.def.$dataError||$n.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$n.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Qo.checkDataTypes)(c,r,s.opts.strictNumbers,Qo.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,Va.getSubschema)(this.it,e);(0,Va.extendSubschemaData)(n,this.it,e),(0,Va.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return kw(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=St.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=St.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};jt.KeywordCxt=es;function eh(t,e,r,n){let o=new es(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Pn.funcKeywordCode)(o,r):"macro"in r?(0,Pn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Pn.funcKeywordCode)(o,r)}var jw=/^\/(?:[^~]|~0|~1)*$/,Lw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function th(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return R.default.rootData;if(t[0]==="/"){if(!jw.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=R.default.rootData}else{let u=Lw.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,St.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}jt.getData=th});var ts=w(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Ja=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ya.default=Ja});var zn=w(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Ba=xn(),Xa=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ba.resolveUrl)(e,r,n),this.missingSchema=(0,Ba.normalizeId)((0,Ba.getFullPath)(e,this.missingRef))}};Qa.default=Xa});var ns=w(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Be=O(),Uw=ts(),Bt=yt(),Xe=xn(),rh=q(),qw=Tn(),Er=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Xe.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Fe.SchemaEnv=Er;function tc(t){let e=nh.call(this,t);if(e)return e;let r=(0,Xe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Be.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Uw.default,code:(0,Be._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Bt.default.data,parentData:Bt.default.parentData,parentDataProperty:Bt.default.parentDataProperty,dataNames:[Bt.default.data],dataPathArr:[Be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Be.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Be._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,qw.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Bt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Bt.default.self}`,`${Bt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:_}=u;f.evaluated={props:m instanceof Be.Name?void 0:m,items:_ instanceof Be.Name?void 0:_,dynamicProps:m instanceof Be.Name,dynamicItems:_ instanceof Be.Name},f.source&&(f.source.evaluated=(0,Be.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Fe.compileSchema=tc;function Zw(t,e,r){var n;r=(0,Xe.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Ww.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Er({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Fw.call(this,s)}Fe.resolveRef=Zw;function Fw(t){return(0,Xe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:tc.call(this,t)}function nh(t){for(let e of this._compilations)if(Hw(e,t))return e}Fe.getCompilingSchema=nh;function Hw(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Ww(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||rs.call(this,t,e)}function rs(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Xe._getFullPath)(this.opts.uriResolver,r),o=(0,Xe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ec.call(this,r,t);let s=(0,Xe.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=rs.call(this,t,i);return typeof a?.schema!="object"?void 0:ec.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||tc.call(this,i),s===(0,Xe.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Xe.resolveUrl)(this.opts.uriResolver,o,u)),new Er({schema:a,schemaId:c,root:t,baseId:o})}return ec.call(this,r,i)}}Fe.resolveSchema=rs;var Vw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ec(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,rh.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Vw.has(a)&&u&&(e=(0,Xe.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,rh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Xe.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=rs.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Er({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var oh=w((AM,Kw)=>{Kw.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var nc=w((OM,ch)=>{"use strict";var Gw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ih=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 rc(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Jw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function sh(t){return t.length=0,!0}function Yw(t,e,r){if(t.length){let n=rc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Bw(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Yw;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=sh}else{o.push(u);continue}}return o.length&&(a===sh?r.zone=o.join(""):i?n.push(o.join("")):n.push(rc(o))),r.address=n.join(""),r}function ah(t){if(Xw(t,":")<2)return{host:t,isIPV6:!1};let e=Bw(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Xw(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:rk}=nc(),nk=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ok=["http","https","ws","wss","urn","urn:uuid"];function sk(t){return ok.indexOf(t)!==-1}function oc(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function uh(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function lh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ik(t){return t.secure=oc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ak(t){if((t.port===(oc(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function ck(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(nk);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=sc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uk(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=sc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function lk(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!rk(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function dk(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var dh={scheme:"http",domainHost:!0,parse:uh,serialize:lh},pk={scheme:"https",domainHost:dh.domainHost,parse:uh,serialize:lh},os={scheme:"ws",domainHost:!0,parse:ik,serialize:ak},fk={scheme:"wss",domainHost:os.domainHost,parse:os.parse,serialize:os.serialize},mk={scheme:"urn",parse:ck,serialize:uk,skipNormalize:!0},hk={scheme:"urn:uuid",parse:lk,serialize:dk,skipNormalize:!0},ss={http:dh,https:pk,ws:os,wss:fk,urn:mk,"urn:uuid":hk};Object.setPrototypeOf(ss,null);function sc(t){return t&&(ss[t]||ss[t.toLowerCase()])||void 0}ph.exports={wsIsSecure:oc,SCHEMES:ss,isValidSchemeName:sk,getSchemeHandler:sc}});var gh=w((CM,as)=>{"use strict";var{normalizeIPv6:gk,removeDotSegments:Rn,recomposeAuthority:_k,normalizeComponentEncoding:is,isIPv4:yk,nonSimpleDomain:Sk}=nc(),{SCHEMES:vk,getSchemeHandler:mh}=fh();function bk(t,e){return typeof t=="string"?t=st(vt(t,e),e):typeof t=="object"&&(t=vt(st(t,e),e)),t}function Ek(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=hh(vt(t,n),vt(e,n),n,!0);return n.skipEscape=!0,st(o,n)}function hh(t,e,r,n){let o={};return n||(t=vt(st(t,r),r),e=vt(st(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Rn(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Rn(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Rn(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Rn(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function wk(t,e,r){return typeof t=="string"?(t=unescape(t),t=st(is(vt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=st(is(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=st(is(vt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=st(is(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function st(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=mh(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=_k(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Rn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var kk=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function vt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(kk);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(yk(n.host)===!1){let c=gk(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=mh(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&Sk(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var ic={SCHEMES:vk,normalize:bk,resolve:Ek,resolveComponent:hh,equal:wk,serialize:st,parse:vt};as.exports=ic;as.exports.default=ic;as.exports.fastUri=ic});var yh=w(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var _h=gh();_h.code='require("ajv/dist/runtime/uri").default';ac.default=_h});var $h=w(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.CodeGen=_e.Name=_e.nil=_e.stringify=_e.str=_e._=_e.KeywordCxt=void 0;var xk=Tn();Object.defineProperty(_e,"KeywordCxt",{enumerable:!0,get:function(){return xk.KeywordCxt}});var wr=O();Object.defineProperty(_e,"_",{enumerable:!0,get:function(){return wr._}});Object.defineProperty(_e,"str",{enumerable:!0,get:function(){return wr.str}});Object.defineProperty(_e,"stringify",{enumerable:!0,get:function(){return wr.stringify}});Object.defineProperty(_e,"nil",{enumerable:!0,get:function(){return wr.nil}});Object.defineProperty(_e,"Name",{enumerable:!0,get:function(){return wr.Name}});Object.defineProperty(_e,"CodeGen",{enumerable:!0,get:function(){return wr.CodeGen}});var $k=ts(),wh=zn(),Pk=Na(),In=ns(),Tk=O(),An=xn(),cs=kn(),uc=q(),Sh=oh(),zk=yh(),kh=(t,e)=>new RegExp(t,e);kh.code="new RegExp";var Rk=["removeAdditional","useDefaults","coerceTypes"],Ik=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Ak={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."},Ok={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},vh=200;function Mk(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,_,S,b,E,v,$,x,Se,we,Zt,nr;let ce=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,Ge=kt===!0||kt===void 0?1:kt||0,Lr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:kh,Q_=(o=t.uriResolver)!==null&&o!==void 0?o:zk.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:ce)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:ce)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:ce)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:ce)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:ce)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Ge,regExp:Lr}:{optimize:Ge,regExp:Lr},loopRequired:(_=t.loopRequired)!==null&&_!==void 0?_:vh,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:vh,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(E=t.messages)!==null&&E!==void 0?E:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:($=t.schemaId)!==null&&$!==void 0?$:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(Se=t.validateSchema)!==null&&Se!==void 0?Se:!0,validateFormats:(we=t.validateFormats)!==null&&we!==void 0?we:!0,unicodeRegExp:(Zt=t.unicodeRegExp)!==null&&Zt!==void 0?Zt:!0,int32range:(nr=t.int32range)!==null&&nr!==void 0?nr:!0,uriResolver:Q_}}var On=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Mk(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Tk.ValueScope({scope:{},prefixes:Ik,es5:r,lines:n}),this.logger=Uk(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Pk.getRules)(),bh.call(this,Ak,e,"NOT SUPPORTED"),bh.call(this,Ok,e,"DEPRECATED","warn"),this._metaOpts=jk.call(this),e.formats&&Nk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Dk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ck.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Sh;n==="id"&&(o={...Sh},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof wh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,An.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Eh.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new In.SchemaEnv({schema:{},schemaId:n});if(r=In.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Eh.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,An.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Zk.call(this,n,r),!r)return(0,uc.eachItem)(n,s=>cc.call(this,s)),this;Hk.call(this,r);let o={...r,type:(0,cs.getJSONTypes)(r.type),schemaType:(0,cs.getJSONTypes)(r.schemaType)};return(0,uc.eachItem)(n,o.type.length===0?s=>cc.call(this,s,o):s=>o.type.forEach(i=>cc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=xh(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,An.normalizeId)(i||n);let u=An.getSchemaRefs.call(this,e,n);return c=new In.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):In.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{In.compileSchema.call(this,e)}finally{this.opts=r}}};On.ValidationError=$k.default;On.MissingRefError=wh.default;_e.default=On;function bh(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Eh(t){return t=(0,An.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ck(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Nk(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Dk(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function jk(){let t={...this.opts};for(let e of Rk)delete t[e];return t}var Lk={log(){},warn(){},error(){}};function Uk(t){if(t===!1)return Lk;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var qk=/^[a-z_$][a-z0-9_$:-]*$/i;function Zk(t,e){let{RULES:r}=this;if((0,uc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!qk.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function cc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,cs.getJSONTypes)(e.type),schemaType:(0,cs.getJSONTypes)(e.schemaType)}};e.before?Fk.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Fk(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Hk(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xh(e)),t.validateSchema=this.compile(e,!0))}var Wk={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xh(t){return{anyOf:[t,Wk]}}});var Ph=w(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Vk={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lc.default=Vk});var Ih=w(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var Kk=zn(),Th=Ze(),Ae=O(),kr=yt(),zh=ns(),us=q(),Gk={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=zh.resolveRef.call(c,u,o,r);if(l===void 0)throw new Kk.default(n.opts.uriResolver,o,r);if(l instanceof zh.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return ls(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return ls(t,(0,Ae._)`${m}.validate`,u,u.$async)}function p(m){let _=Rh(t,m);ls(t,_,m,m.$async)}function f(m){let _=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ae.stringify)(m)}:{ref:m}),S=e.name("valid"),b=t.subschema({schema:m,dataTypes:[],schemaPath:Ae.nil,topSchemaRef:_,errSchemaPath:r},S);t.mergeEvaluated(b),t.ok(S)}}};function Rh(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ae._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xt.getValidate=Rh;function ls(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?kr.default.this:Ae.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Ae._)`await ${(0,Th.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},_=>{o.if((0,Ae._)`!(${_} instanceof ${s.ValidationError})`,()=>o.throw(_)),p(_),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,Th.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let _=(0,Ae._)`${m}.errors`;o.assign(kr.default.vErrors,(0,Ae._)`${kr.default.vErrors} === null ? ${_} : ${kr.default.vErrors}.concat(${_})`),o.assign(kr.default.errors,(0,Ae._)`${kr.default.vErrors}.length`)}function f(m){var _;if(!s.opts.unevaluated)return;let S=(_=r?.validate)===null||_===void 0?void 0:_.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=us.mergeEvaluated.props(o,S.props,s.props));else{let b=o.var("props",(0,Ae._)`${m}.evaluated.props`);s.props=us.mergeEvaluated.props(o,b,s.props,Ae.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=us.mergeEvaluated.items(o,S.items,s.items));else{let b=o.var("items",(0,Ae._)`${m}.evaluated.items`);s.items=us.mergeEvaluated.items(o,b,s.items,Ae.Name)}}}Xt.callRef=ls;Xt.default=Gk});var Ah=w(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Jk=Ph(),Yk=Ih(),Bk=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Jk.default,Yk.default];dc.default=Bk});var Oh=w(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var ds=O(),Lt=ds.operators,ps={maximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},minimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},exclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},exclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},Xk={message:({keyword:t,schemaCode:e})=>(0,ds.str)`must be ${ps[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ds._)`{comparison: ${ps[t].okStr}, limit: ${e}}`},Qk={keyword:Object.keys(ps),type:"number",schemaType:"number",$data:!0,error:Xk,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ds._)`${r} ${ps[e].fail} ${n} || isNaN(${r})`)}};pc.default=Qk});var Mh=w(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Mn=O(),e0={message:({schemaCode:t})=>(0,Mn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Mn._)`{multipleOf: ${t}}`},t0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:e0,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Mn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Mn._)`${i} !== parseInt(${i})`;t.fail$data((0,Mn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};fc.default=t0});var Nh=w(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});function Ch(t){let e=t.length,r=0,n=0,o;for(;n=55296&&o<=56319&&n{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Qt=O(),r0=q(),n0=Nh(),o0={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},s0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:o0,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,i=o.opts.unicode===!1?(0,Qt._)`${r}.length`:(0,Qt._)`${(0,r0.useFunc)(t.gen,n0.default)}(${r})`;t.fail$data((0,Qt._)`${i} ${s} ${n}`)}};hc.default=s0});var jh=w(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var i0=Ze(),a0=q(),xr=O(),c0={message:({schemaCode:t})=>(0,xr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xr._)`{pattern: ${t}}`},u0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:c0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,xr._)`new RegExp`:(0,a0.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,xr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,xr._)`!${l}`)}else{let c=(0,i0.usePattern)(t,o);t.fail$data((0,xr._)`!${c}.test(${r})`)}}};gc.default=u0});var Lh=w(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var Cn=O(),l0={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Cn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Cn._)`{limit: ${t}}`},d0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:l0,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Cn.operators.GT:Cn.operators.LT;t.fail$data((0,Cn._)`Object.keys(${r}).length ${o} ${n}`)}};_c.default=d0});var Uh=w(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Nn=Ze(),Dn=O(),p0=q(),f0={message:({params:{missingProperty:t}})=>(0,Dn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Dn._)`{missingProperty: ${t}}`},m0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:f0,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let _ of r)if(f?.[_]===void 0&&!m.has(_)){let S=i.schemaEnv.baseId+i.errSchemaPath,b=`required property "${_}" is not defined at "${S}" (strictRequired)`;(0,p0.checkStrictMode)(i,b,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Dn.nil,d);else for(let f of r)(0,Nn.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Nn.checkMissingProp)(t,r,f)),(0,Nn.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Nn.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Nn.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Dn.not)(m),()=>{t.error(),e.break()})},Dn.nil)}}};yc.default=m0});var qh=w(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var jn=O(),h0={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,jn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,jn._)`{limit: ${t}}`},g0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:h0,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?jn.operators.GT:jn.operators.LT;t.fail$data((0,jn._)`${r}.length ${o} ${n}`)}};Sc.default=g0});var fs=w(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Zh=Ha();Zh.code='require("ajv/dist/runtime/equal").default';vc.default=Zh});var Fh=w(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var bc=kn(),ye=O(),_0=q(),y0=fs(),S0={message:({params:{i:t,j:e}})=>(0,ye.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ye._)`{i: ${t}, j: ${e}}`},v0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:S0,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,bc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ye._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,ye._)`${r}.length`),_=e.let("j");t.setParams({i:m,j:_}),e.assign(c,!0),e.if((0,ye._)`${m} > 1`,()=>(d()?p:f)(m,_))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,_){let S=e.name("item"),b=(0,bc.checkDataTypes)(u,S,a.opts.strictNumbers,bc.DataType.Wrong),E=e.const("indices",(0,ye._)`{}`);e.for((0,ye._)`;${m}--;`,()=>{e.let(S,(0,ye._)`${r}[${m}]`),e.if(b,(0,ye._)`continue`),u.length>1&&e.if((0,ye._)`typeof ${S} == "string"`,(0,ye._)`${S} += "_"`),e.if((0,ye._)`typeof ${E}[${S}] == "number"`,()=>{e.assign(_,(0,ye._)`${E}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,ye._)`${E}[${S}] = ${m}`)})}function f(m,_){let S=(0,_0.useFunc)(e,y0.default),b=e.name("outer");e.label(b).for((0,ye._)`;${m}--;`,()=>e.for((0,ye._)`${_} = ${m}; ${_}--;`,()=>e.if((0,ye._)`${S}(${r}[${m}], ${r}[${_}])`,()=>{t.error(),e.assign(c,!1).break(b)})))}}};Ec.default=v0});var Hh=w(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var wc=O(),b0=q(),E0=fs(),w0={message:"must be equal to constant",params:({schemaCode:t})=>(0,wc._)`{allowedValue: ${t}}`},k0={keyword:"const",$data:!0,error:w0,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,wc._)`!${(0,b0.useFunc)(e,E0.default)}(${r}, ${o})`):t.fail((0,wc._)`${s} !== ${r}`)}};kc.default=k0});var Wh=w(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Ln=O(),x0=q(),$0=fs(),P0={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ln._)`{allowedValues: ${t}}`},T0={keyword:"enum",schemaType:"array",$data:!0,error:P0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,x0.useFunc)(e,$0.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Ln.or)(...o.map((m,_)=>p(f,_)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Ln._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let _=o[m];return typeof _=="object"&&_!==null?(0,Ln._)`${u()}(${r}, ${f}[${m}])`:(0,Ln._)`${r} === ${_}`}}};xc.default=T0});var Vh=w($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var z0=Oh(),R0=Mh(),I0=Dh(),A0=jh(),O0=Lh(),M0=Uh(),C0=qh(),N0=Fh(),D0=Hh(),j0=Wh(),L0=[z0.default,R0.default,I0.default,A0.default,O0.default,M0.default,C0.default,N0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},D0.default,j0.default];$c.default=L0});var Tc=w(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.validateAdditionalItems=void 0;var er=O(),Pc=q(),U0={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},q0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:U0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Pc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Kh(t,n)}};function Kh(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Pc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,er._)`${a} <= ${e.length}`);r.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Pc.Type.Num},u),i.allErrors||r.if((0,er.not)(u),()=>r.break())})}}Un.validateAdditionalItems=Kh;Un.default=q0});var zc=w(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.validateTuple=void 0;var Gh=O(),ms=q(),Z0=Ze(),F0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Jh(t,"additionalItems",e);r.items=!0,!(0,ms.alwaysValidSchema)(r,e)&&t.ok((0,Z0.validateArray)(t))}};function Jh(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ms.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Gh._)`${s}.length`);r.forEach((d,p)=>{(0,ms.alwaysValidSchema)(a,d)||(n.if((0,Gh._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,_=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!_){let S=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ms.checkStrictMode)(a,S,p.strictTuples)}}}qn.validateTuple=Jh;qn.default=F0});var Yh=w(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var H0=zc(),W0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,H0.validateTuple)(t,"items")};Rc.default=W0});var Xh=w(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Bh=O(),V0=q(),K0=Ze(),G0=Tc(),J0={message:({params:{len:t}})=>(0,Bh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Bh._)`{limit: ${t}}`},Y0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:J0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,V0.alwaysValidSchema)(n,e)&&(o?(0,G0.validateAdditionalItems)(t,o):t.ok((0,K0.validateArray)(t)))}};Ic.default=Y0});var Qh=w(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var He=O(),hs=q(),B0={message:({params:{min:t,max:e}})=>e===void 0?(0,He.str)`must contain at least ${t} valid item(s)`:(0,He.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,He._)`{minContains: ${t}}`:(0,He._)`{minContains: ${t}, maxContains: ${e}}`},X0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:B0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,He._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,hs.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,hs.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,hs.alwaysValidSchema)(s,r)){let _=(0,He._)`${l} >= ${i}`;a!==void 0&&(_=(0,He._)`${_} && ${l} <= ${a}`),t.pass(_);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,He._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let _=e.name("_valid"),S=e.let("count",0);f(_,()=>e.if(_,()=>m(S)))}function f(_,S){e.forRange("i",0,l,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:hs.Type.Num,compositeRule:!0},_),S()})}function m(_){e.code((0,He._)`${_}++`),a===void 0?e.if((0,He._)`${_} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,He._)`${_} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,He._)`${_} >= ${i}`,()=>e.assign(d,!0)))}}};Ac.default=X0});var rg=w(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var Oc=O(),Q0=q(),Zn=Ze();it.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Oc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Oc._)`{property: ${t}, +"use strict";var U_=Object.create;var Ws=Object.defineProperty;var q_=Object.getOwnPropertyDescriptor;var Z_=Object.getOwnPropertyNames;var F_=Object.getPrototypeOf,H_=Object.prototype.hasOwnProperty;var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Ou=(t,e)=>{for(var r in e)Ws(t,r,{get:e[r],enumerable:!0})},W_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Z_(e))!H_.call(t,o)&&o!==r&&Ws(t,o,{get:()=>e[o],enumerable:!(n=q_(e,o))||n.enumerable});return t};var xt=(t,e,r)=>(r=t!=null?U_(F_(t)):{},W_(e||!t||!t.__esModule?Ws(r,"default",{value:t,enumerable:!0}):r,t));var mn=E(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var pn=class{};Z._CodeOrName=pn;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wt=class extends pn{constructor(e){if(super(),!Z.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Z.Name=Wt;var Le=class extends pn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Wt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Le;Z.nil=new Le("");function Xf(t,...e){let r=[t[0]],n=0;for(;n{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var $e=mn(),da=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Co;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Co||(Pe.UsedValueState=Co={}));Pe.varKinds={const:new $e.Name("const"),let:new $e.Name("let"),var:new $e.Name("var")};var No=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof $e.Name?e:this.name(e)}name(e){return new $e.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Pe.Scope=No;var Do=class extends $e.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,$e._)`.${new $e.Name(r)}[${n}]`}};Pe.ValueScopeName=Do;var Pb=(0,$e._)`\n`,pa=class extends No{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Pb:$e.nil}}get(){return this._scope}name(e){return new Do(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,$e._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=$e.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Co.Started);let l=r(u);if(l){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;s=(0,$e._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,$e._)`${s}${l}${this.opts._n}`;else throw new da(u);c.set(u,Co.Completed)})}return s}};Pe.ValueScope=pa});var A=E(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var j=mn(),Ge=fa(),At=mn();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return At.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return At.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return At.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return At.Name}});var qo=fa();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return qo.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return qo.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return qo.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return qo.varKinds}});M.operators={GT:new j._Code(">"),GTE:new j._Code(">="),LT:new j._Code("<"),LTE:new j._Code("<="),EQ:new j._Code("==="),NEQ:new j._Code("!=="),NOT:new j._Code("!"),OR:new j._Code("||"),AND:new j._Code("&&"),ADD:new j._Code("+")};var yt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ma=class extends yt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ge.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=gr(this.rhs,e,r)),this}get names(){return this.rhs instanceof j._CodeOrName?this.rhs.names:{}}},jo=class extends yt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof j.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=gr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof j.Name?{}:{...this.lhs.names};return Uo(e,this.rhs)}},ha=class extends jo{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ga=class extends yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},_a=class extends yt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ya=class extends yt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Sa=class extends yt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=gr(this.code,e,r),this}get names(){return this.code instanceof j._CodeOrName?this.code.names:{}}},hn=class extends yt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Tb(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Jt(e,r.names),{})}},St=class extends hn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},va=class extends hn{},hr=class extends St{};hr.kind="else";var Vt=class t extends St{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new hr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(em(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=gr(this.condition,e,r),this}get names(){let e=super.names;return Uo(e,this.condition),this.else&&Jt(e,this.else.names),e}};Vt.kind="if";var Kt=class extends St{};Kt.kind="for";var ba=class extends Kt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=gr(this.iteration,e,r),this}get names(){return Jt(super.names,this.iteration.names)}},Ea=class extends Kt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ge.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Uo(super.names,this.from);return Uo(e,this.to)}},Lo=class extends Kt{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=gr(this.iterable,e,r),this}get names(){return Jt(super.names,this.iterable.names)}},gn=class extends St{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};gn.kind="func";var _n=class extends hn{render(e){return"return "+super.render(e)}};_n.kind="return";var wa=class extends St{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Jt(e,this.catch.names),this.finally&&Jt(e,this.finally.names),e}},yn=class extends St{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};yn.kind="catch";var Sn=class extends St{render(e){return"finally"+super.render(e)}};Sn.kind="finally";var ka=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` +`:""},this._extScope=e,this._scope=new Ge.Scope({parent:e}),this._nodes=[new va]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new ma(e,s,n)),s}const(e,r,n){return this._def(Ge.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ge.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ge.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new jo(e,r,n))}add(e,r){return this._leafNode(new ha(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==j.nil&&this._leafNode(new Sa(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,j.addCodeArg)(r,o));return r.push("}"),new j._Code(r)}if(e,r,n){if(this._blockNode(new Vt(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vt(e))}else(){return this._elseNode(new hr)}endIf(){return this._endBlockNode(Vt,hr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ba(e),r)}forRange(e,r,n,o,s=this.opts.es5?Ge.varKinds.var:Ge.varKinds.let){let i=this._scope.toName(e);return this._for(new Ea(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Ge.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof j.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,j._)`${i}.length`,a=>{this.var(s,(0,j._)`${i}[${a}]`),n(s)})}return this._for(new Lo("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,j._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Lo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Kt)}label(e){return this._leafNode(new ga(e))}break(e){return this._leafNode(new _a(e))}return(e){let r=new _n;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(_n)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new wa;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new yn(s),r(s)}return n&&(this._currNode=o.finally=new Sn,this.code(n)),this._endBlockNode(yn,Sn)}throw(e){return this._leafNode(new ya(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=j.nil,n,o){return this._blockNode(new gn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(gn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};M.CodeGen=ka;function Jt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Uo(t,e){return e instanceof j._CodeOrName?Jt(t,e.names):t}function gr(t,e,r){if(t instanceof j.Name)return n(t);if(!o(t))return t;return new j._Code(t._items.reduce((s,i)=>(i instanceof j.Name&&(i=n(i)),i instanceof j._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof j._Code&&s._items.some(i=>i instanceof j.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Tb(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function em(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,j._)`!${xa(t)}`}M.not=em;var zb=tm(M.operators.AND);function Rb(...t){return t.reduce(zb)}M.and=Rb;var Ib=tm(M.operators.OR);function Ob(...t){return t.reduce(Ib)}M.or=Ob;function tm(t){return(e,r)=>e===j.nil?r:r===j.nil?e:(0,j._)`${xa(e)} ${t} ${xa(r)}`}function xa(t){return t instanceof j.Name?t:(0,j._)`(${t})`}});var U=E(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var K=A(),Ab=mn();function Mb(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=Mb;function Cb(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(om(t,e),!sm(e,t.self.RULES.all))}C.alwaysValidSchema=Cb;function om(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||cm(t,`unknown keyword: "${s}"`)}C.checkUnknownRules=om;function sm(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=sm;function Nb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Nb;function Db({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${t}${e}${(0,K.getProperty)(n)}`}C.schemaRefOrVal=Db;function jb(t){return im(decodeURIComponent(t))}C.unescapeFragment=jb;function Lb(t){return encodeURIComponent(Pa(t))}C.escapeFragment=Lb;function Pa(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Pa;function im(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=im;function Ub(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=Ub;function rm({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof K.Name?(s instanceof K.Name?t(o,s,i):e(o,s,i),i):s instanceof K.Name?(e(o,i,s),s):r(s,i);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}C.mergeEvaluated={props:rm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,K._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,K._)`${r} || {}`),Ta(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:am}),items:rm({mergeNames:(t,e,r)=>t.if((0,K._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,K._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,K._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,K._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function am(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,K._)`{}`);return e!==void 0&&Ta(t,r,e),r}C.evaluatedPropsToName=am;function Ta(t,e,r){Object.keys(r).forEach(n=>t.assign((0,K._)`${e}${(0,K.getProperty)(n)}`,!0))}C.setEvaluated=Ta;var nm={};function qb(t,e){return t.scopeValue("func",{ref:e,code:nm[e.code]||(nm[e.code]=new Ab._Code(e.code))})}C.useFunc=qb;var $a;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})($a||(C.Type=$a={}));function Zb(t,e,r){if(t instanceof K.Name){let n=e===$a.Num;return r?n?(0,K._)`"[" + ${t} + "]"`:(0,K._)`"['" + ${t} + "']"`:n?(0,K._)`"/" + ${t}`:(0,K._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(t).toString():"/"+Pa(t)}C.getErrorPath=Zb;function cm(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=cm});var vt=E(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var ye=A(),Fb={data:new ye.Name("data"),valCxt:new ye.Name("valCxt"),instancePath:new ye.Name("instancePath"),parentData:new ye.Name("parentData"),parentDataProperty:new ye.Name("parentDataProperty"),rootData:new ye.Name("rootData"),dynamicAnchors:new ye.Name("dynamicAnchors"),vErrors:new ye.Name("vErrors"),errors:new ye.Name("errors"),this:new ye.Name("this"),self:new ye.Name("self"),scope:new ye.Name("scope"),json:new ye.Name("json"),jsonPos:new ye.Name("jsonPos"),jsonLen:new ye.Name("jsonLen"),jsonPart:new ye.Name("jsonPart")};za.default=Fb});var vn=E(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.extendErrors=Se.resetErrorsCount=Se.reportExtraError=Se.reportError=Se.keyword$DataError=Se.keywordError=void 0;var q=A(),Zo=U(),we=vt();Se.keywordError={message:({keyword:t})=>(0,q.str)`must pass "${t}" keyword validation`};Se.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,q.str)`"${t}" keyword must be ${e} ($data)`:(0,q.str)`"${t}" keyword is invalid ($data)`};function Hb(t,e=Se.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=dm(t,e,r);n??(i||a)?um(s,c):lm(o,(0,q._)`[${c}]`)}Se.reportError=Hb;function Wb(t,e=Se.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=dm(t,e,r);um(o,a),s||i||lm(n,we.default.vErrors)}Se.reportExtraError=Wb;function Vb(t,e){t.assign(we.default.errors,e),t.if((0,q._)`${we.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,q._)`${we.default.vErrors}.length`,e),()=>t.assign(we.default.vErrors,null)))}Se.resetErrorsCount=Vb;function Kb({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,we.default.errors,a=>{t.const(i,(0,q._)`${we.default.vErrors}[${a}]`),t.if((0,q._)`${i}.instancePath === undefined`,()=>t.assign((0,q._)`${i}.instancePath`,(0,q.strConcat)(we.default.instancePath,s.errorPath))),t.assign((0,q._)`${i}.schemaPath`,(0,q.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,q._)`${i}.schema`,r),t.assign((0,q._)`${i}.data`,n))})}Se.extendErrors=Kb;function um(t,e){let r=t.const("err",e);t.if((0,q._)`${we.default.vErrors} === null`,()=>t.assign(we.default.vErrors,(0,q._)`[${r}]`),(0,q._)`${we.default.vErrors}.push(${r})`),t.code((0,q._)`${we.default.errors}++`)}function lm(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,q._)`new ${t.ValidationError}(${e})`):(r.assign((0,q._)`${n}.errors`,e),r.return(!1))}var Gt={keyword:new q.Name("keyword"),schemaPath:new q.Name("schemaPath"),params:new q.Name("params"),propertyName:new q.Name("propertyName"),message:new q.Name("message"),schema:new q.Name("schema"),parentSchema:new q.Name("parentSchema")};function dm(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,q._)`{}`:Jb(t,e,r)}function Jb(t,e,r={}){let{gen:n,it:o}=t,s=[Gb(o,r),Yb(t,r)];return Bb(t,e,s),n.object(...s)}function Gb({errorPath:t},{instancePath:e}){let r=e?(0,q.str)`${t}${(0,Zo.getErrorPath)(e,Zo.Type.Str)}`:t;return[we.default.instancePath,(0,q.strConcat)(we.default.instancePath,r)]}function Yb({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,q.str)`${e}/${t}`;return r&&(o=(0,q.str)`${o}${(0,Zo.getErrorPath)(r,Zo.Type.Str)}`),[Gt.schemaPath,o]}function Bb(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Gt.keyword,o],[Gt.params,typeof e=="function"?e(t):e||(0,q._)`{}`]),c.messages&&n.push([Gt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Gt.schema,i],[Gt.parentSchema,(0,q._)`${l}${d}`],[we.default.data,s]),u&&n.push([Gt.propertyName,u])}});var fm=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.boolOrEmptySchema=_r.topBoolOrEmptySchema=void 0;var Xb=vn(),Qb=A(),eE=vt(),tE={message:"boolean schema is false"};function rE(t){let{gen:e,schema:r,validateName:n}=t;r===!1?pm(t,!1):typeof r=="object"&&r.$async===!0?e.return(eE.default.data):(e.assign((0,Qb._)`${n}.errors`,null),e.return(!0))}_r.topBoolOrEmptySchema=rE;function nE(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),pm(t)):r.var(e,!0)}_r.boolOrEmptySchema=nE;function pm(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Xb.reportError)(o,tE,void 0,e)}});var Ra=E(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.getRules=yr.isJSONType=void 0;var oE=["string","number","integer","boolean","null","object","array"],sE=new Set(oE);function iE(t){return typeof t=="string"&&sE.has(t)}yr.isJSONType=iE;function aE(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}yr.getRules=aE});var Ia=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.shouldUseRule=Mt.shouldUseGroup=Mt.schemaHasRulesForType=void 0;function cE({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&mm(t,n)}Mt.schemaHasRulesForType=cE;function mm(t,e){return e.rules.some(r=>hm(t,r))}Mt.shouldUseGroup=mm;function hm(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mt.shouldUseRule=hm});var bn=E(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var uE=Ra(),lE=Ia(),dE=vn(),O=A(),gm=U(),Sr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Sr||(ve.DataType=Sr={}));function pE(t){let e=_m(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ve.getSchemaTypes=pE;function _m(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(uE.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ve.getJSONTypes=_m;function fE(t,e){let{gen:r,data:n,opts:o}=t,s=mE(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,lE.schemaHasRulesForType)(t,e[0]));if(i){let a=Aa(e,n,o.strictNumbers,Sr.Wrong);r.if(a,()=>{s.length?hE(t,e,s):Ma(t)})}return i}ve.coerceAndCheckDataType=fE;var ym=new Set(["string","number","integer","boolean","null"]);function mE(t,e){return e?t.filter(r=>ym.has(r)||e==="array"&&r==="array"):[]}function hE(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,O._)`typeof ${o}`),a=n.let("coerced",(0,O._)`undefined`);s.coerceTypes==="array"&&n.if((0,O._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,O._)`${o}[0]`).assign(i,(0,O._)`typeof ${o}`).if(Aa(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,O._)`${a} !== undefined`);for(let u of r)(ym.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Ma(t),n.endIf(),n.if((0,O._)`${a} !== undefined`,()=>{n.assign(o,a),gE(t,a)});function c(u){switch(u){case"string":n.elseIf((0,O._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,O._)`"" + ${o}`).elseIf((0,O._)`${o} === null`).assign(a,(0,O._)`""`);return;case"number":n.elseIf((0,O._)`${i} == "boolean" || ${o} === null + || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,O._)`+${o}`);return;case"integer":n.elseIf((0,O._)`${i} === "boolean" || ${o} === null + || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,O._)`+${o}`);return;case"boolean":n.elseIf((0,O._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,O._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,O._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,O._)`${i} === "string" || ${i} === "number" + || ${i} === "boolean" || ${o} === null`).assign(a,(0,O._)`[${o}]`)}}}function gE({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,O._)`${e} !== undefined`,()=>t.assign((0,O._)`${e}[${r}]`,n))}function Oa(t,e,r,n=Sr.Correct){let o=n===Sr.Correct?O.operators.EQ:O.operators.NEQ,s;switch(t){case"null":return(0,O._)`${e} ${o} null`;case"array":s=(0,O._)`Array.isArray(${e})`;break;case"object":s=(0,O._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,O._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,O._)`typeof ${e} ${o} ${t}`}return n===Sr.Correct?s:(0,O.not)(s);function i(a=O.nil){return(0,O.and)((0,O._)`typeof ${e} == "number"`,a,r?(0,O._)`isFinite(${e})`:O.nil)}}ve.checkDataType=Oa;function Aa(t,e,r,n){if(t.length===1)return Oa(t[0],e,r,n);let o,s=(0,gm.toHash)(t);if(s.array&&s.object){let i=(0,O._)`typeof ${e} != "object"`;o=s.null?i:(0,O._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=O.nil;s.number&&delete s.integer;for(let i in s)o=(0,O.and)(o,Oa(i,e,r,n));return o}ve.checkDataTypes=Aa;var _E={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,O._)`{type: ${t}}`:(0,O._)`{type: ${e}}`};function Ma(t){let e=yE(t);(0,dE.reportError)(e,_E)}ve.reportTypeError=Ma;function yE(t){let{gen:e,data:r,schema:n}=t,o=(0,gm.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var vm=E(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.assignDefaults=void 0;var vr=A(),SE=U();function vE(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Sm(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Sm(t,s,o.default))}Fo.assignDefaults=vE;function Sm(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vr._)`${s}${(0,vr.getProperty)(e)}`;if(o){(0,SE.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vr._)`${a} = ${(0,vr.stringify)(r)}`)}});var Ue=E(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.validateUnion=W.validateArray=W.usePattern=W.callValidateCode=W.schemaProperties=W.allSchemaProperties=W.noPropertyInData=W.propertyInData=W.isOwnProperty=W.hasPropFunc=W.reportMissingProp=W.checkMissingProp=W.checkReportMissingProp=void 0;var Q=A(),Ca=U(),Ct=vt(),bE=U();function EE(t,e){let{gen:r,data:n,it:o}=t;r.if(Da(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Q._)`${e}`},!0),t.error()})}W.checkReportMissingProp=EE;function wE({gen:t,data:e,it:{opts:r}},n,o){return(0,Q.or)(...n.map(s=>(0,Q.and)(Da(t,e,s,r.ownProperties),(0,Q._)`${o} = ${s}`)))}W.checkMissingProp=wE;function kE(t,e){t.setParams({missingProperty:e},!0),t.error()}W.reportMissingProp=kE;function bm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Q._)`Object.prototype.hasOwnProperty`})}W.hasPropFunc=bm;function Na(t,e,r){return(0,Q._)`${bm(t)}.call(${e}, ${r})`}W.isOwnProperty=Na;function xE(t,e,r,n){let o=(0,Q._)`${e}${(0,Q.getProperty)(r)} !== undefined`;return n?(0,Q._)`${o} && ${Na(t,e,r)}`:o}W.propertyInData=xE;function Da(t,e,r,n){let o=(0,Q._)`${e}${(0,Q.getProperty)(r)} === undefined`;return n?(0,Q.or)(o,(0,Q.not)(Na(t,e,r))):o}W.noPropertyInData=Da;function Em(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}W.allSchemaProperties=Em;function $E(t,e){return Em(e).filter(r=>!(0,Ca.alwaysValidSchema)(t,e[r]))}W.schemaProperties=$E;function PE({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Q._)`${t}, ${e}, ${n}${o}`:e,d=[[Ct.default.instancePath,(0,Q.strConcat)(Ct.default.instancePath,s)],[Ct.default.parentData,i.parentData],[Ct.default.parentDataProperty,i.parentDataProperty],[Ct.default.rootData,Ct.default.rootData]];i.opts.dynamicRef&&d.push([Ct.default.dynamicAnchors,Ct.default.dynamicAnchors]);let p=(0,Q._)`${l}, ${r.object(...d)}`;return c!==Q.nil?(0,Q._)`${a}.call(${c}, ${p})`:(0,Q._)`${a}(${p})`}W.callValidateCode=PE;var TE=(0,Q._)`new RegExp`;function zE({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Q._)`${o.code==="new RegExp"?TE:(0,bE.useFunc)(t,o)}(${r}, ${n})`})}W.usePattern=zE;function RE(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Q._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ca.Type.Num},s),e.if((0,Q.not)(s),a)})}}W.validateArray=RE;function IE(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ca.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Q._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Q.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}W.validateUnion=IE});var xm=E(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.validateKeywordUsage=nt.validSchemaType=nt.funcKeywordCode=nt.macroKeywordCode=void 0;var ke=A(),Yt=vt(),OE=Ue(),AE=vn();function ME(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=km(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ke.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}nt.macroKeywordCode=ME;function CE(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;DE(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=km(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&wm(t),S(()=>t.error());else{let v=e.async?f():m();e.modifying&&wm(t),S(()=>NE(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,ke._)`await `),x=>n.assign(d,!1).if((0,ke._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,ke._)`${x}.errors`),()=>n.throw(x))),v}function m(){let v=(0,ke._)`${l}.errors`;return n.assign(v,null),g(ke.nil),v}function g(v=e.async?(0,ke._)`await `:ke.nil){let x=c.opts.passContext?Yt.default.this:Yt.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ke._)`${v}${(0,OE.callValidateCode)(t,l,x,b)}`,e.modifying)}function S(v){var x;n.if((0,ke.not)((x=e.valid)!==null&&x!==void 0?x:d),v)}}nt.funcKeywordCode=CE;function wm(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ke._)`${n.parentData}[${n.parentDataProperty}]`))}function NE(t,e){let{gen:r}=t;r.if((0,ke._)`Array.isArray(${e})`,()=>{r.assign(Yt.default.vErrors,(0,ke._)`${Yt.default.vErrors} === null ? ${e} : ${Yt.default.vErrors}.concat(${e})`).assign(Yt.default.errors,(0,ke._)`${Yt.default.vErrors}.length`),(0,AE.extendErrors)(t)},()=>t.error())}function DE({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function km(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,ke.stringify)(r)})}function jE(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}nt.validSchemaType=jE;function LE({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}nt.validateKeywordUsage=LE});var Pm=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.extendSubschemaMode=Nt.extendSubschemaData=Nt.getSubschema=void 0;var ot=A(),$m=U();function UE(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,ot._)`${t.schemaPath}${(0,ot.getProperty)(e)}${(0,ot.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$m.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Nt.getSubschema=UE;function qE(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,ot._)`${e.data}${(0,ot.getProperty)(r)}`,!0);c(p),t.errorPath=(0,ot.str)`${u}${(0,$m.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,ot._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof ot.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Nt.extendSubschemaData=qE;function ZE(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Nt.extendSubschemaMode=ZE});var ja=E((cM,Tm)=>{"use strict";Tm.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Rm=E((uM,zm)=>{"use strict";var Dt=zm.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Ho(e,n,o,t,"",t)};Dt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Dt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Dt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Dt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ho(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Dt.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.getSchemaRefs=Te.resolveUrl=Te.normalizeId=Te._getFullPath=Te.getFullPath=Te.inlineRef=void 0;var HE=U(),WE=ja(),VE=Rm(),KE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function JE(t,e=!0){return typeof t=="boolean"?!0:e===!0?!La(t):e?Im(t)<=e:!1}Te.inlineRef=JE;var GE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function La(t){for(let e in t){if(GE.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(La)||typeof r=="object"&&La(r))return!0}return!1}function Im(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!KE.has(r)&&(typeof t[r]=="object"&&(0,HE.eachItem)(t[r],n=>e+=Im(n)),e===1/0))return 1/0}return e}function Om(t,e="",r){r!==!1&&(e=br(e));let n=t.parse(e);return Am(t,n)}Te.getFullPath=Om;function Am(t,e){return t.serialize(e).split("#")[0]+"#"}Te._getFullPath=Am;var YE=/#\/?$/;function br(t){return t?t.replace(YE,""):""}Te.normalizeId=br;function BE(t,e,r){return r=br(r),t.resolve(e,r)}Te.resolveUrl=BE;var XE=/^[a-z_][-a-z0-9._]*$/i;function QE(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=br(t[r]||e),s={"":o},i=Om(n,o,!1),a={},c=new Set;return VE(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,S=s[m];typeof d[r]=="string"&&(S=v.call(this,d[r])),x.call(this,d.$anchor),x.call(this,d.$dynamicAnchor),s[p]=S;function v(b){let $=this.opts.uriResolver.resolve;if(b=br(S?$(S,b):b),c.has(b))throw l(b);c.add(b);let k=this.refs[b];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(d,k.schema,b):b!==br(g)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=g),b}function x(b){if(typeof b=="string"){if(!XE.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!WE(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Te.getSchemaRefs=QE});var xn=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.getData=jt.KeywordCxt=jt.validateFunctionCode=void 0;var jm=fm(),Mm=bn(),qa=Ia(),Wo=bn(),ew=vm(),kn=xm(),Ua=Pm(),T=A(),R=vt(),tw=En(),bt=U(),wn=vn();function rw(t){if(qm(t)&&(Zm(t),Um(t))){sw(t);return}Lm(t,()=>(0,jm.topBoolOrEmptySchema)(t))}jt.validateFunctionCode=rw;function Lm({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${R.default.data}, ${R.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Cm(r,o)}`),ow(t,o),t.code(s)}):t.func(e,(0,T._)`${R.default.data}, ${nw(o)}`,n.$async,()=>t.code(Cm(r,o)).code(s))}function nw(t){return(0,T._)`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${t.dynamicRef?(0,T._)`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function ow(t,e){t.if(R.default.valCxt,()=>{t.var(R.default.instancePath,(0,T._)`${R.default.valCxt}.${R.default.instancePath}`),t.var(R.default.parentData,(0,T._)`${R.default.valCxt}.${R.default.parentData}`),t.var(R.default.parentDataProperty,(0,T._)`${R.default.valCxt}.${R.default.parentDataProperty}`),t.var(R.default.rootData,(0,T._)`${R.default.valCxt}.${R.default.rootData}`),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{t.var(R.default.instancePath,(0,T._)`""`),t.var(R.default.parentData,(0,T._)`undefined`),t.var(R.default.parentDataProperty,(0,T._)`undefined`),t.var(R.default.rootData,R.default.data),e.dynamicRef&&t.var(R.default.dynamicAnchors,(0,T._)`{}`)})}function sw(t){let{schema:e,opts:r,gen:n}=t;Lm(t,()=>{r.$comment&&e.$comment&&Hm(t),lw(t),n.let(R.default.vErrors,null),n.let(R.default.errors,0),r.unevaluated&&iw(t),Fm(t),fw(t)})}function iw(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function Cm(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function aw(t,e){if(qm(t)&&(Zm(t),Um(t))){cw(t,e);return}(0,jm.boolOrEmptySchema)(t,e)}function Um({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function qm(t){return typeof t.schema!="boolean"}function cw(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Hm(t),dw(t),pw(t);let s=n.const("_errs",R.default.errors);Fm(t,s),n.var(e,(0,T._)`${s} === ${R.default.errors}`)}function Zm(t){(0,bt.checkUnknownRules)(t),uw(t)}function Fm(t,e){if(t.opts.jtd)return Nm(t,[],!1,e);let r=(0,Mm.getSchemaTypes)(t.schema),n=(0,Mm.coerceAndCheckDataType)(t,r);Nm(t,r,!n,e)}function uw(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function lw(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(t,"default is ignored in the schema root")}function dw(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,tw.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function pw(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Hm({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${R.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${R.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function fw(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${R.default.errors} === 0`,()=>e.return(R.default.data),()=>e.throw((0,T._)`new ${o}(${R.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,R.default.vErrors),s.unevaluated&&mw(t),e.return((0,T._)`${R.default.errors} === 0`))}function mw({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function Nm(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,bt.schemaHasRulesButRef)(s,l))){o.block(()=>Vm(t,"$ref",l.all.$ref.definition));return}c.jtd||hw(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,qa.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Wo.checkDataType)(p.type,i,c.strictNumbers)),Dm(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Wo.reportTypeError)(t)),o.endIf()):Dm(t,p),a||o.if((0,T._)`${R.default.errors} === ${n||0}`))}}function Dm(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,ew.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,qa.shouldUseRule)(n,s)&&Vm(t,s.keyword,s.definition,e.type)})}function hw(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(gw(t,e),t.opts.allowUnionTypes||_w(t,e),yw(t,t.dataTypes))}function gw(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Wm(t.dataTypes,r)||Za(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),vw(t,e)}}function _w(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Za(t,"use allowUnionTypes to allow union type keyword")}function yw(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,qa.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Sw(e,i))&&Za(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Sw(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Wm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function vw(t,e){let r=[];for(let n of t.dataTypes)Wm(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Za(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(t,e,t.opts.strictTypes)}var Vo=class{constructor(e,r,n){if((0,kn.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Km(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,kn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",R.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?wn.reportExtraError:wn.reportError)(this,this.def.error,r)}$dataError(){(0,wn.reportError)(this,this.def.$dataError||wn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,wn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Wo.checkDataTypes)(c,r,s.opts.strictNumbers,Wo.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,Ua.getSubschema)(this.it,e);(0,Ua.extendSubschemaData)(n,this.it,e),(0,Ua.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return aw(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=bt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=bt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};jt.KeywordCxt=Vo;function Vm(t,e,r,n){let o=new Vo(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,kn.funcKeywordCode)(o,r):"macro"in r?(0,kn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,kn.funcKeywordCode)(o,r)}var bw=/^\/(?:[^~]|~0|~1)*$/,Ew=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Km(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return R.default.rootData;if(t[0]==="/"){if(!bw.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=R.default.rootData}else{let u=Ew.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,bt.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}jt.getData=Km});var Ko=E(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var Fa=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ha.default=Fa});var $n=E(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Wa=En(),Va=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Wa.resolveUrl)(e,r,n),this.missingSchema=(0,Wa.normalizeId)((0,Wa.getFullPath)(e,this.missingRef))}};Ka.default=Va});var Go=E(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.resolveSchema=qe.getCompilingSchema=qe.resolveRef=qe.compileSchema=qe.SchemaEnv=void 0;var Ye=A(),ww=Ko(),Bt=vt(),Be=En(),Jm=U(),kw=xn(),Er=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Be.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qe.SchemaEnv=Er;function Ga(t){let e=Gm.call(this,t);if(e)return e;let r=(0,Be.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ye.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:ww.default,code:(0,Ye._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Bt.default.data,parentData:Bt.default.parentData,parentDataProperty:Bt.default.parentDataProperty,dataNames:[Bt.default.data],dataPathArr:[Ye.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ye.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ye.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ye._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,kw.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Bt.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Bt.default.self}`,`${Bt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof Ye.Name?void 0:m,items:g instanceof Ye.Name?void 0:g,dynamicProps:m instanceof Ye.Name,dynamicItems:g instanceof Ye.Name},f.source&&(f.source.evaluated=(0,Ye.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}qe.compileSchema=Ga;function xw(t,e,r){var n;r=(0,Be.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Tw.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Er({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=$w.call(this,s)}qe.resolveRef=xw;function $w(t){return(0,Be.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ga.call(this,t)}function Gm(t){for(let e of this._compilations)if(Pw(e,t))return e}qe.getCompilingSchema=Gm;function Pw(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Tw(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Jo.call(this,t,e)}function Jo(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Be._getFullPath)(this.opts.uriResolver,r),o=(0,Be.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Ja.call(this,r,t);let s=(0,Be.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Jo.call(this,t,i);return typeof a?.schema!="object"?void 0:Ja.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ga.call(this,i),s===(0,Be.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Be.resolveUrl)(this.opts.uriResolver,o,u)),new Er({schema:a,schemaId:c,root:t,baseId:o})}return Ja.call(this,r,i)}}qe.resolveSchema=Jo;var zw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ja(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Jm.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!zw.has(a)&&u&&(e=(0,Be.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Jm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Be.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Jo.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Er({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Ym=E((hM,Rw)=>{Rw.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ba=E((gM,eh)=>{"use strict";var Iw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xm=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 Ya(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Ow=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Bm(t){return t.length=0,!0}function Aw(t,e,r){if(t.length){let n=Ya(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Mw(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=Aw;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Bm}else{o.push(u);continue}}return o.length&&(a===Bm?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ya(o))),r.address=n.join(""),r}function Qm(t){if(Cw(t,":")<2)return{host:t,isIPV6:!1};let e=Mw(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Cw(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:Lw}=Ba(),Uw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,qw=["http","https","ws","wss","urn","urn:uuid"];function Zw(t){return qw.indexOf(t)!==-1}function Xa(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function th(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function rh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Fw(t){return t.secure=Xa(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Hw(t){if((t.port===(Xa(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function Ww(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Uw);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Qa(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Vw(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Qa(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Kw(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Lw(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Jw(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var nh={scheme:"http",domainHost:!0,parse:th,serialize:rh},Gw={scheme:"https",domainHost:nh.domainHost,parse:th,serialize:rh},Yo={scheme:"ws",domainHost:!0,parse:Fw,serialize:Hw},Yw={scheme:"wss",domainHost:Yo.domainHost,parse:Yo.parse,serialize:Yo.serialize},Bw={scheme:"urn",parse:Ww,serialize:Vw,skipNormalize:!0},Xw={scheme:"urn:uuid",parse:Kw,serialize:Jw,skipNormalize:!0},Bo={http:nh,https:Gw,ws:Yo,wss:Yw,urn:Bw,"urn:uuid":Xw};Object.setPrototypeOf(Bo,null);function Qa(t){return t&&(Bo[t]||Bo[t.toLowerCase()])||void 0}oh.exports={wsIsSecure:Xa,SCHEMES:Bo,isValidSchemeName:Zw,getSchemeHandler:Qa}});var ch=E((yM,Qo)=>{"use strict";var{normalizeIPv6:Qw,removeDotSegments:Pn,recomposeAuthority:ek,normalizeComponentEncoding:Xo,isIPv4:tk,nonSimpleDomain:rk}=Ba(),{SCHEMES:nk,getSchemeHandler:ih}=sh();function ok(t,e){return typeof t=="string"?t=st(Et(t,e),e):typeof t=="object"&&(t=Et(st(t,e),e)),t}function sk(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=ah(Et(t,n),Et(e,n),n,!0);return n.skipEscape=!0,st(o,n)}function ah(t,e,r,n){let o={};return n||(t=Et(st(t,r),r),e=Et(st(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Pn(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Pn(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Pn(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Pn(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ik(t,e,r){return typeof t=="string"?(t=unescape(t),t=st(Xo(Et(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=st(Xo(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=st(Xo(Et(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=st(Xo(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function st(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=ih(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=ek(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Pn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var ak=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Et(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(ak);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(tk(n.host)===!1){let c=Qw(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=ih(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&rk(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var ec={SCHEMES:nk,normalize:ok,resolve:sk,resolveComponent:ah,equal:ik,serialize:st,parse:Et};Qo.exports=ec;Qo.exports.default=ec;Qo.exports.fastUri=ec});var lh=E(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var uh=ch();uh.code='require("ajv/dist/runtime/uri").default';tc.default=uh});var yh=E(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=void 0;var ck=xn();Object.defineProperty(he,"KeywordCxt",{enumerable:!0,get:function(){return ck.KeywordCxt}});var wr=A();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return wr._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return wr.str}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return wr.stringify}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return wr.nil}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return wr.Name}});Object.defineProperty(he,"CodeGen",{enumerable:!0,get:function(){return wr.CodeGen}});var uk=Ko(),hh=$n(),lk=Ra(),Tn=Go(),dk=A(),zn=En(),es=bn(),nc=U(),dh=Ym(),pk=lh(),gh=(t,e)=>new RegExp(t,e);gh.code="new RegExp";var fk=["removeAdditional","useDefaults","coerceTypes"],mk=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),hk={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."},gk={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ph=200;function _k(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,S,v,x,b,$,k,_e,V,tt,Me;let kt=t.strict,Hs=(e=t.code)===null||e===void 0?void 0:e.optimize,Ru=Hs===!0||Hs===void 0?1:Hs||0,Iu=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:gh,L_=(o=t.uriResolver)!==null&&o!==void 0?o:pk.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:kt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:kt)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:kt)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:kt)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:kt)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Ru,regExp:Iu}:{optimize:Ru,regExp:Iu},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:ph,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:ph,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:($=t.schemaId)!==null&&$!==void 0?$:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(_e=t.validateSchema)!==null&&_e!==void 0?_e:!0,validateFormats:(V=t.validateFormats)!==null&&V!==void 0?V:!0,unicodeRegExp:(tt=t.unicodeRegExp)!==null&&tt!==void 0?tt:!0,int32range:(Me=t.int32range)!==null&&Me!==void 0?Me:!0,uriResolver:L_}}var Rn=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._k(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new dk.ValueScope({scope:{},prefixes:mk,es5:r,lines:n}),this.logger=wk(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,lk.getRules)(),fh.call(this,hk,e,"NOT SUPPORTED"),fh.call(this,gk,e,"DEPRECATED","warn"),this._metaOpts=bk.call(this),e.formats&&Sk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),yk.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=dh;n==="id"&&(o={...dh},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof hh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,zn.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=mh.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Tn.SchemaEnv({schema:{},schemaId:n});if(r=Tn.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=mh.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,zn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(xk.call(this,n,r),!r)return(0,nc.eachItem)(n,s=>rc.call(this,s)),this;Pk.call(this,r);let o={...r,type:(0,es.getJSONTypes)(r.type),schemaType:(0,es.getJSONTypes)(r.schemaType)};return(0,nc.eachItem)(n,o.type.length===0?s=>rc.call(this,s,o):s=>o.type.forEach(i=>rc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=_h(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,zn.normalizeId)(i||n);let u=zn.getSchemaRefs.call(this,e,n);return c=new Tn.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Tn.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Tn.compileSchema.call(this,e)}finally{this.opts=r}}};Rn.ValidationError=uk.default;Rn.MissingRefError=hh.default;he.default=Rn;function fh(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function mh(t){return t=(0,zn.normalizeId)(t),this.schemas[t]||this.refs[t]}function yk(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Sk(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function vk(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function bk(){let t={...this.opts};for(let e of fk)delete t[e];return t}var Ek={log(){},warn(){},error(){}};function wk(t){if(t===!1)return Ek;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var kk=/^[a-z_$][a-z0-9_$:-]*$/i;function xk(t,e){let{RULES:r}=this;if((0,nc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!kk.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function rc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,es.getJSONTypes)(e.type),schemaType:(0,es.getJSONTypes)(e.schemaType)}};e.before?$k.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function $k(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function Pk(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=_h(e)),t.validateSchema=this.compile(e,!0))}var Tk={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _h(t){return{anyOf:[t,Tk]}}});var Sh=E(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var zk={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};oc.default=zk});var wh=E(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.callRef=Xt.getValidate=void 0;var Rk=$n(),vh=Ue(),ze=A(),kr=vt(),bh=Go(),ts=U(),Ik={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=bh.resolveRef.call(c,u,o,r);if(l===void 0)throw new Rk.default(n.opts.uriResolver,o,r);if(l instanceof bh.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return rs(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return rs(t,(0,ze._)`${m}.validate`,u,u.$async)}function p(m){let g=Eh(t,m);rs(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ze.stringify)(m)}:{ref:m}),S=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:ze.nil,topSchemaRef:g,errSchemaPath:r},S);t.mergeEvaluated(v),t.ok(S)}}};function Eh(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ze._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xt.getValidate=Eh;function rs(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?kr.default.this:ze.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,ze._)`await ${(0,vh.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,ze._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,vh.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,ze._)`${m}.errors`;o.assign(kr.default.vErrors,(0,ze._)`${kr.default.vErrors} === null ? ${g} : ${kr.default.vErrors}.concat(${g})`),o.assign(kr.default.errors,(0,ze._)`${kr.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let S=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=ts.mergeEvaluated.props(o,S.props,s.props));else{let v=o.var("props",(0,ze._)`${m}.evaluated.props`);s.props=ts.mergeEvaluated.props(o,v,s.props,ze.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=ts.mergeEvaluated.items(o,S.items,s.items));else{let v=o.var("items",(0,ze._)`${m}.evaluated.items`);s.items=ts.mergeEvaluated.items(o,v,s.items,ze.Name)}}}Xt.callRef=rs;Xt.default=Ik});var kh=E(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var Ok=Sh(),Ak=wh(),Mk=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Ok.default,Ak.default];sc.default=Mk});var xh=E(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var ns=A(),Lt=ns.operators,os={maximum:{okStr:"<=",ok:Lt.LTE,fail:Lt.GT},minimum:{okStr:">=",ok:Lt.GTE,fail:Lt.LT},exclusiveMaximum:{okStr:"<",ok:Lt.LT,fail:Lt.GTE},exclusiveMinimum:{okStr:">",ok:Lt.GT,fail:Lt.LTE}},Ck={message:({keyword:t,schemaCode:e})=>(0,ns.str)`must be ${os[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ns._)`{comparison: ${os[t].okStr}, limit: ${e}}`},Nk={keyword:Object.keys(os),type:"number",schemaType:"number",$data:!0,error:Ck,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ns._)`${r} ${os[e].fail} ${n} || isNaN(${r})`)}};ic.default=Nk});var $h=E(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var In=A(),Dk={message:({schemaCode:t})=>(0,In.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,In._)`{multipleOf: ${t}}`},jk={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Dk,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,In._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,In._)`${i} !== parseInt(${i})`;t.fail$data((0,In._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ac.default=jk});var Th=E(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});function Ph(t){let e=t.length,r=0,n=0,o;for(;n=55296&&o<=56319&&n{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Qt=A(),Lk=U(),Uk=Th(),qk={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},Zk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qk,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,i=o.opts.unicode===!1?(0,Qt._)`${r}.length`:(0,Qt._)`${(0,Lk.useFunc)(t.gen,Uk.default)}(${r})`;t.fail$data((0,Qt._)`${i} ${s} ${n}`)}};uc.default=Zk});var Rh=E(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Fk=Ue(),Hk=U(),xr=A(),Wk={message:({schemaCode:t})=>(0,xr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xr._)`{pattern: ${t}}`},Vk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Wk,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,xr._)`new RegExp`:(0,Hk.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,xr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,xr._)`!${l}`)}else{let c=(0,Fk.usePattern)(t,o);t.fail$data((0,xr._)`!${c}.test(${r})`)}}};lc.default=Vk});var Ih=E(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var On=A(),Kk={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,On.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,On._)`{limit: ${t}}`},Jk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Kk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?On.operators.GT:On.operators.LT;t.fail$data((0,On._)`Object.keys(${r}).length ${o} ${n}`)}};dc.default=Jk});var Oh=E(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var An=Ue(),Mn=A(),Gk=U(),Yk={message:({params:{missingProperty:t}})=>(0,Mn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mn._)`{missingProperty: ${t}}`},Bk={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Yk,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let S=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${g}" is not defined at "${S}" (strictRequired)`;(0,Gk.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Mn.nil,d);else for(let f of r)(0,An.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,An.checkMissingProp)(t,r,f)),(0,An.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,An.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,An.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Mn.not)(m),()=>{t.error(),e.break()})},Mn.nil)}}};pc.default=Bk});var Ah=E(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Cn=A(),Xk={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Cn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Cn._)`{limit: ${t}}`},Qk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Xk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Cn.operators.GT:Cn.operators.LT;t.fail$data((0,Cn._)`${r}.length ${o} ${n}`)}};fc.default=Qk});var ss=E(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var Mh=ja();Mh.code='require("ajv/dist/runtime/equal").default';mc.default=Mh});var Ch=E(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var hc=bn(),ge=A(),e0=U(),t0=ss(),r0={message:({params:{i:t,j:e}})=>(0,ge.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ge._)`{i: ${t}, j: ${e}}`},n0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:r0,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,hc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ge._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,ge._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,ge._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let S=e.name("item"),v=(0,hc.checkDataTypes)(u,S,a.opts.strictNumbers,hc.DataType.Wrong),x=e.const("indices",(0,ge._)`{}`);e.for((0,ge._)`;${m}--;`,()=>{e.let(S,(0,ge._)`${r}[${m}]`),e.if(v,(0,ge._)`continue`),u.length>1&&e.if((0,ge._)`typeof ${S} == "string"`,(0,ge._)`${S} += "_"`),e.if((0,ge._)`typeof ${x}[${S}] == "number"`,()=>{e.assign(g,(0,ge._)`${x}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,ge._)`${x}[${S}] = ${m}`)})}function f(m,g){let S=(0,e0.useFunc)(e,t0.default),v=e.name("outer");e.label(v).for((0,ge._)`;${m}--;`,()=>e.for((0,ge._)`${g} = ${m}; ${g}--;`,()=>e.if((0,ge._)`${S}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};gc.default=n0});var Nh=E(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var _c=A(),o0=U(),s0=ss(),i0={message:"must be equal to constant",params:({schemaCode:t})=>(0,_c._)`{allowedValue: ${t}}`},a0={keyword:"const",$data:!0,error:i0,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,_c._)`!${(0,o0.useFunc)(e,s0.default)}(${r}, ${o})`):t.fail((0,_c._)`${s} !== ${r}`)}};yc.default=a0});var Dh=E(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Nn=A(),c0=U(),u0=ss(),l0={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Nn._)`{allowedValues: ${t}}`},d0={keyword:"enum",schemaType:"array",$data:!0,error:l0,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,c0.useFunc)(e,u0.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Nn.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Nn._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Nn._)`${u()}(${r}, ${f}[${m}])`:(0,Nn._)`${r} === ${g}`}}};Sc.default=d0});var jh=E(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var p0=xh(),f0=$h(),m0=zh(),h0=Rh(),g0=Ih(),_0=Oh(),y0=Ah(),S0=Ch(),v0=Nh(),b0=Dh(),E0=[p0.default,f0.default,m0.default,h0.default,g0.default,_0.default,y0.default,S0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},v0.default,b0.default];vc.default=E0});var Ec=E(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.validateAdditionalItems=void 0;var er=A(),bc=U(),w0={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},k0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:w0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,bc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Lh(t,n)}};function Lh(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,er._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,bc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,er._)`${a} <= ${e.length}`);r.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:bc.Type.Num},u),i.allErrors||r.if((0,er.not)(u),()=>r.break())})}}Dn.validateAdditionalItems=Lh;Dn.default=k0});var wc=E(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.validateTuple=void 0;var Uh=A(),is=U(),x0=Ue(),$0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return qh(t,"additionalItems",e);r.items=!0,!(0,is.alwaysValidSchema)(r,e)&&t.ok((0,x0.validateArray)(t))}};function qh(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=is.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Uh._)`${s}.length`);r.forEach((d,p)=>{(0,is.alwaysValidSchema)(a,d)||(n.if((0,Uh._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let S=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,is.checkStrictMode)(a,S,p.strictTuples)}}}jn.validateTuple=qh;jn.default=$0});var Zh=E(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var P0=wc(),T0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,P0.validateTuple)(t,"items")};kc.default=T0});var Hh=E(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Fh=A(),z0=U(),R0=Ue(),I0=Ec(),O0={message:({params:{len:t}})=>(0,Fh.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Fh._)`{limit: ${t}}`},A0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:O0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,z0.alwaysValidSchema)(n,e)&&(o?(0,I0.validateAdditionalItems)(t,o):t.ok((0,R0.validateArray)(t)))}};xc.default=A0});var Wh=E($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Ze=A(),as=U(),M0={message:({params:{min:t,max:e}})=>e===void 0?(0,Ze.str)`must contain at least ${t} valid item(s)`:(0,Ze.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ze._)`{minContains: ${t}}`:(0,Ze._)`{minContains: ${t}, maxContains: ${e}}`},C0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:M0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Ze._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,as.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,as.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,as.alwaysValidSchema)(s,r)){let g=(0,Ze._)`${l} >= ${i}`;a!==void 0&&(g=(0,Ze._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Ze._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),S=e.let("count",0);f(g,()=>e.if(g,()=>m(S)))}function f(g,S){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:as.Type.Num,compositeRule:!0},g),S()})}function m(g){e.code((0,Ze._)`${g}++`),a===void 0?e.if((0,Ze._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ze._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ze._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};$c.default=C0});var Jh=E(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateSchemaDeps=it.validatePropertyDeps=it.error=void 0;var Pc=A(),N0=U(),Ln=Ue();it.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Pc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Pc._)`{property: ${t}, missingProperty: ${n}, depsCount: ${e}, - deps: ${r}}`};var ex={keyword:"dependencies",type:"object",schemaType:"object",error:it.error,code(t){let[e,r]=tx(t);eg(t,e),tg(t,r)}};function tx({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function eg(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Zn.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Zn.checkReportMissingProp)(t,u)}):(r.if((0,Oc._)`${c} && (${(0,Zn.checkMissingProp)(t,a,s)})`),(0,Zn.reportMissingProp)(t,s),r.else())}}it.validatePropertyDeps=eg;function tg(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Q0.alwaysValidSchema)(s,e[a])||(r.if((0,Zn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}it.validateSchemaDeps=tg;it.default=ex});var og=w(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var ng=O(),rx=q(),nx={message:"property name must be valid",params:({params:t})=>(0,ng._)`{propertyName: ${t.propertyName}}`},ox={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nx,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,rx.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,ng.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Mc.default=ox});var Nc=w(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var gs=Ze(),Qe=O(),sx=yt(),_s=q(),ix={message:"must NOT have additional properties",params:({params:t})=>(0,Qe._)`{additionalProperty: ${t.additionalProperty}}`},ax={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ix,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,_s.alwaysValidSchema)(i,r))return;let u=(0,gs.allSchemaProperties)(n.properties),l=(0,gs.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Qe._)`${s} === ${sx.default.errors}`);function d(){e.forIn("key",o,S=>{!u.length&&!l.length?m(S):e.if(p(S),()=>m(S))})}function p(S){let b;if(u.length>8){let E=(0,_s.schemaRefOrVal)(i,n.properties,"properties");b=(0,gs.isOwnProperty)(e,E,S)}else u.length?b=(0,Qe.or)(...u.map(E=>(0,Qe._)`${S} === ${E}`)):b=Qe.nil;return l.length&&(b=(0,Qe.or)(b,...l.map(E=>(0,Qe._)`${(0,gs.usePattern)(t,E)}.test(${S})`))),(0,Qe.not)(b)}function f(S){e.code((0,Qe._)`delete ${o}[${S}]`)}function m(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,_s.alwaysValidSchema)(i,r)){let b=e.name("valid");c.removeAdditional==="failing"?(_(S,b,!1),e.if((0,Qe.not)(b),()=>{t.reset(),f(S)})):(_(S,b),a||e.if((0,Qe.not)(b),()=>e.break()))}}function _(S,b,E){let v={keyword:"additionalProperties",dataProp:S,dataPropType:_s.Type.Str};E===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,b)}}};Cc.default=ax});var ag=w(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var cx=Tn(),sg=Ze(),Dc=q(),ig=Nc(),ux={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ig.default.code(new cx.KeywordCxt(s,ig.default,"additionalProperties"));let i=(0,sg.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Dc.mergeEvaluated.props(e,(0,Dc.toHash)(i),s.props));let a=i.filter(d=>!(0,Dc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,sg.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};jc.default=ux});var dg=w(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var cg=Ze(),ys=O(),ug=q(),lg=q(),lx={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,cg.allSchemaProperties)(r),c=a.filter(_=>(0,ug.alwaysValidSchema)(s,r[_]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ys.Name)&&(s.props=(0,lg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let _ of a)u&&f(_),s.allErrors?m(_):(e.var(l,!0),m(_),e.if(l))}function f(_){for(let S in u)new RegExp(_).test(S)&&(0,ug.checkStrictMode)(s,`property ${S} matches pattern ${_} (use allowMatchingProperties)`)}function m(_){e.forIn("key",n,S=>{e.if((0,ys._)`${(0,cg.usePattern)(t,_)}.test(${S})`,()=>{let b=c.includes(_);b||t.subschema({keyword:"patternProperties",schemaProp:_,dataProp:S,dataPropType:lg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ys._)`${d}[${S}]`,!0):!b&&!s.allErrors&&e.if((0,ys.not)(l),()=>e.break())})})}}};Lc.default=lx});var pg=w(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var dx=q(),px={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,dx.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Uc.default=px});var fg=w(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var fx=Ze(),mx={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fx.validateUnion,error:{message:"must match a schema in anyOf"}};qc.default=mx});var mg=w(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Ss=O(),hx=q(),gx={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ss._)`{passingSchemas: ${t.passing}}`},_x={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gx,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,hx.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ss._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ss._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ss.Name)})})}}};Zc.default=_x});var hg=w(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var yx=q(),Sx={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,yx.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Fc.default=Sx});var yg=w(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var vs=O(),_g=q(),vx={message:({params:t})=>(0,vs.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,vs._)`{failingKeyword: ${t.ifClause}}`},bx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_g.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=gg(n,"then"),s=gg(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,vs.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,vs._)`${l}`):t.setParams({ifClause:l})}}}};function gg(t,e){let r=t.schema[e];return r!==void 0&&!(0,_g.alwaysValidSchema)(t,r)}Hc.default=bx});var Sg=w(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Ex=q(),wx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Ex.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Wc.default=wx});var vg=w(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var kx=Tc(),xx=Yh(),$x=zc(),Px=Xh(),Tx=Qh(),zx=rg(),Rx=og(),Ix=Nc(),Ax=ag(),Ox=dg(),Mx=pg(),Cx=fg(),Nx=mg(),Dx=hg(),jx=yg(),Lx=Sg();function Ux(t=!1){let e=[Mx.default,Cx.default,Nx.default,Dx.default,jx.default,Lx.default,Rx.default,Ix.default,zx.default,Ax.default,Ox.default];return t?e.push(xx.default,Px.default):e.push(kx.default,$x.default),e.push(Tx.default),e}Vc.default=Ux});var bg=w(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var ie=O(),qx={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},Zx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qx,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),_=r.const("fDef",(0,ie._)`${m}[${i}]`),S=r.let("fType"),b=r.let("format");r.if((0,ie._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>r.assign(S,(0,ie._)`${_}.type || "string"`).assign(b,(0,ie._)`${_}.validate`),()=>r.assign(S,(0,ie._)`"string"`).assign(b,_)),t.fail$data((0,ie.or)(E(),v()));function E(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${b}`}function v(){let $=l.$async?(0,ie._)`(${_}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,ie._)`${b}(${n})`,x=(0,ie._)`(typeof ${b} == "function" ? ${$} : ${b}.test(${n}))`;return(0,ie._)`${b} && ${b} !== true && ${S} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){E();return}if(m===!0)return;let[_,S,b]=v(m);_===e&&t.pass($());function E(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(x){let Se=x instanceof RegExp?(0,ie.regexpCode)(x):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,we=r.scopeValue("formats",{key:s,ref:x,code:Se});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,ie._)`${we}.validate`]:["string",x,we]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${b}(${n})`}return typeof S=="function"?(0,ie._)`${b}(${n})`:(0,ie._)`${b}.test(${n})`}}}};Kc.default=Zx});var Eg=w(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Fx=bg(),Hx=[Fx.default];Gc.default=Hx});var wg=w($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xg=w(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Wx=Ah(),Vx=Vh(),Kx=vg(),Gx=Eg(),kg=wg(),Jx=[Wx.default,Vx.default,(0,Kx.default)(),Gx.default,kg.metadataVocabulary,kg.contentVocabulary];Jc.default=Jx});var Pg=w(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.DiscrError=void 0;var $g;(function(t){t.Tag="tag",t.Mapping="mapping"})($g||(bs.DiscrError=$g={}))});var zg=w(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Pr=O(),Yc=Pg(),Tg=ns(),Yx=zn(),Bx=q(),Xx={message:({params:{discrError:t,tagName:e}})=>t===Yc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Pr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Qx={keyword:"discriminator",type:"object",schemaType:"object",error:Xx,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Pr._)`${r}${(0,Pr.getProperty)(a)}`);e.if((0,Pr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Yc.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Pr._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Yc.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),_=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(_,Pr.Name),m}function p(){var f;let m={},_=b(o),S=!0;for(let $=0;${e$.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Qc=w((Q,Xc)=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.MissingRefError=Q.ValidationError=Q.CodeGen=Q.Name=Q.nil=Q.stringify=Q.str=Q._=Q.KeywordCxt=Q.Ajv=void 0;var t$=$h(),r$=xg(),n$=zg(),Ig=Rg(),o$=["/properties"],Es="http://json-schema.org/draft-07/schema",Tr=class extends t$.default{_addVocabularies(){super._addVocabularies(),r$.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(n$.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ig,o$):Ig;this.addMetaSchema(e,Es,!1),this.refs["http://json-schema.org/schema"]=Es}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Es)?Es:void 0)}};Q.Ajv=Tr;Xc.exports=Q=Tr;Xc.exports.Ajv=Tr;Object.defineProperty(Q,"__esModule",{value:!0});Q.default=Tr;var s$=Tn();Object.defineProperty(Q,"KeywordCxt",{enumerable:!0,get:function(){return s$.KeywordCxt}});var zr=O();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return zr._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return zr.str}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return zr.stringify}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return zr.nil}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return zr.Name}});Object.defineProperty(Q,"CodeGen",{enumerable:!0,get:function(){return zr.CodeGen}});var i$=ts();Object.defineProperty(Q,"ValidationError",{enumerable:!0,get:function(){return i$.default}});var a$=zn();Object.defineProperty(Q,"MissingRefError",{enumerable:!0,get:function(){return a$.default}})});var Lg=w(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.formatNames=ct.fastFormats=ct.fullFormats=void 0;function at(t,e){return{validate:t,compare:e}}ct.fullFormats={date:at(Cg,nu),time:at(tu(!0),ou),"date-time":at(Ag(!0),Dg),"iso-time":at(tu(),Ng),"iso-date-time":at(Ag(),jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:f$,"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:v$,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:m$,int32:{type:"number",validate:_$},int64:{type:"number",validate:y$},float:{type:"number",validate:Mg},double:{type:"number",validate:Mg},password:!0,binary:!0};ct.fastFormats={...ct.fullFormats,date:at(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nu),time:at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ou),"date-time":at(/^\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,Dg),"iso-time":at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ng),"iso-date-time":at(/^\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,jg),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};ct.formatNames=Object.keys(ct.fullFormats);function c$(t){return t%4===0&&(t%100!==0||t%400===0)}var u$=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,l$=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Cg(t){let e=u$.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&c$(r)?29:l$[n])}function nu(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function ou(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Ng(t,e){if(!(t&&e))return;let r=eu.exec(t),n=eu.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=h$}function y$(t){return Number.isInteger(t)}function Mg(){return!0}var S$=/[^\\]\\Z/;function v$(t){if(S$.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ug=w(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.formatLimitDefinition=void 0;var b$=Qc(),et=O(),Ut=et.operators,ws={formatMaximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},formatMinimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},formatExclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},formatExclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},E$={message:({keyword:t,schemaCode:e})=>(0,et.str)`should be ${ws[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,et._)`{comparison: ${ws[t].okStr}, limit: ${e}}`};Rr.formatLimitDefinition={keyword:Object.keys(ws),type:"string",schemaType:"string",$data:!0,error:E$,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new b$.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,et._)`${p}[${c.schemaCode}]`);t.fail$data((0,et.or)((0,et._)`typeof ${f} != "object"`,(0,et._)`${f} instanceof RegExp`,(0,et._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,et._)`${i.code.formats}${(0,et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,et._)`${p}.compare(${r}, ${n}) ${ws[o].fail} 0`}},dependencies:["format"]};var w$=t=>(t.addKeyword(Rr.formatLimitDefinition),t);Rr.default=w$});var Hg=w((Fn,Fg)=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});var Ir=Lg(),k$=Ug(),su=O(),qg=new su.Name("fullFormats"),x$=new su.Name("fastFormats"),iu=(t,e={keywords:!0})=>{if(Array.isArray(e))return Zg(t,e,Ir.fullFormats,qg),t;let[r,n]=e.mode==="fast"?[Ir.fastFormats,x$]:[Ir.fullFormats,qg],o=e.formats||Ir.formatNames;return Zg(t,o,r,n),e.keywords&&(0,k$.default)(t),t};iu.get=(t,e="full")=>{let n=(e==="fast"?Ir.fastFormats:Ir.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Zg(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,su._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Fg.exports=Fn=iu;Object.defineProperty(Fn,"__esModule",{value:!0});Fn.default=iu});var dt=require("fs"),Fu=require("path");var L=require("path"),Xs=require("os"),Ur=require("fs");var Uu=require("url");var fy={};function iy(){return typeof __dirname<"u"?__dirname:(0,L.dirname)((0,Uu.fileURLToPath)(fy.url))}var KP=iy();function oo(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,L.join)((0,Xs.homedir)(),".claude-mem"),e=(0,L.join)(t,"settings.json");try{if((0,Ur.existsSync)(e)){let r=JSON.parse((0,Ur.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return t}var ee=oo(),so=process.env.CLAUDE_CONFIG_DIR||(0,L.join)((0,Xs.homedir)(),".claude"),Qs=(0,L.join)(so,"plugins","marketplaces","thedotmack"),ay=(0,L.join)(ee,"archives"),cy=(0,L.join)(ee,"logs"),uy=(0,L.join)(ee,"trash"),ly=(0,L.join)(ee,"backups"),dy=(0,L.join)(ee,"modes"),qu=(0,L.join)(ee,"settings.json"),GP=(0,L.join)(ee,"claude-mem.db"),py=(0,L.join)(ee,"vector-db"),Zu=(0,L.join)(ee,"observer-sessions"),JP=(0,L.basename)(Zu),YP=(0,L.join)(so,"settings.json"),BP=(0,L.join)(so,"commands"),XP=(0,L.join)(so,"CLAUDE.md");var De={dataDir:()=>ee,workerPid:()=>(0,L.join)(ee,"worker.pid"),serverPid:()=>(0,L.join)(ee,".server-beta.pid"),serverPort:()=>(0,L.join)(ee,".server-beta.port"),serverRuntime:()=>(0,L.join)(ee,".server-beta.runtime.json"),settings:()=>(0,L.join)(ee,"settings.json"),database:()=>(0,L.join)(ee,"claude-mem.db"),chroma:()=>(0,L.join)(ee,"chroma"),combinedCerts:()=>(0,L.join)(ee,"combined_certs.pem"),transcriptsConfig:()=>(0,L.join)(ee,"transcript-watch.json"),transcriptsState:()=>(0,L.join)(ee,"transcript-watch-state.json"),corpora:()=>(0,L.join)(ee,"corpora"),supervisorRegistry:()=>(0,L.join)(ee,"supervisor.json"),envFile:()=>(0,L.join)(ee,".env"),logsDir:()=>cy,archives:()=>ay,trash:()=>uy,backups:()=>ly,modes:()=>dy,vectorDb:()=>py,observerSessions:()=>Zu};var my=null;function hy(t){return(my??process.stderr.write.bind(process.stderr))(t)}function ei(t){hy(t)}var ri=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(ri||{}),ti=null,ni=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=De.logsDir();(0,dt.existsSync)(e)||(0,dt.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Fu.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=De.settings();if((0,dt.existsSync)(e)){let r=(0,dt.readFileSync)(e,"utf-8"),o=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ri[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} -${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${i}:${a}.${c}`}log(e,r,n,o,s){if(e{for(let u of a)(0,Ln.checkReportMissingProp)(t,u)}):(r.if((0,Pc._)`${c} && (${(0,Ln.checkMissingProp)(t,a,s)})`),(0,Ln.reportMissingProp)(t,s),r.else())}}it.validatePropertyDeps=Vh;function Kh(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,N0.alwaysValidSchema)(s,e[a])||(r.if((0,Ln.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}it.validateSchemaDeps=Kh;it.default=D0});var Yh=E(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Gh=A(),L0=U(),U0={message:"property name must be valid",params:({params:t})=>(0,Gh._)`{propertyName: ${t.propertyName}}`},q0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:U0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,L0.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Gh.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Tc.default=q0});var Rc=E(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var cs=Ue(),Xe=A(),Z0=vt(),us=U(),F0={message:"must NOT have additional properties",params:({params:t})=>(0,Xe._)`{additionalProperty: ${t.additionalProperty}}`},H0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:F0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,us.alwaysValidSchema)(i,r))return;let u=(0,cs.allSchemaProperties)(n.properties),l=(0,cs.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Xe._)`${s} === ${Z0.default.errors}`);function d(){e.forIn("key",o,S=>{!u.length&&!l.length?m(S):e.if(p(S),()=>m(S))})}function p(S){let v;if(u.length>8){let x=(0,us.schemaRefOrVal)(i,n.properties,"properties");v=(0,cs.isOwnProperty)(e,x,S)}else u.length?v=(0,Xe.or)(...u.map(x=>(0,Xe._)`${S} === ${x}`)):v=Xe.nil;return l.length&&(v=(0,Xe.or)(v,...l.map(x=>(0,Xe._)`${(0,cs.usePattern)(t,x)}.test(${S})`))),(0,Xe.not)(v)}function f(S){e.code((0,Xe._)`delete ${o}[${S}]`)}function m(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,us.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(S,v,!1),e.if((0,Xe.not)(v),()=>{t.reset(),f(S)})):(g(S,v),a||e.if((0,Xe.not)(v),()=>e.break()))}}function g(S,v,x){let b={keyword:"additionalProperties",dataProp:S,dataPropType:us.Type.Str};x===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};zc.default=H0});var Qh=E(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var W0=xn(),Bh=Ue(),Ic=U(),Xh=Rc(),V0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Xh.default.code(new W0.KeywordCxt(s,Xh.default,"additionalProperties"));let i=(0,Bh.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ic.mergeEvaluated.props(e,(0,Ic.toHash)(i),s.props));let a=i.filter(d=>!(0,Ic.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Bh.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Oc.default=V0});var ng=E(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var eg=Ue(),ls=A(),tg=U(),rg=U(),K0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,eg.allSchemaProperties)(r),c=a.filter(g=>(0,tg.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ls.Name)&&(s.props=(0,rg.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let S in u)new RegExp(g).test(S)&&(0,tg.checkStrictMode)(s,`property ${S} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,S=>{e.if((0,ls._)`${(0,eg.usePattern)(t,g)}.test(${S})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:S,dataPropType:rg.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ls._)`${d}[${S}]`,!0):!v&&!s.allErrors&&e.if((0,ls.not)(l),()=>e.break())})})}}};Ac.default=K0});var og=E(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var J0=U(),G0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,J0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Mc.default=G0});var sg=E(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var Y0=Ue(),B0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Y0.validateUnion,error:{message:"must match a schema in anyOf"}};Cc.default=B0});var ig=E(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var ds=A(),X0=U(),Q0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ds._)`{passingSchemas: ${t.passing}}`},ex={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Q0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,X0.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ds._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ds._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,ds.Name)})})}}};Nc.default=ex});var ag=E(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var tx=U(),rx={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,tx.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Dc.default=rx});var lg=E(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var ps=A(),ug=U(),nx={message:({params:t})=>(0,ps.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ps._)`{failingKeyword: ${t.ifClause}}`},ox={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nx,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ug.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=cg(n,"then"),s=cg(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,ps.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,ps._)`${l}`):t.setParams({ifClause:l})}}}};function cg(t,e){let r=t.schema[e];return r!==void 0&&!(0,ug.alwaysValidSchema)(t,r)}jc.default=ox});var dg=E(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var sx=U(),ix={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,sx.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Lc.default=ix});var pg=E(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var ax=Ec(),cx=Zh(),ux=wc(),lx=Hh(),dx=Wh(),px=Jh(),fx=Yh(),mx=Rc(),hx=Qh(),gx=ng(),_x=og(),yx=sg(),Sx=ig(),vx=ag(),bx=lg(),Ex=dg();function wx(t=!1){let e=[_x.default,yx.default,Sx.default,vx.default,bx.default,Ex.default,fx.default,mx.default,px.default,hx.default,gx.default];return t?e.push(cx.default,lx.default):e.push(ax.default,ux.default),e.push(dx.default),e}Uc.default=wx});var fg=E(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var ie=A(),kx={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},xx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:kx,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ie._)`${m}[${i}]`),S=r.let("fType"),v=r.let("format");r.if((0,ie._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(S,(0,ie._)`${g}.type || "string"`).assign(v,(0,ie._)`${g}.validate`),()=>r.assign(S,(0,ie._)`"string"`).assign(v,g)),t.fail$data((0,ie.or)(x(),b()));function x(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${v}`}function b(){let $=l.$async?(0,ie._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ie._)`${v}(${n})`,k=(0,ie._)`(typeof ${v} == "function" ? ${$} : ${v}.test(${n}))`;return(0,ie._)`${v} && ${v} !== true && ${S} === ${e} && !${k}`}}function f(){let m=d.formats[s];if(!m){x();return}if(m===!0)return;let[g,S,v]=b(m);g===e&&t.pass($());function x(){if(c.strictSchema===!1){d.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(k){let _e=k instanceof RegExp?(0,ie.regexpCode)(k):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,V=r.scopeValue("formats",{key:s,ref:k,code:_e});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,ie._)`${V}.validate`]:["string",k,V]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${v}(${n})`}return typeof S=="function"?(0,ie._)`${v}(${n})`:(0,ie._)`${v}.test(${n})`}}}};qc.default=xx});var mg=E(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var $x=fg(),Px=[$x.default];Zc.default=Px});var hg=E($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.contentVocabulary=$r.metadataVocabulary=void 0;$r.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];$r.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var _g=E(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Tx=kh(),zx=jh(),Rx=pg(),Ix=mg(),gg=hg(),Ox=[Tx.default,zx.default,(0,Rx.default)(),Ix.default,gg.metadataVocabulary,gg.contentVocabulary];Fc.default=Ox});var Sg=E(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.DiscrError=void 0;var yg;(function(t){t.Tag="tag",t.Mapping="mapping"})(yg||(fs.DiscrError=yg={}))});var bg=E(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Pr=A(),Hc=Sg(),vg=Go(),Ax=$n(),Mx=U(),Cx={message:({params:{discrError:t,tagName:e}})=>t===Hc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Pr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Nx={keyword:"discriminator",type:"object",schemaType:"object",error:Cx,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Pr._)`${r}${(0,Pr.getProperty)(a)}`);e.if((0,Pr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Hc.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Pr._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Hc.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,Pr.Name),m}function p(){var f;let m={},g=v(o),S=!0;for(let $=0;${Dx.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Kc=E((ee,Vc)=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.MissingRefError=ee.ValidationError=ee.CodeGen=ee.Name=ee.nil=ee.stringify=ee.str=ee._=ee.KeywordCxt=ee.Ajv=void 0;var jx=yh(),Lx=_g(),Ux=bg(),wg=Eg(),qx=["/properties"],ms="http://json-schema.org/draft-07/schema",Tr=class extends jx.default{_addVocabularies(){super._addVocabularies(),Lx.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Ux.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(wg,qx):wg;this.addMetaSchema(e,ms,!1),this.refs["http://json-schema.org/schema"]=ms}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ms)?ms:void 0)}};ee.Ajv=Tr;Vc.exports=ee=Tr;Vc.exports.Ajv=Tr;Object.defineProperty(ee,"__esModule",{value:!0});ee.default=Tr;var Zx=xn();Object.defineProperty(ee,"KeywordCxt",{enumerable:!0,get:function(){return Zx.KeywordCxt}});var zr=A();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return zr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return zr.str}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return zr.stringify}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return zr.nil}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return zr.Name}});Object.defineProperty(ee,"CodeGen",{enumerable:!0,get:function(){return zr.CodeGen}});var Fx=Ko();Object.defineProperty(ee,"ValidationError",{enumerable:!0,get:function(){return Fx.default}});var Hx=$n();Object.defineProperty(ee,"MissingRefError",{enumerable:!0,get:function(){return Hx.default}})});var Ig=E(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.formatNames=ct.fastFormats=ct.fullFormats=void 0;function at(t,e){return{validate:t,compare:e}}ct.fullFormats={date:at(Pg,Bc),time:at(Gc(!0),Xc),"date-time":at(kg(!0),zg),"iso-time":at(Gc(),Tg),"iso-date-time":at(kg(),Rg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Yx,"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:n$,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:Bx,int32:{type:"number",validate:e$},int64:{type:"number",validate:t$},float:{type:"number",validate:$g},double:{type:"number",validate:$g},password:!0,binary:!0};ct.fastFormats={...ct.fullFormats,date:at(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bc),time:at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Xc),"date-time":at(/^\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,zg),"iso-time":at(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Tg),"iso-date-time":at(/^\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,Rg),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};ct.formatNames=Object.keys(ct.fullFormats);function Wx(t){return t%4===0&&(t%100!==0||t%400===0)}var Vx=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Kx=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Pg(t){let e=Vx.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Wx(r)?29:Kx[n])}function Bc(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Xc(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Tg(t,e){if(!(t&&e))return;let r=Jc.exec(t),n=Jc.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=Xx}function t$(t){return Number.isInteger(t)}function $g(){return!0}var r$=/[^\\]\\Z/;function n$(t){if(r$.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Og=E(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.formatLimitDefinition=void 0;var o$=Kc(),Qe=A(),Ut=Qe.operators,hs={formatMaximum:{okStr:"<=",ok:Ut.LTE,fail:Ut.GT},formatMinimum:{okStr:">=",ok:Ut.GTE,fail:Ut.LT},formatExclusiveMaximum:{okStr:"<",ok:Ut.LT,fail:Ut.GTE},formatExclusiveMinimum:{okStr:">",ok:Ut.GT,fail:Ut.LTE}},s$={message:({keyword:t,schemaCode:e})=>(0,Qe.str)`should be ${hs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qe._)`{comparison: ${hs[t].okStr}, limit: ${e}}`};Rr.formatLimitDefinition={keyword:Object.keys(hs),type:"string",schemaType:"string",$data:!0,error:s$,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new o$.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Qe._)`${p}[${c.schemaCode}]`);t.fail$data((0,Qe.or)((0,Qe._)`typeof ${f} != "object"`,(0,Qe._)`${f} instanceof RegExp`,(0,Qe._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,Qe._)`${i.code.formats}${(0,Qe.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Qe._)`${p}.compare(${r}, ${n}) ${hs[o].fail} 0`}},dependencies:["format"]};var i$=t=>(t.addKeyword(Rr.formatLimitDefinition),t);Rr.default=i$});var Ng=E((Un,Cg)=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});var Ir=Ig(),a$=Og(),Qc=A(),Ag=new Qc.Name("fullFormats"),c$=new Qc.Name("fastFormats"),eu=(t,e={keywords:!0})=>{if(Array.isArray(e))return Mg(t,e,Ir.fullFormats,Ag),t;let[r,n]=e.mode==="fast"?[Ir.fastFormats,c$]:[Ir.fullFormats,Ag],o=e.formats||Ir.formatNames;return Mg(t,o,r,n),e.keywords&&(0,a$.default)(t),t};eu.get=(t,e="full")=>{let n=(e==="fast"?Ir.fastFormats:Ir.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Mg(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Qc._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Cg.exports=Un=eu;Object.defineProperty(Un,"__esModule",{value:!0});Un.default=eu});var ft=require("fs"),Cu=require("path");var J=require("path"),Vs=require("os"),Dr=require("fs"),Au=require("url"),Y_={};function V_(){return typeof __dirname<"u"?__dirname:(0,J.dirname)((0,Au.fileURLToPath)(Y_.url))}var AP=V_();function Bn(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,J.join)((0,Vs.homedir)(),".claude-mem"),e=(0,J.join)(t,"settings.json");try{if((0,Dr.existsSync)(e)){let r=JSON.parse((0,Dr.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return t}var ae=Bn(),K_=process.env.CLAUDE_CONFIG_DIR||(0,J.join)((0,Vs.homedir)(),".claude"),Ks=(0,J.join)(K_,"plugins","marketplaces","thedotmack"),J_=(0,J.join)(ae,"logs"),Mu=(0,J.join)(ae,"settings.json"),MP=(0,J.join)(ae,"claude-mem.db"),G_=(0,J.join)(ae,"observer-sessions"),CP=(0,J.basename)(G_);var Ce={dataDir:()=>ae,workerPid:()=>(0,J.join)(ae,"worker.pid"),serverPid:()=>(0,J.join)(ae,".server-beta.pid"),serverPort:()=>(0,J.join)(ae,".server-beta.port"),serverRuntime:()=>(0,J.join)(ae,".server-beta.runtime.json"),settings:()=>(0,J.join)(ae,"settings.json"),database:()=>(0,J.join)(ae,"claude-mem.db"),chroma:()=>(0,J.join)(ae,"chroma"),combinedCerts:()=>(0,J.join)(ae,"combined_certs.pem"),transcriptsConfig:()=>(0,J.join)(ae,"transcript-watch.json"),transcriptsState:()=>(0,J.join)(ae,"transcript-watch-state.json"),corpora:()=>(0,J.join)(ae,"corpora"),supervisorRegistry:()=>(0,J.join)(ae,"supervisor.json"),envFile:()=>(0,J.join)(ae,".env"),logsDir:()=>J_};var B_=null;function X_(t){return(B_??process.stderr.write.bind(process.stderr))(t)}function Js(t){X_(t)}var Ys=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Ys||{}),Gs=null,Bs=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=Ce.logsDir();(0,ft.existsSync)(e)||(0,ft.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Cu.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=Ce.settings();if((0,ft.existsSync)(e)){let r=(0,ft.readFileSync)(e,"utf-8"),o=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Ys[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} +${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${i}:${a}.${c}`}log(e,r,n,o,s){if(e0&&(d=` {${Object.entries(S).map(([E,v])=>`${E}=${v}`).join(", ")}}`)}let p=`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`;if(this.logFilePath)try{(0,dt.appendFileSync)(this.logFilePath,p+` -`,"utf8")}catch(f){ei(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)} -`)}else ei(p+` -`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){ti=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!ti||!(n instanceof Error))return;ti(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}happyPathError(e,r,n,o,s=""){let u=((new Error().stack||"").split(` -`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",d={...n,location:l};return this.warn(e,`[HAPPY-PATH] ${r}`,d,o),s}},y=new ni;var Hu;function g(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var rt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},or=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Hu=globalThis).__zod_globalConfig??(Hu.__zod_globalConfig={});var sr=globalThis.__zod_globalConfig;function Oe(t){return t&&Object.assign(sr,t),sr}var U={};Lu(U,{BIGINT_FORMAT_RANGES:()=>Gu,Class:()=>si,NUMBER_FORMAT_RANGES:()=>di,aborted:()=>Tt,allowsEval:()=>ci,assert:()=>vy,assertEqual:()=>gy,assertIs:()=>yy,assertNever:()=>Sy,assertNotEqual:()=>_y,assignProp:()=>$t,base64ToUint8Array:()=>Yu,base64urlToUint8Array:()=>Dy,cached:()=>ar,captureStackTrace:()=>co,cleanEnum:()=>Ny,cleanRegex:()=>Hr,clone:()=>Je,cloneDef:()=>Ey,createTransparentProxy:()=>Ty,defineLazy:()=>H,esc:()=>ao,escapeRegex:()=>ft,explicitlyAborted:()=>pi,extend:()=>Iy,finalizeIssue:()=>je,floatSafeRemainder:()=>ii,getElementAtPath:()=>wy,getEnumValues:()=>Zr,getLengthableOrigin:()=>Wr,getParsedType:()=>Py,getSizableOrigin:()=>Ju,hexToUint8Array:()=>Ly,isObject:()=>Ft,isPlainObject:()=>Pt,issue:()=>cr,joinValues:()=>io,jsonStringifyReplacer:()=>ir,merge:()=>Oy,mergeDefs:()=>pt,normalizeParams:()=>z,nullish:()=>Fr,numKeys:()=>$y,objectClone:()=>by,omit:()=>Ry,optionalKeys:()=>li,parsedType:()=>fi,partial:()=>My,pick:()=>zy,prefixIssues:()=>mt,primitiveTypes:()=>Ku,promiseAllObject:()=>ky,propertyKeyTypes:()=>ui,randomString:()=>xy,required:()=>Cy,safeExtend:()=>Ay,shallowClone:()=>Vu,slugify:()=>ai,stringifyPrimitive:()=>uo,uint8ArrayToBase64:()=>Bu,uint8ArrayToBase64url:()=>jy,uint8ArrayToHex:()=>Uy,unwrapMessage:()=>qr});function gy(t){return t}function _y(t){return t}function yy(t){}function Sy(t){throw new Error("Unexpected value in exhaustive check")}function vy(t){}function Zr(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function io(t,e="|"){return t.map(r=>uo(r)).join(e)}function ir(t,e){return typeof e=="bigint"?e.toString():e}function ar(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Fr(t){return t==null}function Hr(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ii(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)r?.[n],t):t}function ky(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s{};function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ci=ar(()=>{if(sr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Pt(t){if(Ft(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Ft(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Vu(t){return Pt(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function $y(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Py=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ui=new Set(["string","number","symbol"]),Ku=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ft(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Ty(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function uo(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function li(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var di={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]},Gu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function zy(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=pt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function Ry(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=pt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function Iy(t,e){if(!Pt(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=pt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return $t(this,"shape",s),s}});return Je(t,o)}function Ay(t,e){if(!Pt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=pt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return $t(this,"shape",n),n}});return Je(t,r)}function Oy(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=pt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return $t(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Je(t,r)}function My(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=pt(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return $t(this,"shape",c),c},checks:[]});return Je(e,i)}function Cy(t,e,r){let n=pt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return $t(this,"shape",s),s}});return Je(e,n)}function Tt(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function qr(t){return typeof t=="string"?t:t?.message}function je(t,e,r){let n=t.message?t.message:qr(t.inst?._zod.def?.error?.(t))??qr(e?.error?.(t))??qr(r.customError?.(t))??qr(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function Ju(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Wr(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function fi(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function cr(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ny(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Yu(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var si=class{constructor(...e){}};var Xu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,ir,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},lo=g("$ZodError",Xu),mi=g("$ZodError",Xu,{Parent:Error});function Qu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function el(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new rt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>je(c,s,Oe())));throw co(a,o?.callee),a}return i.value};var fo=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>je(c,s,Oe())));throw co(a,o?.callee),a}return i.value};var Vr=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new rt;return s.issues.length?{success:!1,error:new(t??lo)(s.issues.map(i=>je(i,o,Oe())))}:{success:!0,data:s.value}},Kr=Vr(mi),Gr=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>je(i,o,Oe())))}:{success:!0,data:s.value}},mo=Gr(mi),tl=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return po(t)(e,r,o)};var rl=t=>(e,r,n)=>po(t)(e,r,n);var nl=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return fo(t)(e,r,o)};var ol=t=>async(e,r,n)=>fo(t)(e,r,n);var sl=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Vr(t)(e,r,o)};var il=t=>(e,r,n)=>Vr(t)(e,r,n);var al=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Gr(t)(e,r,o)};var cl=t=>async(e,r,n)=>Gr(t)(e,r,n);var ul=/^[cC][0-9a-z]{6,}$/,ll=/^[0-9a-z]+$/,dl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pl=/^[0-9a-vA-V]{20}$/,fl=/^[A-Za-z0-9]{27}$/,ml=/^[a-zA-Z0-9_-]{21}$/,hl=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gl=/^([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})$/,hi=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var _l=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Zy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function yl(){return new RegExp(Zy,"u")}var Sl=/^(?:(?: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])$/,vl=/^(([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}|:))$/;var bl=/^((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])$/,El=/^(([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])$/,wl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gi=/^[A-Za-z0-9_-]*$/;var kl=/^https?$/,xl=/^\+[1-9]\d{6,14}$/,$l="(?:(?:\\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])))",Pl=new RegExp(`^${$l}$`);function Tl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function zl(t){return new RegExp(`^${Tl(t)}$`)}function Rl(t){let e=Tl({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${$l}T(?:${n})$`)}var Il=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Al=/^-?\d+$/,_i=/^-?\d+(?:\.\d+)?$/,Ol=/^(?:true|false)$/i,Ml=/^null$/i;var Cl=/^[^A-Z]*$/,Nl=/^[^a-z]*$/;var fe=g("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Dl={number:"number",bigint:"bigint",object:"date"},yi=g("$ZodCheckLessThan",(t,e)=>{fe.init(t,e);let r=Dl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{fe.init(t,e);let r=Dl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),jl=g("$ZodCheckMultipleOf",(t,e)=>{fe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ii(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ll=g("$ZodCheckNumberFormat",(t,e)=>{fe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=di[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Al)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Ul=g("$ZodCheckMaxLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=n.value;if(o.length<=e.maximum)return;let i=Wr(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ql=g("$ZodCheckMinLength",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Wr(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Zl=g("$ZodCheckLengthEquals",(t,e)=>{var r;fe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Fr(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Wr(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Jr=g("$ZodCheckStringFormat",(t,e)=>{var r,n;fe.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Fl=g("$ZodCheckRegex",(t,e)=>{Jr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Hl=g("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Cl),Jr.init(t,e)}),Wl=g("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Nl),Jr.init(t,e)}),Vl=g("$ZodCheckIncludes",(t,e)=>{fe.init(t,e);let r=ft(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Kl=g("$ZodCheckStartsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`^${ft(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Gl=g("$ZodCheckEndsWith",(t,e)=>{fe.init(t,e);let r=new RegExp(`.*${ft(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Jl=g("$ZodCheckOverwrite",(t,e)=>{fe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var go=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(` +`+JSON.stringify(s,null,2)}catch{l=" "+this.formatData(s)}else l=" "+this.formatData(s);let d="";if(o){let{sessionId:f,memorySessionId:m,correlationId:g,...S}=o;Object.keys(S).length>0&&(d=` {${Object.entries(S).map(([x,b])=>`${x}=${b}`).join(", ")}}`)}let p=`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`;if(this.logFilePath)try{(0,ft.appendFileSync)(this.logFilePath,p+` +`,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));Js(`[LOGGER] Failed to write to log file: ${m.message} +${m.stack??""} +`)}else Js(p+` +`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){Gs=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!Gs||!(n instanceof Error))return;Gs(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},y=new Bs;var Nu;function _(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var rt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},or=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Nu=globalThis).__zod_globalConfig??(Nu.__zod_globalConfig={});var sr=globalThis.__zod_globalConfig;function Re(t){return t&&Object.assign(sr,t),sr}var L={};Ou(L,{BIGINT_FORMAT_RANGES:()=>Uu,Class:()=>Qs,NUMBER_FORMAT_RANGES:()=>si,aborted:()=>Tt,allowsEval:()=>ri,assert:()=>ny,assertEqual:()=>Q_,assertIs:()=>ty,assertNever:()=>ry,assertNotEqual:()=>ey,assignProp:()=>$t,base64ToUint8Array:()=>Zu,base64urlToUint8Array:()=>vy,cached:()=>ar,captureStackTrace:()=>eo,cleanEnum:()=>Sy,cleanRegex:()=>qr,clone:()=>Je,cloneDef:()=>sy,createTransparentProxy:()=>dy,defineLazy:()=>F,esc:()=>Qn,escapeRegex:()=>ht,explicitlyAborted:()=>ii,extend:()=>my,finalizeIssue:()=>Ne,floatSafeRemainder:()=>ei,getElementAtPath:()=>iy,getEnumValues:()=>Lr,getLengthableOrigin:()=>Zr,getParsedType:()=>ly,getSizableOrigin:()=>qu,hexToUint8Array:()=>Ey,isObject:()=>Ft,isPlainObject:()=>Pt,issue:()=>cr,joinValues:()=>Xn,jsonStringifyReplacer:()=>ir,merge:()=>gy,mergeDefs:()=>mt,normalizeParams:()=>z,nullish:()=>Ur,numKeys:()=>uy,objectClone:()=>oy,omit:()=>fy,optionalKeys:()=>oi,parsedType:()=>ai,partial:()=>_y,pick:()=>py,prefixIssues:()=>gt,primitiveTypes:()=>Lu,promiseAllObject:()=>ay,propertyKeyTypes:()=>ni,randomString:()=>cy,required:()=>yy,safeExtend:()=>hy,shallowClone:()=>ju,slugify:()=>ti,stringifyPrimitive:()=>to,uint8ArrayToBase64:()=>Fu,uint8ArrayToBase64url:()=>by,uint8ArrayToHex:()=>wy,unwrapMessage:()=>jr});function Q_(t){return t}function ey(t){return t}function ty(t){}function ry(t){throw new Error("Unexpected value in exhaustive check")}function ny(t){}function Lr(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Xn(t,e="|"){return t.map(r=>to(r)).join(e)}function ir(t,e){return typeof e=="bigint"?e.toString():e}function ar(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ur(t){return t==null}function qr(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ei(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)r?.[n],t):t}function ay(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s{};function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var ri=ar(()=>{if(sr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Pt(t){if(Ft(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Ft(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ju(t){return Pt(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function uy(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var ly=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ni=new Set(["string","number","symbol"]),Lu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ht(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function dy(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function to(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function oi(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var si={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]},Uu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function py(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=mt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function fy(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=mt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return $t(this,"shape",i),i},checks:[]});return Je(t,s)}function my(t,e){if(!Pt(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=mt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return $t(this,"shape",s),s}});return Je(t,o)}function hy(t,e){if(!Pt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=mt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return $t(this,"shape",n),n}});return Je(t,r)}function gy(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=mt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return $t(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Je(t,r)}function _y(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=mt(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return $t(this,"shape",c),c},checks:[]});return Je(e,i)}function yy(t,e,r){let n=mt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return $t(this,"shape",s),s}});return Je(e,n)}function Tt(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function jr(t){return typeof t=="string"?t:t?.message}function Ne(t,e,r){let n=t.message?t.message:jr(t.inst?._zod.def?.error?.(t))??jr(e?.error?.(t))??jr(r.customError?.(t))??jr(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function qu(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Zr(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ai(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function cr(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Sy(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Zu(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var Qs=class{constructor(...e){}};var Hu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,ir,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ro=_("$ZodError",Hu),ci=_("$ZodError",Hu,{Parent:Error});function Wu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Vu(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new rt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ne(c,s,Re())));throw eo(a,o?.callee),a}return i.value};var oo=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ne(c,s,Re())));throw eo(a,o?.callee),a}return i.value};var Fr=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new rt;return s.issues.length?{success:!1,error:new(t??ro)(s.issues.map(i=>Ne(i,o,Re())))}:{success:!0,data:s.value}},Hr=Fr(ci),Wr=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Ne(i,o,Re())))}:{success:!0,data:s.value}},so=Wr(ci),Ku=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return no(t)(e,r,o)};var Ju=t=>(e,r,n)=>no(t)(e,r,n);var Gu=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return oo(t)(e,r,o)};var Yu=t=>async(e,r,n)=>oo(t)(e,r,n);var Bu=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Fr(t)(e,r,o)};var Xu=t=>(e,r,n)=>Fr(t)(e,r,n);var Qu=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Wr(t)(e,r,o)};var el=t=>async(e,r,n)=>Wr(t)(e,r,n);var tl=/^[cC][0-9a-z]{6,}$/,rl=/^[0-9a-z]+$/,nl=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ol=/^[0-9a-vA-V]{20}$/,sl=/^[A-Za-z0-9]{27}$/,il=/^[a-zA-Z0-9_-]{21}$/,al=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var cl=/^([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})$/,ui=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var ul=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var xy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ll(){return new RegExp(xy,"u")}var dl=/^(?:(?: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])$/,pl=/^(([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}|:))$/;var fl=/^((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])$/,ml=/^(([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])$/,hl=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,li=/^[A-Za-z0-9_-]*$/;var gl=/^https?$/,_l=/^\+[1-9]\d{6,14}$/,yl="(?:(?:\\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])))",Sl=new RegExp(`^${yl}$`);function vl(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function bl(t){return new RegExp(`^${vl(t)}$`)}function El(t){let e=vl({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${yl}T(?:${n})$`)}var wl=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var kl=/^-?\d+$/,di=/^-?\d+(?:\.\d+)?$/,xl=/^(?:true|false)$/i,$l=/^null$/i;var Pl=/^[^A-Z]*$/,Tl=/^[^a-z]*$/;var de=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),zl={number:"number",bigint:"bigint",object:"date"},pi=_("$ZodCheckLessThan",(t,e)=>{de.init(t,e);let r=zl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{de.init(t,e);let r=zl[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Rl=_("$ZodCheckMultipleOf",(t,e)=>{de.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ei(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Il=_("$ZodCheckNumberFormat",(t,e)=>{de.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=si[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=kl)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Ol=_("$ZodCheckMaxLength",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let o=n.value;if(o.length<=e.maximum)return;let i=Zr(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Al=_("$ZodCheckMinLength",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Zr(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ml=_("$ZodCheckLengthEquals",(t,e)=>{var r;de.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ur(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Zr(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Vr=_("$ZodCheckStringFormat",(t,e)=>{var r,n;de.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Cl=_("$ZodCheckRegex",(t,e)=>{Vr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Nl=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Pl),Vr.init(t,e)}),Dl=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Tl),Vr.init(t,e)}),jl=_("$ZodCheckIncludes",(t,e)=>{de.init(t,e);let r=ht(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Ll=_("$ZodCheckStartsWith",(t,e)=>{de.init(t,e);let r=new RegExp(`^${ht(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Ul=_("$ZodCheckEndsWith",(t,e)=>{de.init(t,e);let r=new RegExp(`.*${ht(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var ql=_("$ZodCheckOverwrite",(t,e)=>{de.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ao=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(` `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(` -`))}};var Bl={major:4,minor:4,patch:3};var J=g("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Bl;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Tt(i),l;for(let d of a){if(d._zod.def.when){if(pi(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new rt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Tt(i,p)))});else{if(i.issues.length===p)continue;u||(u=Tt(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Tt(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new rt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new rt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}H(t,"~standard",()=>({validate:o=>{try{let s=Kr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return mo(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),So=g("$ZodString",(t,e)=>{J.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Il(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Y=g("$ZodStringFormat",(t,e)=>{Jr.init(t,e),So.init(t,e)}),id=g("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=gl),Y.init(t,e)}),ad=g("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=hi(n))}else e.pattern??(e.pattern=hi());Y.init(t,e)}),cd=g("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=_l),Y.init(t,e)}),ud=g("$ZodURL",(t,e)=>{Y.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===kl.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ld=g("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=yl()),Y.init(t,e)}),dd=g("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ml),Y.init(t,e)}),pd=g("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ul),Y.init(t,e)}),fd=g("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ll),Y.init(t,e)}),md=g("$ZodULID",(t,e)=>{e.pattern??(e.pattern=dl),Y.init(t,e)}),hd=g("$ZodXID",(t,e)=>{e.pattern??(e.pattern=pl),Y.init(t,e)}),gd=g("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=fl),Y.init(t,e)}),_d=g("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Rl(e)),Y.init(t,e)}),yd=g("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Pl),Y.init(t,e)}),Sd=g("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=zl(e)),Y.init(t,e)}),vd=g("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hl),Y.init(t,e)}),bd=g("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Sl),Y.init(t,e),t._zod.bag.format="ipv4"}),Ed=g("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=vl),Y.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var wd=g("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=bl),Y.init(t,e)}),kd=g("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=El),Y.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function xd(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var $d=g("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=wl),Y.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{xd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Wy(t){if(!gi.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return xd(r)}var Pd=g("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=gi),Y.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{Wy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Td=g("$ZodE164",(t,e)=>{e.pattern??(e.pattern=xl),Y.init(t,e)});function Vy(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var zd=g("$ZodJWT",(t,e)=>{Y.init(t,e),t._zod.check=r=>{Vy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var bi=g("$ZodNumber",(t,e)=>{J.init(t,e),t._zod.pattern=t._zod.bag.pattern??_i,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Rd=g("$ZodNumberFormat",(t,e)=>{Ll.init(t,e),bi.init(t,e)}),Id=g("$ZodBoolean",(t,e)=>{J.init(t,e),t._zod.pattern=Ol,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var Ad=g("$ZodNull",(t,e)=>{J.init(t,e),t._zod.pattern=Ml,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var Od=g("$ZodUnknown",(t,e)=>{J.init(t,e),t._zod.parse=r=>r}),Md=g("$ZodNever",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Xl(t,e,r){t.issues.length&&e.issues.push(...mt(r,t.issues)),e.value[r]=t.value}var Cd=g("$ZodArray",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;iXl(u,r,i))):Xl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function yo(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...mt(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Nd(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=li(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Dd(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(m=>yo(m,r,p,e,l,d))):yo(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var Ky=g("$ZodObject",(t,e)=>{if(J.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=ar(()=>Nd(e));H(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Ft,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],m=f._zod.optin==="optional",_=f._zod.optout==="optional",S=f._zod.run({value:u[p],issues:[]},c);S instanceof Promise?l.push(S.then(b=>yo(b,a,p,u,m,_))):yo(S,a,p,u,m,_)}return s?Dd(l,u,a,c,n.value,t):l.length?Promise.all(l).then(()=>a):a}}),jd=g("$ZodObjectJIT",(t,e)=>{Ky.init(t,e);let r=t._zod.parse,n=ar(()=>Nd(e)),o=p=>{let f=new go(["shape","payload","ctx"]),m=n.value,_=v=>{let $=ao(v);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let S=Object.create(null),b=0;for(let v of m.keys)S[v]=`key_${b++}`;f.write("const newResult = {};");for(let v of m.keys){let $=S[v],x=ao(v),Se=p[v],we=Se?._zod?.optin==="optional",Zt=Se?._zod?.optout==="optional";f.write(`const ${$} = ${_(v)};`),we&&Zt?f.write(` +`))}};var Fl={major:4,minor:4,patch:3};var Y=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Fl;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Tt(i),l;for(let d of a){if(d._zod.def.when){if(ii(i)||!d._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=d._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new rt;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Tt(i,p)))});else{if(i.issues.length===p)continue;u||(u=Tt(i,p))}}return l?l.then(()=>i):i},s=(i,a,c)=>{if(Tt(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new rt;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new rt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}F(t,"~standard",()=>({validate:o=>{try{let s=Hr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return so(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),lo=_("$ZodString",(t,e)=>{Y.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??wl(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),B=_("$ZodStringFormat",(t,e)=>{Vr.init(t,e),lo.init(t,e)}),Xl=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=cl),B.init(t,e)}),Ql=_("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ui(n))}else e.pattern??(e.pattern=ui());B.init(t,e)}),ed=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ul),B.init(t,e)}),td=_("$ZodURL",(t,e)=>{B.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===gl.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),rd=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ll()),B.init(t,e)}),nd=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=il),B.init(t,e)}),od=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=tl),B.init(t,e)}),sd=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=rl),B.init(t,e)}),id=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=nl),B.init(t,e)}),ad=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ol),B.init(t,e)}),cd=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=sl),B.init(t,e)}),ud=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=El(e)),B.init(t,e)}),ld=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sl),B.init(t,e)}),dd=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=bl(e)),B.init(t,e)}),pd=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=al),B.init(t,e)}),fd=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=dl),B.init(t,e),t._zod.bag.format="ipv4"}),md=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=pl),B.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var hd=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=fl),B.init(t,e)}),gd=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ml),B.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function _d(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var yd=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=hl),B.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{_d(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function Ty(t){if(!li.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return _d(r)}var Sd=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=li),B.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{Ty(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),vd=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=_l),B.init(t,e)});function zy(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var bd=_("$ZodJWT",(t,e)=>{B.init(t,e),t._zod.check=r=>{zy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var hi=_("$ZodNumber",(t,e)=>{Y.init(t,e),t._zod.pattern=t._zod.bag.pattern??di,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Ed=_("$ZodNumberFormat",(t,e)=>{Il.init(t,e),hi.init(t,e)}),wd=_("$ZodBoolean",(t,e)=>{Y.init(t,e),t._zod.pattern=xl,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var kd=_("$ZodNull",(t,e)=>{Y.init(t,e),t._zod.pattern=$l,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var xd=_("$ZodUnknown",(t,e)=>{Y.init(t,e),t._zod.parse=r=>r}),$d=_("$ZodNever",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Hl(t,e,r){t.issues.length&&e.issues.push(...gt(r,t.issues)),e.value[r]=t.value}var Pd=_("$ZodArray",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;iHl(u,r,i))):Hl(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function uo(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...gt(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Td(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=oi(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function zd(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(m=>uo(m,r,p,e,l,d))):uo(f,r,p,e,l,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var Ry=_("$ZodObject",(t,e)=>{if(Y.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=ar(()=>Td(e));F(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Ft,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=i.shape;for(let p of i.keys){let f=d[p],m=f._zod.optin==="optional",g=f._zod.optout==="optional",S=f._zod.run({value:u[p],issues:[]},c);S instanceof Promise?l.push(S.then(v=>uo(v,a,p,u,m,g))):uo(S,a,p,u,m,g)}return s?zd(l,u,a,c,n.value,t):l.length?Promise.all(l).then(()=>a):a}}),Rd=_("$ZodObjectJIT",(t,e)=>{Ry.init(t,e);let r=t._zod.parse,n=ar(()=>Td(e)),o=p=>{let f=new ao(["shape","payload","ctx"]),m=n.value,g=b=>{let $=Qn(b);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};f.write("const input = payload.value;");let S=Object.create(null),v=0;for(let b of m.keys)S[b]=`key_${v++}`;f.write("const newResult = {};");for(let b of m.keys){let $=S[b],k=Qn(b),_e=p[b],V=_e?._zod?.optin==="optional",tt=_e?._zod?.optout==="optional";f.write(`const ${$} = ${g(b)};`),V&&tt?f.write(` if (${$}.issues.length) { - if (${x} in input) { + if (${k} in input) { payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${x}, ...iss.path] : [${x}] + path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } } if (${$}.value === undefined) { - if (${x} in input) { - newResult[${x}] = undefined; + if (${k} in input) { + newResult[${k}] = undefined; } } else { - newResult[${x}] = ${$}.value; + newResult[${k}] = ${$}.value; } - `):we?f.write(` + `):V?f.write(` if (${$}.issues.length) { payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${x}, ...iss.path] : [${x}] + path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (${$}.value === undefined) { - if (${x} in input) { - newResult[${x}] = undefined; + if (${k} in input) { + newResult[${k}] = undefined; } } else { - newResult[${x}] = ${$}.value; + newResult[${k}] = ${$}.value; } `):f.write(` - const ${$}_present = ${x} in input; + const ${$}_present = ${k} in input; if (${$}.issues.length) { payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ ...iss, - path: iss.path ? [${x}, ...iss.path] : [${x}] + path: iss.path ? [${k}, ...iss.path] : [${k}] }))); } if (!${$}_present && !${$}.issues.length) { @@ -63,23 +63,23 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{ code: "invalid_type", expected: "nonoptional", input: undefined, - path: [${x}] + path: [${k}] }); } if (${$}_present) { if (${$}.value === undefined) { - newResult[${x}] = undefined; + newResult[${k}] = undefined; } else { - newResult[${x}] = ${$}.value; + newResult[${k}] = ${$}.value; } } - `)}f.write("payload.value = newResult;"),f.write("return payload;");let E=f.compile();return(v,$)=>E(p,v,$)},s,i=Ft,a=!sr.jitless,u=a&&ci.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return i(m)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),l?Dd([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function Ql(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Tt(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>je(i,n,Oe())))}),e)}var Ei=g("$ZodUnion",(t,e)=>{J.init(t,e),H(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),H(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),H(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),H(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>Hr(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>Ql(a,n,t,o)):Ql(i,n,t,o)}});var Ld=g("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ei.init(t,e);let r=t._zod.parse;H(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=ar(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ft(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Ud=g("$ZodIntersection",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>ed(r,c,u)):ed(r,s,i)}});function vi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Pt(t)&&Pt(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=vi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;na.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Tt(t))return t;let i=vi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var qd=g("$ZodRecord",(t,e)=>{J.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Pt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>je(f,n,Oe())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...mt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...mt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&_i.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>je(d,n,Oe())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...mt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...mt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Zd=g("$ZodEnum",(t,e)=>{J.init(t,e);let r=Zr(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>ui.has(typeof o)).map(o=>typeof o=="string"?ft(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Fd=g("$ZodLiteral",(t,e)=>{if(J.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ft(n):n?ft(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var Hd=g("$ZodTransform",(t,e)=>{J.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new rt;return r.value=o,r.fallback=!0,r}});function td(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var wi=g("$ZodOptional",(t,e)=>{J.init(t,e),t._zod.optin="optional",t._zod.optout="optional",H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Hr(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>td(i,o)):td(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Wd=g("$ZodExactOptional",(t,e)=>{wi.init(t,e),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),Vd=g("$ZodNullable",(t,e)=>{J.init(t,e),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Hr(r.source)}|null)$`):void 0}),H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Kd=g("$ZodDefault",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>rd(s,e)):rd(o,e)}});function rd(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Gd=g("$ZodPrefault",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Jd=g("$ZodNonOptional",(t,e)=>{J.init(t,e),H(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>nd(s,t)):nd(o,t)}});function nd(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Yd=g("$ZodCatch",(t,e)=>{J.init(t,e),t._zod.optin="optional",H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>je(i,n,Oe()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>je(s,n,Oe()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var ki=g("$ZodPipe",(t,e)=>{J.init(t,e),H(t._zod,"values",()=>e.in._zod.values),H(t._zod,"optin",()=>e.in._zod.optin),H(t._zod,"optout",()=>e.out._zod.optout),H(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>_o(i,e.in,n)):_o(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>_o(s,e.out,n)):_o(o,e.out,n)}});function _o(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var Bd=g("$ZodPreprocess",(t,e)=>{ki.init(t,e)}),Xd=g("$ZodReadonly",(t,e)=>{J.init(t,e),H(t._zod,"propValues",()=>e.innerType._zod.propValues),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"optin",()=>e.innerType?._zod?.optin),H(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(od):od(o)}});function od(t){return t.value=Object.freeze(t.value),t}var Qd=g("$ZodCustom",(t,e)=>{fe.init(t,e),J.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>sd(s,r,n,t));sd(o,r,n,t)}});function sd(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(cr(o))}}var Gy=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,i=fi(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${uo(o.values[0])}`:`Invalid option: expected one of ${io(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${io(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function ep(){return{localeError:Gy()}}var tp;var xi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Jy(){return new xi}(tp=globalThis).__zod_globalRegistry??(tp.__zod_globalRegistry=Jy());var Ht=globalThis.__zod_globalRegistry;function rp(t,e){return new t({type:"string",...z(e)})}function np(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function $i(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function op(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function sp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function ip(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function ap(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function cp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function up(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function lp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function dp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function pp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function fp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function mp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function hp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function gp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function _p(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function yp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function Sp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function vp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function bp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function Ep(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function wp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}function kp(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function xp(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function $p(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function Pp(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function Tp(t,e){return new t({type:"number",checks:[],...z(e)})}function zp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function Rp(t,e){return new t({type:"boolean",...z(e)})}function Ip(t,e){return new t({type:"null",...z(e)})}function Ap(t){return new t({type:"unknown"})}function Op(t,e){return new t({type:"never",...z(e)})}function vo(t,e){return new yi({check:"less_than",...z(e),value:t,inclusive:!1})}function Yr(t,e){return new yi({check:"less_than",...z(e),value:t,inclusive:!0})}function bo(t,e){return new Si({check:"greater_than",...z(e),value:t,inclusive:!1})}function Br(t,e){return new Si({check:"greater_than",...z(e),value:t,inclusive:!0})}function Eo(t,e){return new jl({check:"multiple_of",...z(e),value:t})}function wo(t,e){return new Ul({check:"max_length",...z(e),maximum:t})}function ur(t,e){return new ql({check:"min_length",...z(e),minimum:t})}function ko(t,e){return new Zl({check:"length_equals",...z(e),length:t})}function Pi(t,e){return new Fl({check:"string_format",format:"regex",...z(e),pattern:t})}function Ti(t){return new Hl({check:"string_format",format:"lowercase",...z(t)})}function zi(t){return new Wl({check:"string_format",format:"uppercase",...z(t)})}function Ri(t,e){return new Vl({check:"string_format",format:"includes",...z(e),includes:t})}function Ii(t,e){return new Kl({check:"string_format",format:"starts_with",...z(e),prefix:t})}function Ai(t,e){return new Gl({check:"string_format",format:"ends_with",...z(e),suffix:t})}function zt(t){return new Jl({check:"overwrite",tx:t})}function Oi(t){return zt(e=>e.normalize(t))}function Mi(){return zt(t=>t.trim())}function Ci(){return zt(t=>t.toLowerCase())}function Ni(){return zt(t=>t.toUpperCase())}function Di(){return zt(t=>ai(t))}function Mp(t,e,r){return new t({type:"array",element:e,...z(r)})}function Cp(t,e,r){let n=z(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Np(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function Dp(t,e){let r=Yy(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(cr(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(cr(s))}},t(n.value,n)),e);return r}function Yy(t,e){let r=new fe({check:"custom",...z(e)});return r._zod.check=t,r}function ji(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ht,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function se(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),se(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&ke(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Li(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ + `)}f.write("payload.value = newResult;"),f.write("return payload;");let x=f.compile();return(b,$)=>x(p,b,$)},s,i=Ft,a=!sr.jitless,u=a&&ri.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return i(m)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),l?zd([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function Wl(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Tt(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>Ne(i,n,Re())))}),e)}var gi=_("$ZodUnion",(t,e)=>{Y.init(t,e),F(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),F(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),F(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),F(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>qr(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>Wl(a,n,t,o)):Wl(i,n,t,o)}});var Id=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,gi.init(t,e);let r=t._zod.parse;F(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=ar(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ft(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Od=_("$ZodIntersection",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Vl(r,c,u)):Vl(r,s,i)}});function mi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Pt(t)&&Pt(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=mi(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;na.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Tt(t))return t;let i=mi(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Ad=_("$ZodRecord",(t,e)=>{Y.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Pt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.keyType._zod.run({value:u,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>Ne(f,n,Re())),input:u,path:[u],inst:t});continue}let d=l.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...gt(u,f.issues)),r.value[d]=f.value})):(p.issues.length&&r.issues.push(...gt(u,p.issues)),r.value[d]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&di.test(a)&&c.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Ne(d,n,Re())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...gt(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...gt(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Md=_("$ZodEnum",(t,e)=>{Y.init(t,e);let r=Lr(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>ni.has(typeof o)).map(o=>typeof o=="string"?ht(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Cd=_("$ZodLiteral",(t,e)=>{if(Y.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ht(n):n?ht(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var Nd=_("$ZodTransform",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new rt;return r.value=o,r.fallback=!0,r}});function Kl(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var _i=_("$ZodOptional",(t,e)=>{Y.init(t,e),t._zod.optin="optional",t._zod.optout="optional",F(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),F(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${qr(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>Kl(i,o)):Kl(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Dd=_("$ZodExactOptional",(t,e)=>{_i.init(t,e),F(t._zod,"values",()=>e.innerType._zod.values),F(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),jd=_("$ZodNullable",(t,e)=>{Y.init(t,e),F(t._zod,"optin",()=>e.innerType._zod.optin),F(t._zod,"optout",()=>e.innerType._zod.optout),F(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${qr(r.source)}|null)$`):void 0}),F(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ld=_("$ZodDefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Jl(s,e)):Jl(o,e)}});function Jl(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ud=_("$ZodPrefault",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),qd=_("$ZodNonOptional",(t,e)=>{Y.init(t,e),F(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Gl(s,t)):Gl(o,t)}});function Gl(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Zd=_("$ZodCatch",(t,e)=>{Y.init(t,e),t._zod.optin="optional",F(t._zod,"optout",()=>e.innerType._zod.optout),F(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Ne(i,n,Re()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Ne(s,n,Re()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var yi=_("$ZodPipe",(t,e)=>{Y.init(t,e),F(t._zod,"values",()=>e.in._zod.values),F(t._zod,"optin",()=>e.in._zod.optin),F(t._zod,"optout",()=>e.out._zod.optout),F(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>co(i,e.in,n)):co(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>co(s,e.out,n)):co(o,e.out,n)}});function co(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var Fd=_("$ZodPreprocess",(t,e)=>{yi.init(t,e)}),Hd=_("$ZodReadonly",(t,e)=>{Y.init(t,e),F(t._zod,"propValues",()=>e.innerType._zod.propValues),F(t._zod,"values",()=>e.innerType._zod.values),F(t._zod,"optin",()=>e.innerType?._zod?.optin),F(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Yl):Yl(o)}});function Yl(t){return t.value=Object.freeze(t.value),t}var Wd=_("$ZodCustom",(t,e)=>{de.init(t,e),Y.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Bl(s,r,n,t));Bl(o,r,n,t)}});function Bl(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(cr(o))}}var Iy=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,i=ai(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${to(o.values[0])}`:`Invalid option: expected one of ${Xn(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Xn(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Vd(){return{localeError:Iy()}}var Kd;var Si=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Oy(){return new Si}(Kd=globalThis).__zod_globalRegistry??(Kd.__zod_globalRegistry=Oy());var Ht=globalThis.__zod_globalRegistry;function Jd(t,e){return new t({type:"string",...z(e)})}function Gd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function vi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function Yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function Bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function Xd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function Qd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function ep(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function tp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function rp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function np(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function op(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function sp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function ip(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function ap(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function cp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function up(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function lp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function dp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function pp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function fp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function mp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function hp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}function gp(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function _p(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function yp(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function Sp(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function vp(t,e){return new t({type:"number",checks:[],...z(e)})}function bp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function Ep(t,e){return new t({type:"boolean",...z(e)})}function wp(t,e){return new t({type:"null",...z(e)})}function kp(t){return new t({type:"unknown"})}function xp(t,e){return new t({type:"never",...z(e)})}function po(t,e){return new pi({check:"less_than",...z(e),value:t,inclusive:!1})}function Kr(t,e){return new pi({check:"less_than",...z(e),value:t,inclusive:!0})}function fo(t,e){return new fi({check:"greater_than",...z(e),value:t,inclusive:!1})}function Jr(t,e){return new fi({check:"greater_than",...z(e),value:t,inclusive:!0})}function mo(t,e){return new Rl({check:"multiple_of",...z(e),value:t})}function ho(t,e){return new Ol({check:"max_length",...z(e),maximum:t})}function ur(t,e){return new Al({check:"min_length",...z(e),minimum:t})}function go(t,e){return new Ml({check:"length_equals",...z(e),length:t})}function bi(t,e){return new Cl({check:"string_format",format:"regex",...z(e),pattern:t})}function Ei(t){return new Nl({check:"string_format",format:"lowercase",...z(t)})}function wi(t){return new Dl({check:"string_format",format:"uppercase",...z(t)})}function ki(t,e){return new jl({check:"string_format",format:"includes",...z(e),includes:t})}function xi(t,e){return new Ll({check:"string_format",format:"starts_with",...z(e),prefix:t})}function $i(t,e){return new Ul({check:"string_format",format:"ends_with",...z(e),suffix:t})}function zt(t){return new ql({check:"overwrite",tx:t})}function Pi(t){return zt(e=>e.normalize(t))}function Ti(){return zt(t=>t.trim())}function zi(){return zt(t=>t.toLowerCase())}function Ri(){return zt(t=>t.toUpperCase())}function Ii(){return zt(t=>ti(t))}function $p(t,e,r){return new t({type:"array",element:e,...z(r)})}function Pp(t,e,r){let n=z(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Tp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...z(r)})}function zp(t,e){let r=Ay(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(cr(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(cr(s))}},t(n.value,n)),e);return r}function Ay(t,e){let r=new de({check:"custom",...z(e)});return r._zod.check=t,r}function Oi(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Ht,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function se(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,l);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(i.ref||(i.ref=d),se(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&be(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Ai(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(i[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,l=i[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Ui(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(m.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let p=a._zod.parent;if(p&&p!==d){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Xr(e,"input",t.processors),output:Xr(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ke(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ke(n.element,r);if(n.type==="set")return ke(n.valueType,r);if(n.type==="lazy")return ke(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ke(n.innerType,r);if(n.type==="intersection")return ke(n.left,r)||ke(n.right,r);if(n.type==="record"||n.type==="map")return ke(n.keyType,r)||ke(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:ke(n.in,r)||ke(n.out,r);if(n.type==="object"){for(let o in n.shape)if(ke(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ke(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ke(o,r))return!0;return!!(n.rest&&ke(n.rest,r))}return!1}var jp=(t,e={})=>r=>{let n=ji({...r,processors:e});return se(t,n),Li(n,t),Ui(n,t)},Xr=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ji({...o??{},target:s,io:e,processors:r});return se(t,i),Li(i,t),Ui(i,t)};var By={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Lp=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=By[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Up=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},qp=(t,e,r,n)=>{r.type="boolean"};var Zp=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Fp=(t,e,r,n)=>{r.not={}};var Hp=(t,e,r,n)=>{};var Wp=(t,e,r,n)=>{let o=t._zod.def,s=Zr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},Vp=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var Kp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Gp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Jp=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=se(s.element,e,{...n,path:[...n.path,"items"]})},Yp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=se(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=se(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Bp=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>se(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Xp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=se(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var Qp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=se(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=se(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=se(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},ef=(t,e,r,n)=>{let o=t._zod.def,s=se(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},tf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},rf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},nf=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},of=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},sf=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;se(i,e,n);let a=e.seen.get(t);a.ref=i},af=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var qi=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function lr(t){return!!t._zod}function Rt(t,e){return lr(t)?Kr(t,e):t.safeParse(e)}function xo(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function cf(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var en={};Lu(en,{ZodISODate:()=>lf,ZodISODateTime:()=>uf,ZodISODuration:()=>pf,ZodISOTime:()=>df,date:()=>Fi,datetime:()=>Zi,duration:()=>Wi,time:()=>Hi});var uf=g("ZodISODateTime",(t,e)=>{_d.init(t,e),te.init(t,e)});function Zi(t){return kp(uf,t)}var lf=g("ZodISODate",(t,e)=>{yd.init(t,e),te.init(t,e)});function Fi(t){return xp(lf,t)}var df=g("ZodISOTime",(t,e)=>{Sd.init(t,e),te.init(t,e)});function Hi(t){return $p(df,t)}var pf=g("ZodISODuration",(t,e)=>{vd.init(t,e),te.init(t,e)});function Wi(t){return Pp(pf,t)}var iS=(t,e)=>{lo.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>el(t,r)},flatten:{value:r=>Qu(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ir,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ir,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Me=g("ZodError",iS,{Parent:Error});var ff=po(Me),mf=fo(Me),hf=Vr(Me),gf=Gr(Me),_f=tl(Me),yf=rl(Me),Sf=nl(Me),vf=ol(Me),bf=sl(Me),Ef=il(Me),wf=al(Me),kf=cl(Me);var xf=new WeakMap;function tn(t,e,r){let n=Object.getPrototypeOf(t),o=xf.get(n);if(o||(o=new Set,xf.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=g("ZodType",(t,e)=>(J.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Xr(t,"input"),output:Xr(t,"output")}}),t.toJSONSchema=jp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>ff(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>hf(t,r,n),t.parseAsync=async(r,n)=>mf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>gf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>_f(t,r,n),t.decode=(r,n)=>yf(t,r,n),t.encodeAsync=async(r,n)=>Sf(t,r,n),t.decodeAsync=async(r,n)=>vf(t,r,n),t.safeEncode=(r,n)=>bf(t,r,n),t.safeDecode=(r,n)=>Ef(t,r,n),t.safeEncodeAsync=async(r,n)=>wf(t,r,n),t.safeDecodeAsync=async(r,n)=>kf(t,r,n),tn(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Je(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(YS(r,n))},superRefine(r,n){return this.check(BS(r,n))},overwrite(r){return this.check(zt(r))},optional(){return ne(this)},exactOptional(){return jS(this)},nullable(){return zf(this)},nullish(){return ne(zf(this))},nonoptional(r){return HS(this,r)},array(){return D(this)},or(r){return B([this,r])},and(r){return Po(this,r)},transform(r){return Rf(this,Nf(r))},default(r){return qS(this,r)},prefault(r){return FS(this,r)},catch(r){return VS(this,r)},pipe(r){return Rf(this,r)},readonly(){return JS(this)},describe(r){let n=this.clone();return Ht.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ht.get(this);let n=this.clone();return Ht.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ht.get(t)?.description},configurable:!0}),t)),If=g("_ZodString",(t,e)=>{So.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Lp(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,tn(t,"_ZodString",{regex(...n){return this.check(Pi(...n))},includes(...n){return this.check(Ri(...n))},startsWith(...n){return this.check(Ii(...n))},endsWith(...n){return this.check(Ai(...n))},min(...n){return this.check(ur(...n))},max(...n){return this.check(wo(...n))},length(...n){return this.check(ko(...n))},nonempty(...n){return this.check(ur(1,...n))},lowercase(n){return this.check(Ti(n))},uppercase(n){return this.check(zi(n))},trim(){return this.check(Mi())},normalize(...n){return this.check(Oi(...n))},toLowerCase(){return this.check(Ci())},toUpperCase(){return this.check(Ni())},slugify(){return this.check(Di())}})}),cS=g("ZodString",(t,e)=>{So.init(t,e),If.init(t,e),t.email=r=>t.check(np(uS,r)),t.url=r=>t.check(cp(lS,r)),t.jwt=r=>t.check(wp(xS,r)),t.emoji=r=>t.check(up(dS,r)),t.guid=r=>t.check($i($f,r)),t.uuid=r=>t.check(op($o,r)),t.uuidv4=r=>t.check(sp($o,r)),t.uuidv6=r=>t.check(ip($o,r)),t.uuidv7=r=>t.check(ap($o,r)),t.nanoid=r=>t.check(lp(pS,r)),t.guid=r=>t.check($i($f,r)),t.cuid=r=>t.check(dp(fS,r)),t.cuid2=r=>t.check(pp(mS,r)),t.ulid=r=>t.check(fp(hS,r)),t.base64=r=>t.check(vp(ES,r)),t.base64url=r=>t.check(bp(wS,r)),t.xid=r=>t.check(mp(gS,r)),t.ksuid=r=>t.check(hp(_S,r)),t.ipv4=r=>t.check(gp(yS,r)),t.ipv6=r=>t.check(_p(SS,r)),t.cidrv4=r=>t.check(yp(vS,r)),t.cidrv6=r=>t.check(Sp(bS,r)),t.e164=r=>t.check(Ep(kS,r)),t.datetime=r=>t.check(Zi(r)),t.date=r=>t.check(Fi(r)),t.time=r=>t.check(Hi(r)),t.duration=r=>t.check(Wi(r))});function h(t){return rp(cS,t)}var te=g("ZodStringFormat",(t,e)=>{Y.init(t,e),If.init(t,e)}),uS=g("ZodEmail",(t,e)=>{cd.init(t,e),te.init(t,e)});var $f=g("ZodGUID",(t,e)=>{id.init(t,e),te.init(t,e)});var $o=g("ZodUUID",(t,e)=>{ad.init(t,e),te.init(t,e)});var lS=g("ZodURL",(t,e)=>{ud.init(t,e),te.init(t,e)});var dS=g("ZodEmoji",(t,e)=>{ld.init(t,e),te.init(t,e)});var pS=g("ZodNanoID",(t,e)=>{dd.init(t,e),te.init(t,e)});var fS=g("ZodCUID",(t,e)=>{pd.init(t,e),te.init(t,e)});var mS=g("ZodCUID2",(t,e)=>{fd.init(t,e),te.init(t,e)});var hS=g("ZodULID",(t,e)=>{md.init(t,e),te.init(t,e)});var gS=g("ZodXID",(t,e)=>{hd.init(t,e),te.init(t,e)});var _S=g("ZodKSUID",(t,e)=>{gd.init(t,e),te.init(t,e)});var yS=g("ZodIPv4",(t,e)=>{bd.init(t,e),te.init(t,e)});var SS=g("ZodIPv6",(t,e)=>{Ed.init(t,e),te.init(t,e)});var vS=g("ZodCIDRv4",(t,e)=>{wd.init(t,e),te.init(t,e)});var bS=g("ZodCIDRv6",(t,e)=>{kd.init(t,e),te.init(t,e)});var ES=g("ZodBase64",(t,e)=>{$d.init(t,e),te.init(t,e)});var wS=g("ZodBase64URL",(t,e)=>{Pd.init(t,e),te.init(t,e)});var kS=g("ZodE164",(t,e)=>{Td.init(t,e),te.init(t,e)});var xS=g("ZodJWT",(t,e)=>{zd.init(t,e),te.init(t,e)});var Af=g("ZodNumber",(t,e)=>{bi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Up(t,n,o,s),tn(t,"ZodNumber",{gt(n,o){return this.check(bo(n,o))},gte(n,o){return this.check(Br(n,o))},min(n,o){return this.check(Br(n,o))},lt(n,o){return this.check(vo(n,o))},lte(n,o){return this.check(Yr(n,o))},max(n,o){return this.check(Yr(n,o))},int(n){return this.check(Pf(n))},safe(n){return this.check(Pf(n))},positive(n){return this.check(bo(0,n))},nonnegative(n){return this.check(Br(0,n))},negative(n){return this.check(vo(0,n))},nonpositive(n){return this.check(Yr(0,n))},multipleOf(n,o){return this.check(Eo(n,o))},step(n,o){return this.check(Eo(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function W(t){return Tp(Af,t)}var $S=g("ZodNumberFormat",(t,e)=>{Rd.init(t,e),Af.init(t,e)});function Pf(t){return zp($S,t)}var PS=g("ZodBoolean",(t,e)=>{Id.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qp(t,r,n,o)});function de(t){return Rp(PS,t)}var TS=g("ZodNull",(t,e)=>{Ad.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zp(t,r,n,o)});function Of(t){return Ip(TS,t)}var zS=g("ZodUnknown",(t,e)=>{Od.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hp(t,r,n,o)});function re(){return Ap(zS)}var RS=g("ZodNever",(t,e)=>{Md.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fp(t,r,n,o)});function IS(t){return Op(RS,t)}var AS=g("ZodArray",(t,e)=>{Cd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o),t.element=e.element,tn(t,"ZodArray",{min(r,n){return this.check(ur(r,n))},nonempty(r){return this.check(ur(1,r))},max(r,n){return this.check(wo(r,n))},length(r,n){return this.check(ko(r,n))},unwrap(){return this.element}})});function D(t,e){return Mp(AS,t,e)}var Mf=g("ZodObject",(t,e)=>{jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),tn(t,"ZodObject",{keyof(){return Te(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:re()})},loose(){return this.clone({...this._zod.def,catchall:re()})},strict(){return this.clone({...this._zod.def,catchall:IS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(Df,this,r[0])},required(...r){return U.required(jf,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new Mf(r)}function xe(t,e){return new Mf({type:"object",shape:t,catchall:re(),...U.normalizeParams(e)})}var Cf=g("ZodUnion",(t,e)=>{Ei.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bp(t,r,n,o),t.options=e.options});function B(t,e){return new Cf({type:"union",options:t,...U.normalizeParams(e)})}var OS=g("ZodDiscriminatedUnion",(t,e)=>{Cf.init(t,e),Ld.init(t,e)});function Ki(t,e,r){return new OS({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var MS=g("ZodIntersection",(t,e)=>{Ud.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xp(t,r,n,o)});function Po(t,e){return new MS({type:"intersection",left:t,right:e})}var Tf=g("ZodRecord",(t,e)=>{qd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qp(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function G(t,e,r){return!e||!e._zod?new Tf({type:"record",keyType:h(),valueType:t,...U.normalizeParams(e)}):new Tf({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var Vi=g("ZodEnum",(t,e)=>{Zd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Wp(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Vi({...e,checks:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Vi({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Te(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Vi({type:"enum",entries:r,...U.normalizeParams(e)})}var CS=g("ZodLiteral",(t,e)=>{Fd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function P(t,e){return new CS({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var NS=g("ZodTransform",(t,e)=>{Hd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Nf(t){return new NS({type:"transform",transform:t})}var Df=g("ZodOptional",(t,e)=>{wi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ne(t){return new Df({type:"optional",innerType:t})}var DS=g("ZodExactOptional",(t,e)=>{Wd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qi(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function jS(t){return new DS({type:"optional",innerType:t})}var LS=g("ZodNullable",(t,e)=>{Vd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function zf(t){return new LS({type:"nullable",innerType:t})}var US=g("ZodDefault",(t,e)=>{Kd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function qS(t,e){return new US({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var ZS=g("ZodPrefault",(t,e)=>{Gd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function FS(t,e){return new ZS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var jf=g("ZodNonOptional",(t,e)=>{Jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tf(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function HS(t,e){return new jf({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var WS=g("ZodCatch",(t,e)=>{Yd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>of(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function VS(t,e){return new WS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Lf=g("ZodPipe",(t,e)=>{ki.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sf(t,r,n,o),t.in=e.in,t.out=e.out});function Rf(t,e){return new Lf({type:"pipe",in:t,out:e})}var KS=g("ZodPreprocess",(t,e)=>{Lf.init(t,e),Bd.init(t,e)}),GS=g("ZodReadonly",(t,e)=>{Xd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>af(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function JS(t){return new GS({type:"readonly",innerType:t})}var Uf=g("ZodCustom",(t,e)=>{Qd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o)});function qf(t,e){return Cp(Uf,t??(()=>!0),e)}function YS(t,e={}){return Np(Uf,t,e)}function BS(t,e){return Dp(t,e)}function Gi(t,e){return new KS({type:"pipe",in:Nf(t),out:e})}Oe(ep());var Yi="2025-11-25";var Zf=[Yi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],It="io.modelcontextprotocol/related-task",zo="2.0",le=qf(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ff=B([h(),W().int()]),Hf=h(),wR=xe({ttl:W().optional(),pollInterval:W().optional()}),XS=k({ttl:W().optional()}),QS=k({taskId:h()}),Bi=xe({progressToken:Ff.optional(),[It]:QS.optional()}),Ce=k({_meta:Bi.optional()}),rn=Ce.extend({task:XS.optional()}),Wf=t=>rn.safeParse(t).success,me=k({method:h(),params:Ce.loose().optional()}),Le=k({_meta:Bi.optional()}),Ue=k({method:h(),params:Le.loose().optional()}),he=xe({_meta:Bi.optional()}),Ro=B([h(),W().int()]),Vf=k({jsonrpc:P(zo),id:Ro,...me.shape}).strict(),Xi=t=>Vf.safeParse(t).success,Kf=k({jsonrpc:P(zo),...Ue.shape}).strict(),Gf=t=>Kf.safeParse(t).success,Qi=k({jsonrpc:P(zo),id:Ro,result:he}).strict(),nn=t=>Qi.safeParse(t).success;var N;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));var ea=k({jsonrpc:P(zo),id:Ro.optional(),error:k({code:W().int(),message:h(),data:re().optional()})}).strict();var Jf=t=>ea.safeParse(t).success;var Yf=B([Vf,Kf,Qi,ea]),kR=B([Qi,ea]),Io=he.strict(),ev=Le.extend({requestId:Ro.optional(),reason:h().optional()}),Ao=Ue.extend({method:P("notifications/cancelled"),params:ev}),tv=k({src:h(),mimeType:h().optional(),sizes:D(h()).optional(),theme:Te(["light","dark"]).optional()}),on=k({icons:D(tv).optional()}),dr=k({name:h(),title:h().optional()}),Bf=dr.extend({...dr.shape,...on.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),rv=Po(k({applyDefaults:de().optional()}),G(h(),re())),nv=Gi(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Po(k({form:rv.optional(),url:le.optional()}),G(h(),re()).optional())),ov=xe({list:le.optional(),cancel:le.optional(),requests:xe({sampling:xe({createMessage:le.optional()}).optional(),elicitation:xe({create:le.optional()}).optional()}).optional()}),sv=xe({list:le.optional(),cancel:le.optional(),requests:xe({tools:xe({call:le.optional()}).optional()}).optional()}),iv=k({experimental:G(h(),le).optional(),sampling:k({context:le.optional(),tools:le.optional()}).optional(),elicitation:nv.optional(),roots:k({listChanged:de().optional()}).optional(),tasks:ov.optional(),extensions:G(h(),le).optional()}),av=Ce.extend({protocolVersion:h(),capabilities:iv,clientInfo:Bf}),ta=me.extend({method:P("initialize"),params:av});var cv=k({experimental:G(h(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:k({listChanged:de().optional()}).optional(),resources:k({subscribe:de().optional(),listChanged:de().optional()}).optional(),tools:k({listChanged:de().optional()}).optional(),tasks:sv.optional(),extensions:G(h(),le).optional()}),uv=he.extend({protocolVersion:h(),capabilities:cv,serverInfo:Bf,instructions:h().optional()}),ra=Ue.extend({method:P("notifications/initialized"),params:Le.optional()});var Oo=me.extend({method:P("ping"),params:Ce.optional()}),lv=k({progress:W(),total:ne(W()),message:ne(h())}),dv=k({...Le.shape,...lv.shape,progressToken:Ff}),Mo=Ue.extend({method:P("notifications/progress"),params:dv}),pv=Ce.extend({cursor:Hf.optional()}),sn=me.extend({params:pv.optional()}),an=he.extend({nextCursor:Hf.optional()}),fv=Te(["working","input_required","completed","failed","cancelled"]),cn=k({taskId:h(),status:fv,ttl:B([W(),Of()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ne(W()),statusMessage:ne(h())}),pr=he.extend({task:cn}),mv=Le.merge(cn),un=Ue.extend({method:P("notifications/tasks/status"),params:mv}),Co=me.extend({method:P("tasks/get"),params:Ce.extend({taskId:h()})}),No=he.merge(cn),Do=me.extend({method:P("tasks/result"),params:Ce.extend({taskId:h()})}),xR=he.loose(),jo=sn.extend({method:P("tasks/list")}),Lo=an.extend({tasks:D(cn)}),Uo=me.extend({method:P("tasks/cancel"),params:Ce.extend({taskId:h()})}),Xf=he.merge(cn),Qf=k({uri:h(),mimeType:ne(h()),_meta:G(h(),re()).optional()}),em=Qf.extend({text:h()}),na=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),tm=Qf.extend({blob:na}),ln=Te(["user","assistant"]),fr=k({audience:D(ln).optional(),priority:W().min(0).max(1).optional(),lastModified:en.datetime({offset:!0}).optional()}),rm=k({...dr.shape,...on.shape,uri:h(),description:ne(h()),mimeType:ne(h()),size:ne(W()),annotations:fr.optional(),_meta:ne(xe({}))}),hv=k({...dr.shape,...on.shape,uriTemplate:h(),description:ne(h()),mimeType:ne(h()),annotations:fr.optional(),_meta:ne(xe({}))}),gv=sn.extend({method:P("resources/list")}),_v=an.extend({resources:D(rm)}),yv=sn.extend({method:P("resources/templates/list")}),Sv=an.extend({resourceTemplates:D(hv)}),oa=Ce.extend({uri:h()}),vv=oa,bv=me.extend({method:P("resources/read"),params:vv}),Ev=he.extend({contents:D(B([em,tm]))}),wv=Ue.extend({method:P("notifications/resources/list_changed"),params:Le.optional()}),kv=oa,xv=me.extend({method:P("resources/subscribe"),params:kv}),$v=oa,Pv=me.extend({method:P("resources/unsubscribe"),params:$v}),Tv=Le.extend({uri:h()}),zv=Ue.extend({method:P("notifications/resources/updated"),params:Tv}),Rv=k({name:h(),description:ne(h()),required:ne(de())}),Iv=k({...dr.shape,...on.shape,description:ne(h()),arguments:ne(D(Rv)),_meta:ne(xe({}))}),Av=sn.extend({method:P("prompts/list")}),Ov=an.extend({prompts:D(Iv)}),Mv=Ce.extend({name:h(),arguments:G(h(),h()).optional()}),Cv=me.extend({method:P("prompts/get"),params:Mv}),sa=k({type:P("text"),text:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),ia=k({type:P("image"),data:na,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),aa=k({type:P("audio"),data:na,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),Nv=k({type:P("tool_use"),name:h(),id:h(),input:G(h(),re()),_meta:G(h(),re()).optional()}),Dv=k({type:P("resource"),resource:B([em,tm]),annotations:fr.optional(),_meta:G(h(),re()).optional()}),jv=rm.extend({type:P("resource_link")}),ca=B([sa,ia,aa,jv,Dv]),Lv=k({role:ln,content:ca}),Uv=he.extend({description:h().optional(),messages:D(Lv)}),qv=Ue.extend({method:P("notifications/prompts/list_changed"),params:Le.optional()}),Zv=k({title:h().optional(),readOnlyHint:de().optional(),destructiveHint:de().optional(),idempotentHint:de().optional(),openWorldHint:de().optional()}),Fv=k({taskSupport:Te(["required","optional","forbidden"]).optional()}),nm=k({...dr.shape,...on.shape,description:h().optional(),inputSchema:k({type:P("object"),properties:G(h(),le).optional(),required:D(h()).optional()}).catchall(re()),outputSchema:k({type:P("object"),properties:G(h(),le).optional(),required:D(h()).optional()}).catchall(re()).optional(),annotations:Zv.optional(),execution:Fv.optional(),_meta:G(h(),re()).optional()}),ua=sn.extend({method:P("tools/list")}),Hv=an.extend({tools:D(nm)}),qo=he.extend({content:D(ca).default([]),structuredContent:G(h(),re()).optional(),isError:de().optional()}),$R=qo.or(he.extend({toolResult:re()})),Wv=rn.extend({name:h(),arguments:G(h(),re()).optional()}),dn=me.extend({method:P("tools/call"),params:Wv}),Vv=Ue.extend({method:P("notifications/tools/list_changed"),params:Le.optional()}),PR=k({autoRefresh:de().default(!0),debounceMs:W().int().nonnegative().default(300)}),pn=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),Kv=Ce.extend({level:pn}),la=me.extend({method:P("logging/setLevel"),params:Kv}),Gv=Le.extend({level:pn,logger:h().optional(),data:re()}),Jv=Ue.extend({method:P("notifications/message"),params:Gv}),Yv=k({name:h().optional()}),Bv=k({hints:D(Yv).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),Xv=k({mode:Te(["auto","required","none"]).optional()}),Qv=k({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:D(ca).default([]),structuredContent:k({}).loose().optional(),isError:de().optional(),_meta:G(h(),re()).optional()}),eb=Ki("type",[sa,ia,aa]),To=Ki("type",[sa,ia,aa,Nv,Qv]),tb=k({role:ln,content:B([To,D(To)]),_meta:G(h(),re()).optional()}),rb=rn.extend({messages:D(tb),modelPreferences:Bv.optional(),systemPrompt:h().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:D(h()).optional(),metadata:le.optional(),tools:D(nm).optional(),toolChoice:Xv.optional()}),nb=me.extend({method:P("sampling/createMessage"),params:rb}),fn=he.extend({model:h(),stopReason:ne(Te(["endTurn","stopSequence","maxTokens"]).or(h())),role:ln,content:eb}),da=he.extend({model:h(),stopReason:ne(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:ln,content:B([To,D(To)])}),ob=k({type:P("boolean"),title:h().optional(),description:h().optional(),default:de().optional()}),sb=k({type:P("string"),title:h().optional(),description:h().optional(),minLength:W().optional(),maxLength:W().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:h().optional()}),ib=k({type:Te(["number","integer"]),title:h().optional(),description:h().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),ab=k({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),default:h().optional()}),cb=k({type:P("string"),title:h().optional(),description:h().optional(),oneOf:D(k({const:h(),title:h()})),default:h().optional()}),ub=k({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),enumNames:D(h()).optional(),default:h().optional()}),lb=B([ab,cb]),db=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({type:P("string"),enum:D(h())}),default:D(h()).optional()}),pb=k({type:P("array"),title:h().optional(),description:h().optional(),minItems:W().optional(),maxItems:W().optional(),items:k({anyOf:D(k({const:h(),title:h()}))}),default:D(h()).optional()}),fb=B([db,pb]),mb=B([ub,lb,fb]),hb=B([mb,ob,sb,ib]),gb=rn.extend({mode:P("form").optional(),message:h(),requestedSchema:k({type:P("object"),properties:G(h(),hb),required:D(h()).optional()})}),_b=rn.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),yb=B([gb,_b]),Sb=me.extend({method:P("elicitation/create"),params:yb}),vb=Le.extend({elicitationId:h()}),bb=Ue.extend({method:P("notifications/elicitation/complete"),params:vb}),mr=he.extend({action:Te(["accept","decline","cancel"]),content:Gi(t=>t===null?void 0:t,G(h(),B([h(),W(),de(),D(h())])).optional())}),Eb=k({type:P("ref/resource"),uri:h()});var wb=k({type:P("ref/prompt"),name:h()}),kb=Ce.extend({ref:B([wb,Eb]),argument:k({name:h(),value:h()}),context:k({arguments:G(h(),h()).optional()}).optional()}),xb=me.extend({method:P("completion/complete"),params:kb});var $b=he.extend({completion:xe({values:D(h()).max(100),total:ne(W().int()),hasMore:ne(de())})}),Pb=k({uri:h().startsWith("file://"),name:h().optional(),_meta:G(h(),re()).optional()}),Tb=me.extend({method:P("roots/list"),params:Ce.optional()}),pa=he.extend({roots:D(Pb)}),zb=Ue.extend({method:P("notifications/roots/list_changed"),params:Le.optional()}),TR=B([Oo,ta,xb,la,Cv,Av,gv,yv,bv,xv,Pv,dn,ua,Co,Do,jo,Uo]),zR=B([Ao,Mo,ra,zb,un]),RR=B([Io,fn,da,mr,pa,No,Lo,pr]),IR=B([Oo,nb,Sb,Tb,Co,Do,jo,Uo]),AR=B([Ao,Mo,Jv,zv,wv,Vv,qv,un,bb]),OR=B([Io,uv,$b,Uv,Ov,_v,Sv,Ev,qo,Hv,No,Lo,pr]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ji(o.elicitations,r)}return new t(e,r,n)}},Ji=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function At(t){return t==="completed"||t==="failed"||t==="cancelled"}var pI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function fa(t){let r=xo(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cf(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ma(t,e){let r=Rt(t,e);if(!r.success)throw r.error;return r.data}var Cb=6e4,Zo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ao,r=>{this._oncancel(r)}),this.setNotificationHandler(Mo,r=>{this._onprogress(r)}),this.setRequestHandler(Oo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Co,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Do,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new I(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(N.InvalidParams,`Task not found: ${s}`);if(!At(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(At(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[It]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(jo,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Uo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(At(o.status))throw new I(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),nn(s)||Jf(s)?this._onresponse(s):Xi(s)?this._onrequest(s,i):Gf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[It]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Wf(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new I(N.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),nn(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(nn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),nn(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,pr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},At(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=E=>{l(E)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(E){d(E);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[It]:c}});let m=E=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(E)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let v=E instanceof I?E:new I(N.RequestTimeout,String(E));l(v)};this._responseHandlers.set(p,E=>{if(!n?.signal?.aborted){if(E instanceof Error)return l(E);try{let v=Rt(r,E.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let _=n?.timeout??Cb,S=()=>m(I.fromError(N.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let E=v=>{let $=this._responseHandlers.get(p);$?$(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,E),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(E=>{this._cleanupTimeout(p),l(E)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},No,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Lo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Xf,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[It]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[It]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[It]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=fa(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ma(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=fa(e);this._notificationHandlers.set(n,o=>{let s=ma(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Xi(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=un.parse({method:"notifications/tasks/status",params:a});await this.notification(c),At(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(At(a.status))throw new I(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=un.parse({method:"notifications/tasks/status",params:c});await this.notification(u),At(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function om(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function sm(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];om(i)&&om(s)?r[o]={...i,...s}:r[o]=s}return r}var Wg=xt(Qc(),1),Vg=xt(Hg(),1);function $$(){let t=new Wg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Vg.default)(t),t}var ks=class{constructor(e){this._ajv=e??$$()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var xs=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},fn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},mr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Kg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Gg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var $s=class extends Zo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(pn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(ra,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(la,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=pn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xs(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=sm(this._capabilities,e)}setRequestHandler(e,r){let o=xo(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(lr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Rt(dn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(N.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Rt(pr,p);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new I(N.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}let f=Rt(qo,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(N.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Gg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Kg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Zf.includes(r)?r:Yi,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"},Io)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},da,r):this.request({method:"sampling/createMessage",params:e},fn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},mr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},mr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},pa,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var au=xt(require("node:process"),1);var Ps=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` -`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),P$(r)}clear(){this._buffer=void 0}};function P$(t){return Yf.parse(JSON.parse(t))}function Jg(t){return JSON.stringify(t)+` -`}var Ts=class{constructor(e=au.default.stdin,r=au.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ps,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Jg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var qs=xt(require("path"),1),Mr=require("fs");var Yg=require("node:child_process");function zs(t,e,r){return(0,Yg.spawn)(t,e??[],{windowsHide:!0,...r})}var ue={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function bt(t){return process.platform==="win32"?Math.round(t*ue.WINDOWS_MULTIPLIER):t}var ut=require("fs"),Hn=require("path"),cu=require("os");var Et=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(bt(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Hn.join)((0,cu.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Hn.join)((0,cu.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,ut.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,Hn.dirname)(e);(0,ut.existsSync)(c)||(0,ut.mkdirSync)(c,{recursive:!0}),(0,ut.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,ut.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{(0,ut.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var Rs=null;function Is(){return Rs!==null||(Rs=Et.loadFromFile(qu)),Rs}var tr=require("fs");var fu=require("child_process");var lt=require("fs"),du=xt(require("path"),1);var T$=["CLAUDECODE_","CLAUDE_CODE_"],z$=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),R$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Wn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(R$.has(r)){e[r]=n;continue}z$.has(r)||T$.some(o=>r.startsWith(o))||(e[r]=n)}return e}var I$=5e3,A$=1e3,O$=De.supervisorRegistry();function wt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function As(t,e){let r=Date.now()+e;for(;Date.now()!wt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var M$=5e3,Bg=new Map;function C$(t){let e=Bg.get(t);if(e&&Date.now()-e.capturedAtMs0?o:null}}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return Bg.set(t,{token:r,capturedAtMs:Date.now()}),r}function Xg(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,lt.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let o=e.slice(r+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return C$(t);try{let e=(0,fu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Wn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function mu(t){if(!t||!wt(t.pid))return!1;if(!t.startToken)return!0;let e=Xg(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var pu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=O$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,lt.mkdirSync)(du.default.dirname(this.registryPath),{recursive:!0}),!(0,lt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,lt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&lu()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)wt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;ni.pid)});let o=r.filter(i=>wt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await As(o,I$);let s=o.filter(i=>wt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+A$;for(;Date.now()wt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&lu();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,lt.mkdirSync)(du.default.dirname(this.registryPath),{recursive:!0}),(0,lt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},uu=null;function Os(){return uu||(uu=new pu),uu}var N$=[];function lu(){let t=N$.shift();t&&t()}var e_=require("child_process"),Ar=require("fs"),t_=require("util");var D$=(0,t_.promisify)(e_.execFile),j$=De.workerPid();async function r_(t){let e=t.currentPid??process.pid,r=t.pidFilePath??j$,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!wt(i.pid)){t.registry.unregister(i.id);continue}try{await Qg(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await As(o,5e3);let s=o.filter(i=>wt(i.pid));for(let i of s)try{await Qg(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await As(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);L$(r,e),t.registry.pruneDeadEntries()}function L$(t,e){if(!(0,Ar.existsSync)(t))return;let r=null;try{let n=JSON.parse((0,Ar.readFileSync)(t,"utf-8"));r=typeof n.pid=="number"?n.pid:null}catch(n){y.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:n instanceof Error?n.message:String(n)});return}if(r!==e){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ar.rmSync)(t,{force:!0})}catch(n){n instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},n):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(n)})}}async function Qg(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=await U$();if(o){await new Promise((i,a)=>{o(r,e,c=>{if(!c){i();return}if(c.code==="ESRCH"){i();return}a(c)})});return}let s=["/PID",String(r),"/T"];e==="SIGKILL"&&s.push("/F"),await D$("taskkill",s,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}async function U$(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return y.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var n_=3e4,Or=null;function q$(){let e=Os().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function o_(){Or===null&&(Or=setInterval(q$,n_),Or.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:n_}))}function s_(){Or!==null&&(clearInterval(Or),Or=null,y.debug("SYSTEM","Health checker stopped"))}var Z$=De.workerPid(),hu=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ms({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,o_()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}s_(),this.stopPromise=r_({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},F$=new hu(Os());function gu(){return F$}function Ms(t={}){let e=t.pidFilePath??Z$;if(!(0,tr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,tr.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,tr.rmSync)(e,{force:!0}),"invalid"}return mu(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,tr.rmSync)(e,{force:!0}),"stale")}var rr=xt(require("path"),1),u_=require("os"),Ne=require("fs"),Cs=require("child_process");function i_(t){return t instanceof Error?t:new Error(String(t))}var qN=De.dataDir(),a_=De.workerPid();function c_(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function H$(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Cs.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var _u;function l_(t={}){let e=Object.keys(t).length===0;if(e&&_u!==void 0)return _u;let r=W$(t);return e&&r!==null&&(_u=r),r}function W$(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(c_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,u_.homedir)(),s=t.pathExists??Ne.existsSync,i=t.lookupInPath??H$,a=e==="win32"?[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun.exe"),rr.default.join(o,".bun","bin","bun"),n.USERPROFILE?rr.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(c_(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function qt(t){return process.platform==="win32"?Math.round(t*2):t}function d_(t,e,r={}){gu().assertCanSpawn("worker daemon");let n=Wn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=l_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=`Start-Process -FilePath '${o.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Cs.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},i_(p));return}}let s="/usr/bin/setsid",i=(0,Ne.existsSync)(s),u=zs(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function p_(){try{if(!(0,Ne.existsSync)(a_))return;let t=new Date;(0,Ne.utimesSync)(a_,t,t)}catch{}}function f_(){return Ms({logAlive:!1})}var m_=xt(require("net"),1);async function V$(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function h_(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=m_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function g_(t,e,r,n){let o=Date.now();for(;Date.now()-osetTimeout(s,500))}return!1}function Vn(t,e=3e4){return g_(t,"/api/health",e,"Service not ready yet, will retry")}function Kn(t,e=3e4){return g_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Ns=require("path"),We=require("fs");var K$=6e4;function __(){return(0,Ns.join)(oo(),"spawn.lock")}function yu(){let t=__(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,We.mkdirSync)((0,Ns.dirname)(t),{recursive:!0}),(0,We.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){if(n?.code!=="EEXIST")return!0;if(r>0)return!1;let s;try{s=(0,We.statSync)(t).mtimeMs}catch{continue}if(Date.now()-s<=K$)return!1;let i;try{i=(0,We.statSync)(t).mtimeMs}catch{continue}if(i!==s)return!1;try{(0,We.unlinkSync)(t)}catch{return!1}}return!1}function Su(){let t=__();try{if(JSON.parse((0,We.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,We.unlinkSync)(t)}catch{}}function vu(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var _D=vu("CLAUDE_MEM_HEALTH_TIMEOUT_MS",bt(ue.HEALTH_CHECK),{min:500,max:3e5}),yD=vu("CLAUDE_MEM_API_TIMEOUT_MS",bt(ue.API_REQUEST),{min:500,max:3e5}),SD=vu("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",bt(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),G$={min:500,max:3e5};async function bu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ds=null,js=null,Ls=null,Us=null;function J$(){return qs.default.join(Et.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Eu(){return Ls!==null||(Ls=Et.loadFromFile(J$())),Ls}function y_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Y$(t,e,r){let n=process.env[t];if(n!==void 0){let i=y_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=Eu()[t],s=y_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function wu(){if(Ds!==null)return Ds;let t=Eu();return Ds=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ds}function B$(){return js!==null||(js=Eu().CLAUDE_MEM_WORKER_HOST),js}function X$(){return Us!==null||(Us=Y$("CLAUDE_MEM_API_TIMEOUT_MS",bt(ue.API_REQUEST),G$)),Us}function Q$(t){return`http://${B$()}:${wu()}${t}`}function Gn(t,e={}){let r=e.method??"GET",n=e.timeoutMs??X$(),o=Q$(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?bu(o,s,n):fetch(o,s)}function S_(){let t=[qs.default.join(Qs,"plugin","scripts","worker-service.cjs"),qs.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Mr.existsSync)(e))return e;return null}var ku=xt(require("path"),1),Ve=require("fs");var eP=120*1e3;function xu(){return ku.default.join(Et.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function tP(){if(process.platform!=="win32")return!1;let t=xu();if(!(0,Ve.existsSync)(t))return!1;try{let e=(0,Ve.statSync)(t).mtimeMs;return Date.now()-etypeof d=="string")){o.grammars[s]={package:c,extensions:u,query:typeof l=="string"?l:void 0};for(let d of u)Iu[d]||(o.extensionToLanguage[d]=s);if(typeof l=="string"){let d=(0,ae.join)(t,l);try{let p=(0,pe.readFileSync)(d,"utf-8"),f=`user_${s}`;T_[f]=p,o.languageToQueryKey[s]=f}catch{y.warn("PARSER","Custom query file not found, falling back to generic",{fullQueryPath:d}),o.languageToQueryKey[s]="generic"}}else o.languageToQueryKey[s]="generic"}}return Jn.set(t,o),o}var $_={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",elixir:"tree-sitter-elixir",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},nP={markdown:"tree-sitter-markdown"};function oP(t){let e=$_[t];if(!e)return null;let r=nP[t];if(r){try{let n=Ru.resolve(e+"/package.json"),o=(0,ae.join)((0,ae.dirname)(n),r);if((0,pe.existsSync)((0,ae.join)(o,"src")))return o}catch{}return null}try{let n=Ru.resolve(e+"/package.json");return(0,ae.dirname)(n)}catch{return null}}function P_(t,e){let r=oP(t);if(r)return r;if(!e)return null;let o=Bn(e).grammars[t];if(!o)return null;try{let s=(0,ae.join)(e,"node_modules",o.package,"package.json");if((0,pe.existsSync)(s)){let i=(0,ae.dirname)(s);if((0,pe.existsSync)((0,ae.join)(i,"src")))return i}}catch{}return y.warn("PARSER","Grammar package not found",{language:t,package:o.package}),null}var T_={jsts:` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Mi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(m.$ref&&f.def)for(let S in u)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(u[S])===JSON.stringify(f.def[S])&&delete u[S]}let p=a._zod.parent;if(p&&p!==d){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Gr(e,"input",t.processors),output:Gr(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function be(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return be(n.element,r);if(n.type==="set")return be(n.valueType,r);if(n.type==="lazy")return be(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return be(n.innerType,r);if(n.type==="intersection")return be(n.left,r)||be(n.right,r);if(n.type==="record"||n.type==="map")return be(n.keyType,r)||be(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:be(n.in,r)||be(n.out,r);if(n.type==="object"){for(let o in n.shape)if(be(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(be(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(be(o,r))return!0;return!!(n.rest&&be(n.rest,r))}return!1}var Rp=(t,e={})=>r=>{let n=Oi({...r,processors:e});return se(t,n),Ai(n,t),Mi(n,t)},Gr=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Oi({...o??{},target:s,io:e,processors:r});return se(t,i),Ai(i,t),Mi(i,t)};var My={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ip=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=My[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Op=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Ap=(t,e,r,n)=>{r.type="boolean"};var Mp=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Cp=(t,e,r,n)=>{r.not={}};var Np=(t,e,r,n)=>{};var Dp=(t,e,r,n)=>{let o=t._zod.def,s=Lr(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},jp=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var Lp=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Up=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var qp=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=se(s.element,e,{...n,path:[...n.path,"items"]})},Zp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=se(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=se(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Fp=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>se(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},Hp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=se(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var Wp=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=se(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=se(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=se(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},Vp=(t,e,r,n)=>{let o=t._zod.def,s=se(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Kp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},Jp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Gp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Yp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Bp=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;se(i,e,n);let a=e.seen.get(t);a.ref=i},Xp=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var Ci=(t,e,r,n)=>{let o=t._zod.def;se(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function lr(t){return!!t._zod}function Rt(t,e){return lr(t)?Hr(t,e):t.safeParse(e)}function _o(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Qp(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Br={};Ou(Br,{ZodISODate:()=>tf,ZodISODateTime:()=>ef,ZodISODuration:()=>nf,ZodISOTime:()=>rf,date:()=>Di,datetime:()=>Ni,duration:()=>Li,time:()=>ji});var ef=_("ZodISODateTime",(t,e)=>{ud.init(t,e),te.init(t,e)});function Ni(t){return gp(ef,t)}var tf=_("ZodISODate",(t,e)=>{ld.init(t,e),te.init(t,e)});function Di(t){return _p(tf,t)}var rf=_("ZodISOTime",(t,e)=>{dd.init(t,e),te.init(t,e)});function ji(t){return yp(rf,t)}var nf=_("ZodISODuration",(t,e)=>{pd.init(t,e),te.init(t,e)});function Li(t){return Sp(nf,t)}var Fy=(t,e)=>{ro.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Vu(t,r)},flatten:{value:r=>Wu(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ir,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ir,2)}},isEmpty:{get(){return t.issues.length===0}}})};var Ie=_("ZodError",Fy,{Parent:Error});var of=no(Ie),sf=oo(Ie),af=Fr(Ie),cf=Wr(Ie),uf=Ku(Ie),lf=Ju(Ie),df=Gu(Ie),pf=Yu(Ie),ff=Bu(Ie),mf=Xu(Ie),hf=Qu(Ie),gf=el(Ie);var _f=new WeakMap;function Xr(t,e,r){let n=Object.getPrototypeOf(t),o=_f.get(n);if(o||(o=new Set,_f.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=_("ZodType",(t,e)=>(Y.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Gr(t,"input"),output:Gr(t,"output")}}),t.toJSONSchema=Rp(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>of(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>af(t,r,n),t.parseAsync=async(r,n)=>sf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>cf(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>uf(t,r,n),t.decode=(r,n)=>lf(t,r,n),t.encodeAsync=async(r,n)=>df(t,r,n),t.decodeAsync=async(r,n)=>pf(t,r,n),t.safeEncode=(r,n)=>ff(t,r,n),t.safeDecode=(r,n)=>mf(t,r,n),t.safeEncodeAsync=async(r,n)=>hf(t,r,n),t.safeDecodeAsync=async(r,n)=>gf(t,r,n),Xr(t,"ZodType",{check(...r){let n=this.def;return this.clone(L.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Je(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(AS(r,n))},superRefine(r,n){return this.check(MS(r,n))},overwrite(r){return this.check(zt(r))},optional(){return ne(this)},exactOptional(){return bS(this)},nullable(){return bf(this)},nullish(){return ne(bf(this))},nonoptional(r){return PS(this,r)},array(){return D(this)},or(r){return X([this,r])},and(r){return So(this,r)},transform(r){return Ef(this,Tf(r))},default(r){return kS(this,r)},prefault(r){return $S(this,r)},catch(r){return zS(this,r)},pipe(r){return Ef(this,r)},readonly(){return OS(this)},describe(r){let n=this.clone();return Ht.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ht.get(this);let n=this.clone();return Ht.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Ht.get(t)?.description},configurable:!0}),t)),wf=_("_ZodString",(t,e)=>{lo.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Ip(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Xr(t,"_ZodString",{regex(...n){return this.check(bi(...n))},includes(...n){return this.check(ki(...n))},startsWith(...n){return this.check(xi(...n))},endsWith(...n){return this.check($i(...n))},min(...n){return this.check(ur(...n))},max(...n){return this.check(ho(...n))},length(...n){return this.check(go(...n))},nonempty(...n){return this.check(ur(1,...n))},lowercase(n){return this.check(Ei(n))},uppercase(n){return this.check(wi(n))},trim(){return this.check(Ti())},normalize(...n){return this.check(Pi(...n))},toLowerCase(){return this.check(zi())},toUpperCase(){return this.check(Ri())},slugify(){return this.check(Ii())}})}),Wy=_("ZodString",(t,e)=>{lo.init(t,e),wf.init(t,e),t.email=r=>t.check(Gd(Vy,r)),t.url=r=>t.check(ep(Ky,r)),t.jwt=r=>t.check(hp(cS,r)),t.emoji=r=>t.check(tp(Jy,r)),t.guid=r=>t.check(vi(yf,r)),t.uuid=r=>t.check(Yd(yo,r)),t.uuidv4=r=>t.check(Bd(yo,r)),t.uuidv6=r=>t.check(Xd(yo,r)),t.uuidv7=r=>t.check(Qd(yo,r)),t.nanoid=r=>t.check(rp(Gy,r)),t.guid=r=>t.check(vi(yf,r)),t.cuid=r=>t.check(np(Yy,r)),t.cuid2=r=>t.check(op(By,r)),t.ulid=r=>t.check(sp(Xy,r)),t.base64=r=>t.check(pp(sS,r)),t.base64url=r=>t.check(fp(iS,r)),t.xid=r=>t.check(ip(Qy,r)),t.ksuid=r=>t.check(ap(eS,r)),t.ipv4=r=>t.check(cp(tS,r)),t.ipv6=r=>t.check(up(rS,r)),t.cidrv4=r=>t.check(lp(nS,r)),t.cidrv6=r=>t.check(dp(oS,r)),t.e164=r=>t.check(mp(aS,r)),t.datetime=r=>t.check(Ni(r)),t.date=r=>t.check(Di(r)),t.time=r=>t.check(ji(r)),t.duration=r=>t.check(Li(r))});function h(t){return Jd(Wy,t)}var te=_("ZodStringFormat",(t,e)=>{B.init(t,e),wf.init(t,e)}),Vy=_("ZodEmail",(t,e)=>{ed.init(t,e),te.init(t,e)});var yf=_("ZodGUID",(t,e)=>{Xl.init(t,e),te.init(t,e)});var yo=_("ZodUUID",(t,e)=>{Ql.init(t,e),te.init(t,e)});var Ky=_("ZodURL",(t,e)=>{td.init(t,e),te.init(t,e)});var Jy=_("ZodEmoji",(t,e)=>{rd.init(t,e),te.init(t,e)});var Gy=_("ZodNanoID",(t,e)=>{nd.init(t,e),te.init(t,e)});var Yy=_("ZodCUID",(t,e)=>{od.init(t,e),te.init(t,e)});var By=_("ZodCUID2",(t,e)=>{sd.init(t,e),te.init(t,e)});var Xy=_("ZodULID",(t,e)=>{id.init(t,e),te.init(t,e)});var Qy=_("ZodXID",(t,e)=>{ad.init(t,e),te.init(t,e)});var eS=_("ZodKSUID",(t,e)=>{cd.init(t,e),te.init(t,e)});var tS=_("ZodIPv4",(t,e)=>{fd.init(t,e),te.init(t,e)});var rS=_("ZodIPv6",(t,e)=>{md.init(t,e),te.init(t,e)});var nS=_("ZodCIDRv4",(t,e)=>{hd.init(t,e),te.init(t,e)});var oS=_("ZodCIDRv6",(t,e)=>{gd.init(t,e),te.init(t,e)});var sS=_("ZodBase64",(t,e)=>{yd.init(t,e),te.init(t,e)});var iS=_("ZodBase64URL",(t,e)=>{Sd.init(t,e),te.init(t,e)});var aS=_("ZodE164",(t,e)=>{vd.init(t,e),te.init(t,e)});var cS=_("ZodJWT",(t,e)=>{bd.init(t,e),te.init(t,e)});var kf=_("ZodNumber",(t,e)=>{hi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Op(t,n,o,s),Xr(t,"ZodNumber",{gt(n,o){return this.check(fo(n,o))},gte(n,o){return this.check(Jr(n,o))},min(n,o){return this.check(Jr(n,o))},lt(n,o){return this.check(po(n,o))},lte(n,o){return this.check(Kr(n,o))},max(n,o){return this.check(Kr(n,o))},int(n){return this.check(Sf(n))},safe(n){return this.check(Sf(n))},positive(n){return this.check(fo(0,n))},nonnegative(n){return this.check(Jr(0,n))},negative(n){return this.check(po(0,n))},nonpositive(n){return this.check(Kr(0,n))},multipleOf(n,o){return this.check(mo(n,o))},step(n,o){return this.check(mo(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function H(t){return vp(kf,t)}var uS=_("ZodNumberFormat",(t,e)=>{Ed.init(t,e),kf.init(t,e)});function Sf(t){return bp(uS,t)}var lS=_("ZodBoolean",(t,e)=>{wd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ap(t,r,n,o)});function le(t){return Ep(lS,t)}var dS=_("ZodNull",(t,e)=>{kd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mp(t,r,n,o)});function xf(t){return wp(dS,t)}var pS=_("ZodUnknown",(t,e)=>{xd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Np(t,r,n,o)});function re(){return kp(pS)}var fS=_("ZodNever",(t,e)=>{$d.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Cp(t,r,n,o)});function mS(t){return xp(fS,t)}var hS=_("ZodArray",(t,e)=>{Pd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qp(t,r,n,o),t.element=e.element,Xr(t,"ZodArray",{min(r,n){return this.check(ur(r,n))},nonempty(r){return this.check(ur(1,r))},max(r,n){return this.check(ho(r,n))},length(r,n){return this.check(go(r,n))},unwrap(){return this.element}})});function D(t,e){return $p(hS,t,e)}var $f=_("ZodObject",(t,e)=>{Rd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zp(t,r,n,o),L.defineLazy(t,"shape",()=>e.shape),Xr(t,"ZodObject",{keyof(){return xe(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:re()})},loose(){return this.clone({...this._zod.def,catchall:re()})},strict(){return this.clone({...this._zod.def,catchall:mS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return L.extend(this,r)},safeExtend(r){return L.safeExtend(this,r)},merge(r){return L.merge(this,r)},pick(r){return L.pick(this,r)},omit(r){return L.omit(this,r)},partial(...r){return L.partial(zf,this,r[0])},required(...r){return L.required(Rf,this,r[0])}})});function w(t,e){let r={type:"object",shape:t??{},...L.normalizeParams(e)};return new $f(r)}function Ee(t,e){return new $f({type:"object",shape:t,catchall:re(),...L.normalizeParams(e)})}var Pf=_("ZodUnion",(t,e)=>{gi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fp(t,r,n,o),t.options=e.options});function X(t,e){return new Pf({type:"union",options:t,...L.normalizeParams(e)})}var gS=_("ZodDiscriminatedUnion",(t,e)=>{Pf.init(t,e),Id.init(t,e)});function qi(t,e,r){return new gS({type:"union",options:e,discriminator:t,...L.normalizeParams(r)})}var _S=_("ZodIntersection",(t,e)=>{Od.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hp(t,r,n,o)});function So(t,e){return new _S({type:"intersection",left:t,right:e})}var vf=_("ZodRecord",(t,e)=>{Ad.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Wp(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function G(t,e,r){return!e||!e._zod?new vf({type:"record",keyType:h(),valueType:t,...L.normalizeParams(e)}):new vf({type:"record",keyType:t,valueType:e,...L.normalizeParams(r)})}var Ui=_("ZodEnum",(t,e)=>{Md.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Dp(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ui({...e,checks:[],...L.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ui({...e,checks:[],...L.normalizeParams(o),entries:s})}});function xe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Ui({type:"enum",entries:r,...L.normalizeParams(e)})}var yS=_("ZodLiteral",(t,e)=>{Cd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jp(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function P(t,e){return new yS({type:"literal",values:Array.isArray(t)?t:[t],...L.normalizeParams(e)})}var SS=_("ZodTransform",(t,e)=>{Nd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Up(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new or(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(L.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(L.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Tf(t){return new SS({type:"transform",transform:t})}var zf=_("ZodOptional",(t,e)=>{_i.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ci(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ne(t){return new zf({type:"optional",innerType:t})}var vS=_("ZodExactOptional",(t,e)=>{Dd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ci(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function bS(t){return new vS({type:"optional",innerType:t})}var ES=_("ZodNullable",(t,e)=>{jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function bf(t){return new ES({type:"nullable",innerType:t})}var wS=_("ZodDefault",(t,e)=>{Ld.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function kS(t,e){return new wS({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var xS=_("ZodPrefault",(t,e)=>{Ud.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function $S(t,e){return new xS({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():L.shallowClone(e)}})}var Rf=_("ZodNonOptional",(t,e)=>{qd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Kp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function PS(t,e){return new Rf({type:"nonoptional",innerType:t,...L.normalizeParams(e)})}var TS=_("ZodCatch",(t,e)=>{Zd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function zS(t,e){return new TS({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var If=_("ZodPipe",(t,e)=>{yi.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bp(t,r,n,o),t.in=e.in,t.out=e.out});function Ef(t,e){return new If({type:"pipe",in:t,out:e})}var RS=_("ZodPreprocess",(t,e)=>{If.init(t,e),Fd.init(t,e)}),IS=_("ZodReadonly",(t,e)=>{Hd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function OS(t){return new IS({type:"readonly",innerType:t})}var Of=_("ZodCustom",(t,e)=>{Wd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Lp(t,r,n,o)});function Af(t,e){return Pp(Of,t??(()=>!0),e)}function AS(t,e={}){return Tp(Of,t,e)}function MS(t,e){return zp(t,e)}function Zi(t,e){return new RS({type:"pipe",in:Tf(t),out:e})}Re(Vd());var Hi="2025-11-25";var Mf=[Hi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],It="io.modelcontextprotocol/related-task",bo="2.0",ce=Af(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Cf=X([h(),H().int()]),Nf=h(),iR=Ee({ttl:H().optional(),pollInterval:H().optional()}),CS=w({ttl:H().optional()}),NS=w({taskId:h()}),Wi=Ee({progressToken:Cf.optional(),[It]:NS.optional()}),Oe=w({_meta:Wi.optional()}),Qr=Oe.extend({task:CS.optional()}),Df=t=>Qr.safeParse(t).success,pe=w({method:h(),params:Oe.loose().optional()}),De=w({_meta:Wi.optional()}),je=w({method:h(),params:De.loose().optional()}),fe=Ee({_meta:Wi.optional()}),Eo=X([h(),H().int()]),jf=w({jsonrpc:P(bo),id:Eo,...pe.shape}).strict(),Vi=t=>jf.safeParse(t).success,Lf=w({jsonrpc:P(bo),...je.shape}).strict(),Uf=t=>Lf.safeParse(t).success,Ki=w({jsonrpc:P(bo),id:Eo,result:fe}).strict(),en=t=>Ki.safeParse(t).success;var N;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(N||(N={}));var Ji=w({jsonrpc:P(bo),id:Eo.optional(),error:w({code:H().int(),message:h(),data:re().optional()})}).strict();var qf=t=>Ji.safeParse(t).success;var Zf=X([jf,Lf,Ki,Ji]),aR=X([Ki,Ji]),wo=fe.strict(),DS=De.extend({requestId:Eo.optional(),reason:h().optional()}),ko=je.extend({method:P("notifications/cancelled"),params:DS}),jS=w({src:h(),mimeType:h().optional(),sizes:D(h()).optional(),theme:xe(["light","dark"]).optional()}),tn=w({icons:D(jS).optional()}),dr=w({name:h(),title:h().optional()}),Ff=dr.extend({...dr.shape,...tn.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),LS=So(w({applyDefaults:le().optional()}),G(h(),re())),US=Zi(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,So(w({form:LS.optional(),url:ce.optional()}),G(h(),re()).optional())),qS=Ee({list:ce.optional(),cancel:ce.optional(),requests:Ee({sampling:Ee({createMessage:ce.optional()}).optional(),elicitation:Ee({create:ce.optional()}).optional()}).optional()}),ZS=Ee({list:ce.optional(),cancel:ce.optional(),requests:Ee({tools:Ee({call:ce.optional()}).optional()}).optional()}),FS=w({experimental:G(h(),ce).optional(),sampling:w({context:ce.optional(),tools:ce.optional()}).optional(),elicitation:US.optional(),roots:w({listChanged:le().optional()}).optional(),tasks:qS.optional(),extensions:G(h(),ce).optional()}),HS=Oe.extend({protocolVersion:h(),capabilities:FS,clientInfo:Ff}),Gi=pe.extend({method:P("initialize"),params:HS});var WS=w({experimental:G(h(),ce).optional(),logging:ce.optional(),completions:ce.optional(),prompts:w({listChanged:le().optional()}).optional(),resources:w({subscribe:le().optional(),listChanged:le().optional()}).optional(),tools:w({listChanged:le().optional()}).optional(),tasks:ZS.optional(),extensions:G(h(),ce).optional()}),VS=fe.extend({protocolVersion:h(),capabilities:WS,serverInfo:Ff,instructions:h().optional()}),Yi=je.extend({method:P("notifications/initialized"),params:De.optional()});var xo=pe.extend({method:P("ping"),params:Oe.optional()}),KS=w({progress:H(),total:ne(H()),message:ne(h())}),JS=w({...De.shape,...KS.shape,progressToken:Cf}),$o=je.extend({method:P("notifications/progress"),params:JS}),GS=Oe.extend({cursor:Nf.optional()}),rn=pe.extend({params:GS.optional()}),nn=fe.extend({nextCursor:Nf.optional()}),YS=xe(["working","input_required","completed","failed","cancelled"]),on=w({taskId:h(),status:YS,ttl:X([H(),xf()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ne(H()),statusMessage:ne(h())}),pr=fe.extend({task:on}),BS=De.merge(on),sn=je.extend({method:P("notifications/tasks/status"),params:BS}),Po=pe.extend({method:P("tasks/get"),params:Oe.extend({taskId:h()})}),To=fe.merge(on),zo=pe.extend({method:P("tasks/result"),params:Oe.extend({taskId:h()})}),cR=fe.loose(),Ro=rn.extend({method:P("tasks/list")}),Io=nn.extend({tasks:D(on)}),Oo=pe.extend({method:P("tasks/cancel"),params:Oe.extend({taskId:h()})}),Hf=fe.merge(on),Wf=w({uri:h(),mimeType:ne(h()),_meta:G(h(),re()).optional()}),Vf=Wf.extend({text:h()}),Bi=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Kf=Wf.extend({blob:Bi}),an=xe(["user","assistant"]),fr=w({audience:D(an).optional(),priority:H().min(0).max(1).optional(),lastModified:Br.datetime({offset:!0}).optional()}),Jf=w({...dr.shape,...tn.shape,uri:h(),description:ne(h()),mimeType:ne(h()),size:ne(H()),annotations:fr.optional(),_meta:ne(Ee({}))}),XS=w({...dr.shape,...tn.shape,uriTemplate:h(),description:ne(h()),mimeType:ne(h()),annotations:fr.optional(),_meta:ne(Ee({}))}),QS=rn.extend({method:P("resources/list")}),ev=nn.extend({resources:D(Jf)}),tv=rn.extend({method:P("resources/templates/list")}),rv=nn.extend({resourceTemplates:D(XS)}),Xi=Oe.extend({uri:h()}),nv=Xi,ov=pe.extend({method:P("resources/read"),params:nv}),sv=fe.extend({contents:D(X([Vf,Kf]))}),iv=je.extend({method:P("notifications/resources/list_changed"),params:De.optional()}),av=Xi,cv=pe.extend({method:P("resources/subscribe"),params:av}),uv=Xi,lv=pe.extend({method:P("resources/unsubscribe"),params:uv}),dv=De.extend({uri:h()}),pv=je.extend({method:P("notifications/resources/updated"),params:dv}),fv=w({name:h(),description:ne(h()),required:ne(le())}),mv=w({...dr.shape,...tn.shape,description:ne(h()),arguments:ne(D(fv)),_meta:ne(Ee({}))}),hv=rn.extend({method:P("prompts/list")}),gv=nn.extend({prompts:D(mv)}),_v=Oe.extend({name:h(),arguments:G(h(),h()).optional()}),yv=pe.extend({method:P("prompts/get"),params:_v}),Qi=w({type:P("text"),text:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),ea=w({type:P("image"),data:Bi,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),ta=w({type:P("audio"),data:Bi,mimeType:h(),annotations:fr.optional(),_meta:G(h(),re()).optional()}),Sv=w({type:P("tool_use"),name:h(),id:h(),input:G(h(),re()),_meta:G(h(),re()).optional()}),vv=w({type:P("resource"),resource:X([Vf,Kf]),annotations:fr.optional(),_meta:G(h(),re()).optional()}),bv=Jf.extend({type:P("resource_link")}),ra=X([Qi,ea,ta,bv,vv]),Ev=w({role:an,content:ra}),wv=fe.extend({description:h().optional(),messages:D(Ev)}),kv=je.extend({method:P("notifications/prompts/list_changed"),params:De.optional()}),xv=w({title:h().optional(),readOnlyHint:le().optional(),destructiveHint:le().optional(),idempotentHint:le().optional(),openWorldHint:le().optional()}),$v=w({taskSupport:xe(["required","optional","forbidden"]).optional()}),Gf=w({...dr.shape,...tn.shape,description:h().optional(),inputSchema:w({type:P("object"),properties:G(h(),ce).optional(),required:D(h()).optional()}).catchall(re()),outputSchema:w({type:P("object"),properties:G(h(),ce).optional(),required:D(h()).optional()}).catchall(re()).optional(),annotations:xv.optional(),execution:$v.optional(),_meta:G(h(),re()).optional()}),na=rn.extend({method:P("tools/list")}),Pv=nn.extend({tools:D(Gf)}),Ao=fe.extend({content:D(ra).default([]),structuredContent:G(h(),re()).optional(),isError:le().optional()}),uR=Ao.or(fe.extend({toolResult:re()})),Tv=Qr.extend({name:h(),arguments:G(h(),re()).optional()}),cn=pe.extend({method:P("tools/call"),params:Tv}),zv=je.extend({method:P("notifications/tools/list_changed"),params:De.optional()}),lR=w({autoRefresh:le().default(!0),debounceMs:H().int().nonnegative().default(300)}),un=xe(["debug","info","notice","warning","error","critical","alert","emergency"]),Rv=Oe.extend({level:un}),oa=pe.extend({method:P("logging/setLevel"),params:Rv}),Iv=De.extend({level:un,logger:h().optional(),data:re()}),Ov=je.extend({method:P("notifications/message"),params:Iv}),Av=w({name:h().optional()}),Mv=w({hints:D(Av).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Cv=w({mode:xe(["auto","required","none"]).optional()}),Nv=w({type:P("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:D(ra).default([]),structuredContent:w({}).loose().optional(),isError:le().optional(),_meta:G(h(),re()).optional()}),Dv=qi("type",[Qi,ea,ta]),vo=qi("type",[Qi,ea,ta,Sv,Nv]),jv=w({role:an,content:X([vo,D(vo)]),_meta:G(h(),re()).optional()}),Lv=Qr.extend({messages:D(jv),modelPreferences:Mv.optional(),systemPrompt:h().optional(),includeContext:xe(["none","thisServer","allServers"]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:D(h()).optional(),metadata:ce.optional(),tools:D(Gf).optional(),toolChoice:Cv.optional()}),Uv=pe.extend({method:P("sampling/createMessage"),params:Lv}),ln=fe.extend({model:h(),stopReason:ne(xe(["endTurn","stopSequence","maxTokens"]).or(h())),role:an,content:Dv}),sa=fe.extend({model:h(),stopReason:ne(xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:an,content:X([vo,D(vo)])}),qv=w({type:P("boolean"),title:h().optional(),description:h().optional(),default:le().optional()}),Zv=w({type:P("string"),title:h().optional(),description:h().optional(),minLength:H().optional(),maxLength:H().optional(),format:xe(["email","uri","date","date-time"]).optional(),default:h().optional()}),Fv=w({type:xe(["number","integer"]),title:h().optional(),description:h().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),Hv=w({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),default:h().optional()}),Wv=w({type:P("string"),title:h().optional(),description:h().optional(),oneOf:D(w({const:h(),title:h()})),default:h().optional()}),Vv=w({type:P("string"),title:h().optional(),description:h().optional(),enum:D(h()),enumNames:D(h()).optional(),default:h().optional()}),Kv=X([Hv,Wv]),Jv=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:H().optional(),maxItems:H().optional(),items:w({type:P("string"),enum:D(h())}),default:D(h()).optional()}),Gv=w({type:P("array"),title:h().optional(),description:h().optional(),minItems:H().optional(),maxItems:H().optional(),items:w({anyOf:D(w({const:h(),title:h()}))}),default:D(h()).optional()}),Yv=X([Jv,Gv]),Bv=X([Vv,Kv,Yv]),Xv=X([Bv,qv,Zv,Fv]),Qv=Qr.extend({mode:P("form").optional(),message:h(),requestedSchema:w({type:P("object"),properties:G(h(),Xv),required:D(h()).optional()})}),eb=Qr.extend({mode:P("url"),message:h(),elicitationId:h(),url:h().url()}),tb=X([Qv,eb]),rb=pe.extend({method:P("elicitation/create"),params:tb}),nb=De.extend({elicitationId:h()}),ob=je.extend({method:P("notifications/elicitation/complete"),params:nb}),mr=fe.extend({action:xe(["accept","decline","cancel"]),content:Zi(t=>t===null?void 0:t,G(h(),X([h(),H(),le(),D(h())])).optional())}),sb=w({type:P("ref/resource"),uri:h()});var ib=w({type:P("ref/prompt"),name:h()}),ab=Oe.extend({ref:X([ib,sb]),argument:w({name:h(),value:h()}),context:w({arguments:G(h(),h()).optional()}).optional()}),cb=pe.extend({method:P("completion/complete"),params:ab});var ub=fe.extend({completion:Ee({values:D(h()).max(100),total:ne(H().int()),hasMore:ne(le())})}),lb=w({uri:h().startsWith("file://"),name:h().optional(),_meta:G(h(),re()).optional()}),db=pe.extend({method:P("roots/list"),params:Oe.optional()}),ia=fe.extend({roots:D(lb)}),pb=je.extend({method:P("notifications/roots/list_changed"),params:De.optional()}),dR=X([xo,Gi,cb,oa,yv,hv,QS,tv,ov,cv,lv,cn,na,Po,zo,Ro,Oo]),pR=X([ko,$o,Yi,pb,sn]),fR=X([wo,ln,sa,mr,ia,To,Io,pr]),mR=X([xo,Uv,rb,db,Po,zo,Ro,Oo]),hR=X([ko,$o,Ov,pv,iv,zv,kv,sn,ob]),gR=X([wo,VS,ub,wv,gv,ev,rv,sv,Ao,Pv,To,Io,pr]),I=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===N.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Fi(o.elicitations,r)}return new t(e,r,n)}},Fi=class extends I{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(N.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Ot(t){return t==="completed"||t==="failed"||t==="cancelled"}var GR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function aa(t){let r=_o(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ca(t,e){let r=Rt(t,e);if(!r.success)throw r.error;return r.data}var yb=6e4,Mo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ko,r=>{this._oncancel(r)}),this.setNotificationHandler($o,r=>{this._onprogress(r)}),this.setRequestHandler(xo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Po,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(zo,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new I(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(N.InvalidParams,`Task not found: ${s}`);if(!Ot(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ot(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[It]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ro,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Oo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ot(o.status))throw new I(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),en(s)||qf(s)?this._onresponse(s):Vi(s)?this._onrequest(s,i):Uf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[It]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Df(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new I(N.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),en(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(en(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),en(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,pr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Ot(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=x=>{l(x)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(x){d(x);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[It]:c}});let m=x=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let b=x instanceof I?x:new I(N.RequestTimeout,String(x));l(b)};this._responseHandlers.set(p,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let b=Rt(r,x.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??yb,S=()=>m(I.fromError(N.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let x=b=>{let $=this._responseHandlers.get(p);$?$(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,x),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(p),l(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},To,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Io,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Hf,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[It]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[It]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[It]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=aa(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ca(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=aa(e);this._notificationHandlers.set(n,o=>{let s=ca(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Vi(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=sn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ot(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ot(a.status))throw new I(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=sn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ot(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Yf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Yf(i)&&Yf(s)?r[o]={...i,...s}:r[o]=s}return r}var Dg=xt(Kc(),1),jg=xt(Ng(),1);function u$(){let t=new Dg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,jg.default)(t),t}var gs=class{constructor(e){this._ajv=e??u$()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var _s=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},ln,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},mr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Lg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Ug(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ys=class extends Mo{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(un.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(Yi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(oa,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=un.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new _s(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Bf(this._capabilities,e)}setRequestHandler(e,r){let o=_o(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(lr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Rt(cn,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new I(N.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Rt(pr,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new I(N.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=Rt(Ao,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new I(N.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Ug(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Lg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Mf.includes(r)?r:Hi,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"},wo)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},sa,r):this.request({method:"sampling/createMessage",params:e},ln,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},mr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},mr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},ia,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var tu=xt(require("node:process"),1);var Ss=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` +`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),l$(r)}clear(){this._buffer=void 0}};function l$(t){return Zf.parse(JSON.parse(t))}function qg(t){return JSON.stringify(t)+` +`}var vs=class{constructor(e=tu.default.stdin,r=tu.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ss,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=qg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var As=xt(require("path"),1),Mr=require("fs");var Zg=require("node:child_process");function bs(t,e,r){return(0,Zg.spawn)(t,e??[],{windowsHide:!0,...r})}var ue={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function qt(t){return process.platform==="win32"?Math.round(t*ue.WINDOWS_MULTIPLIER):t}var ut=require("fs"),qn=require("path"),ru=require("os");var wt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(qt(ue.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,qn.join)((0,ru.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,qn.join)((0,ru.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,ut.existsSync)(e)){let a=this.getAllDefaults();try{let c=(0,qn.dirname)(e);(0,ut.existsSync)(c)||(0,ut.mkdirSync)(c,{recursive:!0}),(0,ut.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(c){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,c instanceof Error?c.message:String(c))}return r?this.applyEnvOverrides(a):a}let n=(0,ut.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{(0,ut.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))s[a]!==void 0&&(i[a]=s[a]);return r?this.applyEnvOverrides(i):i}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var Es=null;function ws(){return Es!==null||(Es=wt.loadFromFile(Mu)),Es}var tr=require("fs");var au=require("child_process");var dt=require("fs"),su=xt(require("path"),1);var d$=["CLAUDECODE_","CLAUDE_CODE_"],p$=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),f$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Zn(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(f$.has(r)){e[r]=n;continue}p$.has(r)||d$.some(o=>r.startsWith(o))||(e[r]=n)}return e}var m$=5e3,h$=1e3,g$=Ce.supervisorRegistry();function lt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(y.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return y.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function ks(t,e){let r=Date.now()+e;for(;Date.now()!lt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var _$=5e3,Fg=new Map;function y$(t){let e=(0,au.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Zn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function S$(t){let e=Fg.get(t);if(e&&Date.now()-e.capturedAtMs<_$)return e.token;let r=null;try{r=y$(t)}catch(n){y.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return Fg.set(t,{token:r,capturedAtMs:Date.now()}),r}function Hg(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,dt.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let o=e.slice(r+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return S$(t);try{let e=(0,au.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Zn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return y.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function cu(t){if(!t||!lt(t.pid))return!1;if(!t.startToken)return!0;let e=Hg(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||y.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var iu=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=g$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,dt.mkdirSync)(su.default.dirname(this.registryPath),{recursive:!0}),!(0,dt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,dt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):y.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&y.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&ou()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)lt(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;ni.pid)});let o=r.filter(i=>lt(i.pid));for(let i of o)try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGTERM"):process.kill(i.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}await ks(o,m$);let s=o.filter(i=>lt(i.pid));for(let i of s){y.warn("SYSTEM",`Session process PID ${i.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:i.pid,pgid:i.pgid,sessionId:n});try{typeof i.pgid=="number"&&process.platform!=="win32"?process.kill(-i.pgid,"SIGKILL"):process.kill(i.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${i.pid}`,{pid:i.pid,pgid:i.pgid},a):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${i.pid} (non-Error)`,{pid:i.pid,pgid:i.pgid,error:String(a)})}}if(s.length>0){let i=Date.now()+h$;for(;Date.now()lt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let i of r)this.entries.delete(i.id),this.runtimeProcesses.delete(i.id);this.persist();for(let i of r)i.type==="sdk"&&ou();return y.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,dt.mkdirSync)(su.default.dirname(this.registryPath),{recursive:!0}),(0,dt.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},nu=null;function xs(){return nu||(nu=new iu),nu}var v$=[];function ou(){let t=v$.shift();t&&t()}var Vg=require("child_process"),Or=require("fs"),Kg=require("util");var b$=(0,Kg.promisify)(Vg.execFile),E$=Ce.workerPid();async function Jg(t){let e=t.currentPid??process.pid,r=t.pidFilePath??E$,n=t.registry.getAll(),o=[...n].filter(i=>i.pid!==e).sort((i,a)=>Date.parse(a.startedAt)-Date.parse(i.startedAt));for(let i of o){if(!lt(i.pid)){t.registry.unregister(i.id);continue}try{await Wg(i,"SIGTERM")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}}await ks(o,5e3);let s=o.filter(i=>lt(i.pid));for(let i of s)try{await Wg(i,"SIGKILL")}catch(a){a instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},a):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(a)})}await ks(s,1e3);for(let i of o)t.registry.unregister(i.id);for(let i of n.filter(a=>a.pid===e))t.registry.unregister(i.id);Gg(r,e),t.registry.pruneDeadEntries()}function Gg(t,e,r=!1){if(!(0,Or.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Or.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){y.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let o=e!==null&&n===e,s=n===null||!lt(n);if(!o&&!(r&&s)){y.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Or.rmSync)(t,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):y.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}async function Wg(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await b$("taskkill",o,{timeout:ue.POWERSHELL_COMMAND,windowsHide:!0})}var Yg=3e4,Ar=null;function w$(){let e=xs().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Bg(){Ar===null&&(Ar=setInterval(w$,Yg),Ar.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:Yg}))}function Xg(){Ar!==null&&(clearInterval(Ar),Ar=null,y.debug("SYSTEM","Health checker stopped"))}var k$=Ce.workerPid(),uu=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),$s({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Bg()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){y.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,y.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?y.error("SYSTEM","Error during shutdown",{},o):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{y.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Xg(),this.stopPromise=Jg({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},x$=new uu(xs());function lu(){return x$}function $s(t={}){let e=t.pidFilePath??k$;if(!(0,tr.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,tr.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,tr.rmSync)(e,{force:!0}),"invalid"}return cu(r)&&r?((t.logAlive??!0)&&y.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(y.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,tr.rmSync)(e,{force:!0}),"stale")}var rr=xt(require("path"),1),t_=require("os"),Fe=require("fs"),Ps=require("child_process");var xN=Ce.dataDir(),Qg=Ce.workerPid();function e_(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function $$(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Ps.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},s):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var du;function r_(t={}){let e=Object.keys(t).length===0;if(e&&du!==void 0)return du;let r=P$(t);return e&&r!==null&&(du=r),r}function P$(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(e_(r))return r;let n=t.env??process.env,o=t.homeDirectory??(0,t_.homedir)(),s=t.pathExists??Fe.existsSync,i=t.lookupInPath??$$,a=e==="win32"?[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun.exe"),rr.default.join(o,".bun","bin","bun"),n.USERPROFILE?rr.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?rr.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,rr.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let c of a){let u=c?.trim();if(u&&(e_(u)&&s(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function Zt(t){return process.platform==="win32"?Math.round(t*2):t}function n_(t,e,r={}){lu().assertCanSpawn("worker daemon");let n=Zn({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),o=r_();if(!o){y.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let l=`Start-Process -FilePath '${o.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,d=Buffer.from(l,"utf16le").toString("base64");try{return(0,Ps.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){let f=p instanceof Error?p:new Error(String(p));y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},f);return}}let s="/usr/bin/setsid",i=(0,Fe.existsSync)(s),u=bs(i?s:o,i?[o,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function o_(){try{if(!(0,Fe.existsSync)(Qg))return;let t=new Date;(0,Fe.utimesSync)(Qg,t,t)}catch{}}function s_(){return $s({logAlive:!1})}var i_=xt(require("net"),1);async function T$(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function a_(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?y.debug("SYSTEM","Windows health check failed (port not in use)",{},e):y.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=i_.default.createServer();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function c_(t,e,r,n){let o=Date.now();for(;Date.now()-osetTimeout(s,500))}return!1}function Fn(t,e=3e4){return c_(t,"/api/health",e,"Service not ready yet, will retry")}function Hn(t,e=3e4){return c_(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Ts=require("path"),He=require("fs");var z$=6e4;function u_(){return(0,Ts.join)(Bn(),"spawn.lock")}function pu(){let t=u_(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,He.mkdirSync)((0,Ts.dirname)(t),{recursive:!0}),(0,He.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return y.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:s},o),!0;if(r>0)return!1;let i;try{i=(0,He.statSync)(t).mtimeMs}catch{continue}if(Date.now()-i<=z$)return!1;let a;try{a=(0,He.statSync)(t).mtimeMs}catch{continue}if(a!==i)return!1;try{(0,He.unlinkSync)(t)}catch{return!1}}return!1}function fu(){let t=u_();try{if(JSON.parse((0,He.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,He.unlinkSync)(t)}catch{}}function d_(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var rD=d_("CLAUDE_MEM_HEALTH_TIMEOUT_MS",qt(ue.HEALTH_CHECK),{min:500,max:3e5}),nD=d_("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",qt(ue.HOOK_READINESS_WAIT),{min:0,max:3e5}),R$={min:500,max:3e5};async function mu(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var zs=null,Rs=null,Is=null,Os=null;function I$(){return As.default.join(wt.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function hu(){return Is!==null||(Is=wt.loadFromFile(I$())),Is}function l_(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function O$(t,e,r){let n=process.env[t];if(n!==void 0){let i=l_(n,r);return i!==null?i:(y.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let o=hu()[t],s=l_(o,r);return s!==null?s:(y.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:o,min:r.min,max:r.max}),e)}function gu(){if(zs!==null)return zs;let t=hu();return zs=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),zs}function A$(){return Rs!==null||(Rs=hu().CLAUDE_MEM_WORKER_HOST),Rs}function M$(){return Os!==null||(Os=O$("CLAUDE_MEM_API_TIMEOUT_MS",qt(ue.API_REQUEST),R$)),Os}function C$(t){return`http://${A$()}:${gu()}${t}`}function Ms(t,e={}){let r=e.method??"GET",n=e.timeoutMs??M$(),o=C$(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?mu(o,s,n):fetch(o,s)}function p_(){let t=[As.default.join(Ks,"plugin","scripts","worker-service.cjs"),As.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Mr.existsSync)(e))return e;return null}var _u=xt(require("path"),1),We=require("fs");var N$=120*1e3;function yu(){return _u.default.join(wt.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function D$(){if(process.platform!=="win32")return!1;let t=yu();if(!(0,We.existsSync)(t))return!1;try{let e=(0,We.statSync)(t).mtimeMs;return Date.now()-e0&&!o.startsWith(" ")&&!o.startsWith(" ")){r=o.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let s=o.match(/^\s+pattern:\s+(\d+)/);if(s){n={pattern:parseInt(s[1]),captures:[]},e.get(r).push(n);continue}let i=o.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var b_={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},lP=new Set(["class","struct","impl","trait"]);function dP(t,e,r,n=200){let s=t[e]||"";if(!s.trimEnd().endsWith("{")&&!s.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(` -`),a=i.indexOf("{");a!==-1&&a<500&&(s=i.slice(0,a).replace(/\n/g," ").replace(/\s+/g," ").trim())}return s=s.replace(/\s*[{:]\s*$/,"").trim(),s.length>n&&(s=s.slice(0,n-3)+"..."),s}function pP(t,e){let r=[],n=!1;for(let o=e-1;o>=0;o--){let s=t[o].trim();if(s===""){if(n)break;continue}if(s.startsWith("/**")||s.startsWith("*")||s.startsWith("*/")||s.startsWith("//")||s.startsWith("///")||s.startsWith("//!")||s.startsWith("#")||s.startsWith("@"))r.unshift(t[o]),n=!0;else break}return r.length>0?r.join(` -`).trim():void 0}function fP(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let o=t[n]?.trim();if(o){if(o.startsWith('"""')||o.startsWith("'''"))return o;break}}}function mP(t,e,r,n,o,s){switch(s){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return o[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function I_(t,e,r){let n=[],o=[],s=[],i=[];for(let c of t)for(let u of c.captures)u.tag==="exp"&&s.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&o.push(u.text||e[u.startRow]?.trim()||"");for(let c of t){let u=c.captures.find(v=>b_[v.tag]),l=c.captures.find(v=>v.tag==="name");if(!u)continue;let d=u.startRow,p=u.endRow,f=b_[u.tag],m=l?.text||"anonymous",_;if(r==="markdown"&&f==="section"){let $=(e[d]||"").match(/^(#{1,6})\s/),x=$?$[1].length:1;_=`${"#".repeat(x)} ${m}`}else if(r==="markdown"&&f==="code"){let v=m!=="anonymous"?m:"";_=v?"```"+v:"```"}else r==="markdown"&&f==="metadata"?_="---frontmatter---":r==="markdown"&&f==="reference"?_=e[d]?.trim()||m:_=dP(e,d,p);let S=r==="markdown"?void 0:pP(e,d),b=r==="python"?fP(e,d,p):void 0,E={name:m,kind:f,signature:_,jsdoc:S||b,lineStart:d,lineEnd:p,exported:mP(m,d,p,s,e,r)};lP.has(f)&&(E.children=[],i.push({sym:E,startRow:d,endRow:p})),n.push(E)}if(r==="markdown"){let c=new Map,u=new Set;for(let l of n){if(l.kind!=="code")continue;let d=`${l.lineStart}:${l.lineEnd}`,p=c.get(d);p?l.name!=="anonymous"?(u.add(p),c.set(d,l)):u.add(l):c.set(d,l)}if(u.size>0){let l=n.filter(d=>!u.has(d));n.length=0,n.push(...l)}}let a=new Set;for(let c of i)for(let u of n)u!==c.sym&&u.lineStart>c.startRow&&u.lineEnd<=c.endRow&&(u.kind==="function"&&(u.kind="method"),c.sym.children.push(u),a.add(u));return{symbols:n.filter(c=>!a.has(c)),imports:o}}function Au(t){let e=(0,ae.dirname)(t);for(;;){if((0,pe.existsSync)((0,ae.join)(e,".claude-mem.json")))return e;let r=(0,ae.dirname)(e);if(r===e)return;e=r}}function Hs(t,e,r){let n=r?Bn(r):Cr,o=k_(e,n),s=t.split(` -`),i=P_(o,r);if(!i)return{filePath:e,language:o,symbols:[],imports:[],totalLines:s.length,foldedTokenEstimate:50};let a=x_(o,n),c=z_(a),u=e.slice(e.lastIndexOf("."))||".txt",l=(0,pe.mkdtempSync)((0,ae.join)((0,Fs.tmpdir)(),"smart-src-")),d=(0,ae.join)(l,`source${u}`);(0,pe.writeFileSync)(d,t);try{let p=cP(c,d,i),f=I_(p,s,o),m=Nr({filePath:e,language:o,symbols:f.symbols,imports:f.imports,totalLines:s.length,foldedTokenEstimate:0});return{filePath:e,language:o,symbols:f.symbols,imports:f.imports,totalLines:s.length,foldedTokenEstimate:Math.ceil(m.length/4)}}finally{(0,pe.rmSync)(l,{recursive:!0,force:!0})}}function A_(t,e){let r=new Map,n=e?Bn(e):Cr,o=new Map;for(let s of t){let i=k_(s.relativePath,n);o.has(i)||o.set(i,[]),o.get(i).push(s)}for(let[s,i]of o){let a=P_(s,e);if(!a){for(let p of i){let f=p.content.split(` -`);r.set(p.relativePath,{filePath:p.relativePath,language:s,symbols:[],imports:[],totalLines:f.length,foldedTokenEstimate:50})}continue}let c=x_(s,n),u=z_(c),l=i.map(p=>p.absolutePath),d=R_(u,l,a);for(let p of i){let f=p.content.split(` -`),m=d.get(p.absolutePath)||[],_=I_(m,f,s),S=Nr({filePath:p.relativePath,language:s,symbols:_.symbols,imports:_.imports,totalLines:f.length,foldedTokenEstimate:0});r.set(p.relativePath,{filePath:p.relativePath,language:s,symbols:_.symbols,imports:_.imports,totalLines:f.length,foldedTokenEstimate:Math.ceil(S.length/4)})}}return r}function Nr(t){if(t.language==="markdown")return hP(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(O_(r," "));return e.join(` -`)}function hP(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let o=n.signature.match(/^(#{1,6})\s/),s=o?o[1].length:1,i=" ".repeat(s),a=`L${n.lineStart+1}`,c=`${i}${n.signature}`;e.push(`${c.padEnd(56)}${a}`)}else if(n.kind==="code"){let o=E_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,a=`${s}${n.signature}`;e.push(`${a.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let o=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,s=` ${n.signature}`;e.push(`${s.padEnd(56)}${o}`)}else if(n.kind==="reference"){let o=E_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=`L${n.lineStart+1}`,a=`${s}\u2197 ${n.name}`;e.push(`${a.padEnd(56)}${i}`)}return e.join(` -`)}function E_(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart{let u=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(a){let c=a.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();c&&r.push(`${e} \u{1F4AC} ${c}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(O_(i,e+" "));return r.join(` -`)}function gP(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function M_(t,e,r,n){let o=Hs(t,e,n),s=l=>{for(let d of l){if(d.name===r)return d;if(d.children){let p=s(d.children);if(p)return p}}return null},i=s(o.symbols);if(!i)return null;let a=t.split(` -`);if(o.language==="markdown"&&i.kind==="section"){let l=i.signature.match(/^(#{1,6})\s/),d=l?l[1].length:1,p=i.lineStart,f=a.length-1;for(let _ of o.symbols)if(_.kind==="section"&&_.lineStart>p){let S=_.signature.match(/^(#{1,6})\s/);if((S?S[1].length:1)<=d){for(f=_.lineStart-1;f>p&&a[f].trim()==="";)f--;break}}let m=a.slice(p,f+1).join(` -`);return` -${m}`}let c=i.lineStart;for(let l=i.lineStart-1;l>=0;l--){let d=a[l].trim();if(d===""||d.startsWith("*")||d.startsWith("/**")||d.startsWith("///")||d.startsWith("//")||d.startsWith("#")||d.startsWith("@")||d==="*/")c=l;else break}let u=a.slice(c,i.lineEnd+1).join(` -`);return`// \u{1F4CD} ${e} L${c+1}-${i.lineEnd+1} -${u}`}var C_=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),yP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),SP=512*1024;async function*N_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Dr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||yP.has(s.name))continue;let i=(0,Xn.join)(t,s.name);if(s.isDirectory())yield*N_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(C_.has(a)||n&&n.has(a))&&(yield i)}}}async function vP(t){try{let e=await(0,Dr.stat)(t);if(e.size>SP||e.size===0)return null;let r=await(0,Dr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function D_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=Bn(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)C_.has(v)||c.add(v);let u=[];for await(let E of N_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Xn.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await vP(E);v&&u.push({absolutePath:E,relativePath:(0,Xn.relative)(t,E),content:v})}let l=A_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=bP(v);let x=Ws(E.toLowerCase(),s)>0,Se=[],we=(Zt,nr)=>{for(let ce of Zt){let kt=0,Ge="",Lr=Ws(ce.name.toLowerCase(),s);Lr>0&&(kt+=Lr*3,Ge="name match"),ce.signature.toLowerCase().includes(o)&&(kt+=2,Ge=Ge?`${Ge} + signature`:"signature match"),ce.jsdoc&&ce.jsdoc.toLowerCase().includes(o)&&(kt+=1,Ge=Ge?`${Ge} + jsdoc`:"jsdoc match"),kt>0&&(x=!0,Se.push({filePath:E,symbolName:nr?`${nr}.${ce.name}`:ce.name,kind:ce.kind,signature:ce.signature,jsdoc:ce.jsdoc,lineStart:ce.lineStart,lineEnd:ce.lineEnd,matchReason:Ge})),ce.children&&we(ce.children,ce.name)}};we(v.symbols),x&&(d.push(v),p.push(...Se))}p.sort((E,v)=>{let $=Ws(E.symbolName.toLowerCase(),s);return Ws(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Ws(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function bP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function j_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` +`};function S_(t){switch(t){case"javascript":return"js";case"typescript":case"tsx":return"jsts";case"python":return"python";case"go":return"go";case"rust":return"rust";case"ruby":return"ruby";case"java":return"java";case"kotlin":return"kotlin";case"swift":return"swift";case"php":return"php";case"lua":return"lua";case"scala":return"scala";case"bash":return"bash";case"haskell":return"haskell";case"zig":return"zig";case"css":return"css";case"scss":return"scss";case"toml":return"toml";case"yaml":return"yaml";case"sql":return"sql";case"markdown":return"markdown";default:return"generic"}}var Su=null,vu=new Map;function v_(t){if(vu.has(t))return vu.get(t);Su||(Su=(0,Ve.mkdtempSync)((0,Ae.join)((0,Ns.tmpdir)(),"smart-read-queries-")));let e=(0,Ae.join)(Su,`${t}.scm`);return(0,Ve.writeFileSync)(e,Z$[t]),vu.set(t,e),e}var nr=null,bu=null,Eu={platform:process.platform,fileExists:Ve.existsSync,resolvePackageJson:t=>ku.resolve(t)};function F$(){if(nr)return nr;let t;try{t=Eu.resolvePackageJson("tree-sitter-cli/package.json")}catch{return nr="tree-sitter",nr}let e=Eu.platform==="win32"?["tree-sitter.exe","tree-sitter"]:["tree-sitter"];for(let r of e){let n=(0,Ae.join)((0,Ae.dirname)(t),r);if(Eu.fileExists(n))return nr=n,n}return nr="tree-sitter",nr}function H$(){return bu||(bu=(0,Ve.mkdtempSync)((0,Ae.join)((0,Ns.tmpdir)(),"claude-mem-tree-sitter-cache-"))),bu}function W$(t,e,r){return b_(t,[e],r).get(e)||[]}function b_(t,e,r){if(e.length===0)return new Map;let n=F$(),o=["query","-p",r,t,...e],s;try{s=(0,g_.execFileSync)(n,o,{encoding:"utf-8",timeout:3e4,stdio:["pipe","pipe","pipe"],env:{...process.env,XDG_CACHE_HOME:H$()}})}catch(i){return y.debug("WORKER",`tree-sitter query failed for ${e.length} file(s)`,void 0,i instanceof Error?i:void 0),new Map}return V$(s)}function V$(t){let e=new Map,r=null,n=null;for(let o of t.split(` +`)){if(o.length>0&&!o.startsWith(" ")&&!o.startsWith(" ")){r=o.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let s=o.match(/^\s+pattern:\s+(\d+)/);if(s){n={pattern:parseInt(s[1]),captures:[]},e.get(r).push(n);continue}let i=o.match(/^\s+capture:\s+(?:\d+\s*-\s*)?(\w+),\s*start:\s*\((\d+),\s*(\d+)\),\s*end:\s*\((\d+),\s*(\d+)\)(?:,\s*text:\s*`([^`]*)`)?/);i&&n&&n.captures.push({tag:i[1],startRow:parseInt(i[2]),startCol:parseInt(i[3]),endRow:parseInt(i[4]),endCol:parseInt(i[5]),text:i[6]})}return e}var m_={func:"function",const_func:"function",cls:"class",method:"method",iface:"interface",tdef:"type",enm:"enum",struct_def:"struct",trait_def:"trait",impl_def:"impl",mixin_def:"mixin",heading:"section",code_block:"code",frontmatter:"metadata",ref:"reference"},K$=new Set(["class","struct","impl","trait"]);function J$(t,e,r,n=200){let s=t[e]||"";if(!s.trimEnd().endsWith("{")&&!s.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(` +`),a=i.indexOf("{");a!==-1&&a<500&&(s=i.slice(0,a).replace(/\n/g," ").replace(/\s+/g," ").trim())}return s=s.replace(/\s*[{:]\s*$/,"").trim(),s.length>n&&(s=s.slice(0,n-3)+"..."),s}function G$(t,e){let r=[],n=!1;for(let o=e-1;o>=0;o--){let s=t[o].trim();if(s===""){if(n)break;continue}if(s.startsWith("/**")||s.startsWith("*")||s.startsWith("*/")||s.startsWith("//")||s.startsWith("///")||s.startsWith("//!")||s.startsWith("#")||s.startsWith("@"))r.unshift(t[o]),n=!0;else break}return r.length>0?r.join(` +`).trim():void 0}function Y$(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let o=t[n]?.trim();if(o){if(o.startsWith('"""')||o.startsWith("'''"))return o;break}}}function B$(t,e,r,n,o,s){switch(s){case"javascript":case"typescript":case"tsx":return n.some(i=>e>=i.startRow&&r<=i.endRow);case"python":return!t.startsWith("_");case"go":return t.length>0&&t[0]===t[0].toUpperCase()&&t[0]!==t[0].toLowerCase();case"rust":return o[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function E_(t,e,r){let n=[],o=[],s=[],i=[];for(let c of t)for(let u of c.captures)u.tag==="exp"&&s.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&o.push(u.text||e[u.startRow]?.trim()||"");for(let c of t){let u=c.captures.find(b=>m_[b.tag]),l=c.captures.find(b=>b.tag==="name");if(!u)continue;let d=u.startRow,p=u.endRow,f=m_[u.tag],m=l?.text||"anonymous",g;if(r==="markdown"&&f==="section"){let $=(e[d]||"").match(/^(#{1,6})\s/),k=$?$[1].length:1;g=`${"#".repeat(k)} ${m}`}else if(r==="markdown"&&f==="code"){let b=m!=="anonymous"?m:"";g=b?"```"+b:"```"}else r==="markdown"&&f==="metadata"?g="---frontmatter---":r==="markdown"&&f==="reference"?g=e[d]?.trim()||m:g=J$(e,d,p);let S=r==="markdown"?void 0:G$(e,d),v=r==="python"?Y$(e,d,p):void 0,x={name:m,kind:f,signature:g,jsdoc:S||v,lineStart:d,lineEnd:p,exported:B$(m,d,p,s,e,r)};K$.has(f)&&(x.children=[],i.push({sym:x,startRow:d,endRow:p})),n.push(x)}if(r==="markdown"){let c=new Map,u=new Set;for(let l of n){if(l.kind!=="code")continue;let d=`${l.lineStart}:${l.lineEnd}`,p=c.get(d);p?l.name!=="anonymous"?(u.add(p),c.set(d,l)):u.add(l):c.set(d,l)}if(u.size>0){let l=n.filter(d=>!u.has(d));n.length=0,n.push(...l)}}let a=new Set;for(let c of i)for(let u of n)u!==c.sym&&u.lineStart>c.startRow&&u.lineEnd<=c.endRow&&(u.kind==="function"&&(u.kind="method"),c.sym.children.push(u),a.add(u));return{symbols:n.filter(c=>!a.has(c)),imports:o}}function Ds(t,e){let r=__(e),n=t.split(` +`),o=y_(r);if(!o)return{filePath:e,language:r,symbols:[],imports:[],totalLines:n.length,foldedTokenEstimate:50};let s=v_(S_(r)),i=e.slice(e.lastIndexOf("."))||".txt",a=(0,Ve.mkdtempSync)((0,Ae.join)((0,Ns.tmpdir)(),"smart-src-")),c=(0,Ae.join)(a,`source${i}`);(0,Ve.writeFileSync)(c,t);try{let u=W$(s,c,o),l=E_(u,n,r),d=Cr({filePath:e,language:r,symbols:l.symbols,imports:l.imports,totalLines:n.length,foldedTokenEstimate:0});return{filePath:e,language:r,symbols:l.symbols,imports:l.imports,totalLines:n.length,foldedTokenEstimate:Math.ceil(d.length/4)}}finally{(0,Ve.rmSync)(a,{recursive:!0,force:!0})}}function w_(t){let e=new Map,r=new Map;for(let n of t){let o=__(n.relativePath);r.has(o)||r.set(o,[]),r.get(o).push(n)}for(let[n,o]of r){let s=y_(n);if(!s){for(let u of o){let l=u.content.split(` +`);e.set(u.relativePath,{filePath:u.relativePath,language:n,symbols:[],imports:[],totalLines:l.length,foldedTokenEstimate:50})}continue}let i=v_(S_(n)),a=o.map(u=>u.absolutePath),c=b_(i,a,s);for(let u of o){let l=u.content.split(` +`),d=c.get(u.absolutePath)||[],p=E_(d,l,n),f=Cr({filePath:u.relativePath,language:n,symbols:p.symbols,imports:p.imports,totalLines:l.length,foldedTokenEstimate:0});e.set(u.relativePath,{filePath:u.relativePath,language:n,symbols:p.symbols,imports:p.imports,totalLines:l.length,foldedTokenEstimate:Math.ceil(f.length/4)})}}return e}function Cr(t){if(t.language==="markdown")return X$(t);let e=[];if(e.push(`\u{1F4C1} ${t.filePath} (${t.language}, ${t.totalLines} lines)`),e.push(""),t.imports.length>0){e.push(` \u{1F4E6} Imports: ${t.imports.length} statements`);for(let r of t.imports.slice(0,10))e.push(` ${r}`);t.imports.length>10&&e.push(` ... +${t.imports.length-10} more`),e.push("")}for(let r of t.symbols)e.push(k_(r," "));return e.join(` +`)}function X$(t){let e=[];e.push(`\u{1F4C4} ${t.filePath} (${t.language}, ${t.totalLines} lines)`);for(let n of t.symbols)if(n.kind==="section"){let o=n.signature.match(/^(#{1,6})\s/),s=o?o[1].length:1,i=" ".repeat(s),a=`L${n.lineStart+1}`,c=`${i}${n.signature}`;e.push(`${c.padEnd(56)}${a}`)}else if(n.kind==="code"){let o=h_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,a=`${s}${n.signature}`;e.push(`${a.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let o=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,s=` ${n.signature}`;e.push(`${s.padEnd(56)}${o}`)}else if(n.kind==="reference"){let o=h_(t.symbols,n.lineStart),s=" ".repeat(o+1),i=`L${n.lineStart+1}`,a=`${s}\u2197 ${n.name}`;e.push(`${a.padEnd(56)}${i}`)}return e.join(` +`)}function h_(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart{let u=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(a){let c=a.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();c&&r.push(`${e} \u{1F4AC} ${c}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(k_(i,e+" "));return r.join(` +`)}function Q$(t){return{function:"\u0192",method:"\u0192",class:"\u25C6",interface:"\u25C7",type:"\u25C7",const:"\u25CF",variable:"\u25CB",export:"\u2192",struct:"\u25C6",enum:"\u25A3",trait:"\u25C7",impl:"\u25C8",property:"\u25CB",getter:"\u21E2",setter:"\u21E0",mixin:"\u25C8",section:"\xA7",code:"\u2318",metadata:"\u25CA",reference:"\u2197"}[t]||"\xB7"}function x_(t,e,r){let n=Ds(t,e),o=u=>{for(let l of u){if(l.name===r)return l;if(l.children){let d=o(l.children);if(d)return d}}return null},s=o(n.symbols);if(!s)return null;let i=t.split(` +`);if(n.language==="markdown"&&s.kind==="section"){let u=s.signature.match(/^(#{1,6})\s/),l=u?u[1].length:1,d=s.lineStart,p=i.length-1;for(let m of n.symbols)if(m.kind==="section"&&m.lineStart>d){let g=m.signature.match(/^(#{1,6})\s/);if((g?g[1].length:1)<=l){for(p=m.lineStart-1;p>d&&i[p].trim()==="";)p--;break}}let f=i.slice(d,p+1).join(` +`);return` +${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l===""||l.startsWith("*")||l.startsWith("/**")||l.startsWith("///")||l.startsWith("//")||l.startsWith("#")||l.startsWith("@")||l==="*/")a=u;else break}let c=i.slice(a,s.lineEnd+1).join(` +`);return`// \u{1F4CD} ${e} L${a+1}-${s.lineEnd+1} +${c}`}var tP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),rP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),nP=512*1024;async function*$_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Nr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||rP.has(o.name))continue;let s=(0,Wn.join)(t,o.name);if(o.isDirectory())yield*$_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));tP.has(i)&&(yield s)}}}async function oP(t){try{let e=await(0,Nr.stat)(t);if(e.size>nP||e.size===0)return null;let r=await(0,Nr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function P_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of $_(t,t,20)){if(r.filePattern&&!(0,Wn.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await oP(g);S&&i.push({absolutePath:g,relativePath:(0,Wn.relative)(t,g),content:S})}let a=w_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=sP(S);let x=js(g.toLowerCase(),s)>0,b=[],$=(k,_e)=>{for(let V of k){let tt=0,Me="",kt=js(V.name.toLowerCase(),s);kt>0&&(tt+=kt*3,Me="name match"),V.signature.toLowerCase().includes(o)&&(tt+=2,Me=Me?`${Me} + signature`:"signature match"),V.jsdoc&&V.jsdoc.toLowerCase().includes(o)&&(tt+=1,Me=Me?`${Me} + jsdoc`:"jsdoc match"),tt>0&&(x=!0,b.push({filePath:g,symbolName:_e?`${_e}.${V.name}`:V.name,kind:V.kind,signature:V.signature,jsdoc:V.jsdoc,lineStart:V.lineStart,lineEnd:V.lineEnd,matchReason:Me})),V.children&&$(V.children,V.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=js(g.symbolName.toLowerCase(),s);return js(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function js(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function sP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function T_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(` -`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Nr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` -`)}var Nu=require("node:fs/promises"),Gs=require("node:fs"),tt=require("node:path"),K_=require("node:os"),G_=require("node:url");var L_="claude";function EP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Vs(t){if(!t)return L_;let e=EP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:L_}var wP=bt(ue.API_REQUEST),Ke=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ks=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=kP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??wP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ke("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ke("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ou(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ke("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await bu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ke(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ke("http_error",`Server ${e} ${r} returned ${i.status}: ${xP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Ke("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:c})}}};function U_(t){return t instanceof Ke}function kP(t){return t.replace(/\/+$/,"")}function Ou(t){return typeof t=="string"?Vs(t):null}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Mu(){let e=(Is().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function q_(){let t=Is(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ks(s),projectId:o,serverBaseUrl:r}}var FP={},$P="13.9.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var J_=!1,Y_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,G_.fileURLToPath)(FP.url))}catch{return J_=!0,process.cwd()}})(),Du=S_()??(0,tt.resolve)(Y_,"worker-service.cjs");function PP(){J_&&((0,Gs.existsSync)(Du)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Du,mcpServerDir:Y_}))}var Z_={search:"/api/search",timeline:"/api/timeline"};async function Cu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Gn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function TP(t,e){y.debug("SYSTEM","\u2192 Worker API text",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Gn(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.text();return y.debug("SYSTEM","\u2190 Worker API text success",void 0,{endpoint:t}),{content:[{type:"text",text:s}]}}catch(o){return y.error("SYSTEM","\u2190 Worker API text error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function zP(t,e){let r=await Gn(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function jr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function RP(){try{return(await Gn("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){if(Mu()!=="server")return null;let e=q_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function eo(t){return U_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function to(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=IP();if(!e)throw new Ke("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ke("missing_api_key",`${t}: ${e.reason}`);return e}async function F_(t){try{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return to(o)}catch(e){return eo(e)}}function Ys(t){return typeof t=="string"?Vs(t):null}async function AP(t){try{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return to(o)}catch(e){return eo(e)}}async function H_(t){try{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.searchObservations(n);return to(o)}catch(e){return eo(e)}}async function W_(t){try{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{}},o=await e.client.contextObservations(n);return to(o)}catch(e){return eo(e)}}function OP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function MP(t){let e=OP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:TP("/api/context/inject",{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Ys(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}})}async function CP(t){try{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return to(n)}catch(e){return eo(e)}}async function NP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),PP();try{let t=wu(),e=await v_(t,Du);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var B_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Cr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` +`)}var Pu=require("node:fs/promises"),qs=require("node:fs"),et=require("node:path"),A_=require("node:os"),M_=require("node:url");var z_="claude";function iP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ls(t){if(!t)return z_;let e=iP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:z_}var aP=qt(ue.API_REQUEST),Ke=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Us=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=cP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??aP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ke("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ke("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:xu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:xu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:xu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ke("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await mu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ke(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ke("http_error",`Server ${e} ${r} returned ${i.status}: ${uP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ke("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function R_(t){return t instanceof Ke}function cP(t){return t.replace(/\/+$/,"")}function xu(t){return typeof t=="string"?Ls(t):null}function uP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function $u(){let e=(ws().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function I_(){let t=ws(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Us(s),projectId:o,serverBaseUrl:r}}var RP={},lP="13.10.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var C_=!1,N_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,M_.fileURLToPath)(RP.url))}catch(t){return C_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Tu=p_()??(0,et.resolve)(N_,"worker-service.cjs");function dP(){C_&&((0,qs.existsSync)(Tu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Tu,mcpServerDir:N_}))}async function pt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ms(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ms(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function pP(){try{return(await Ms("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function fP(){if($u()!=="server")return null;let e=I_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function mP(t){return R_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Kn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Jn(t){let e=fP();if(!e)throw new Ke("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ke("missing_api_key",`${t}: ${e.reason}`);return e}function Gn(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),mP(n)}}}var hP=Gn("observation_add",async t=>{let e=Jn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Kn(o)});function Fs(t){return typeof t=="string"?Ls(t):null}var gP=Gn("observation_record_event",async t=>{let e=Jn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Fs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Kn(o)}),_P=Gn("observation_search",async t=>{let e=Jn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Fs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Kn(o)}),yP=Gn("observation_context",async t=>{let e=Jn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Fs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Kn(o)});function SP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function vP(t){let e=SP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:pt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Fs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var bP=Gn("observation_generation_status",async t=>{let e=Jn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Kn(n)});async function EP(){if(await pP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),dP();try{let t=gu(),e=await f_(t,Tu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var D_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs @@ -239,8 +239,8 @@ NEVER fetch full details without filtering first. 10x token savings.`,inputSchem \`get_observations(ids=[...])\` # ALWAYS batch for 2+ items Returns: Complete details (~500-1000 tokens/result) -**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, platformSource, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},platformSource:{type:"string",description:"Filter by platform source (e.g. claude, codex, cursor) \u2014 restricts results to that agent's own memory"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>{let e=Z_.search;return await Cu(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>{let e=Z_.timeline;return await Cu(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await jr("/api/observations/batch",t)},{name:"session_start_context",description:"Render the exact worker-mode SessionStart context for a project. Calls /api/context/inject and returns the same text hooks inject at startup. Params: project OR projects, platformSource, full, colors.",inputSchema:{type:"object",properties:{project:{type:"string",description:"Project name, e.g. claude-mem/night-parsnip"},projects:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}],description:"Project chain for context injection. Array or comma-separated string; last project is treated as primary."},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},full:{type:"boolean",description:"When true, request full context instead of configured limits"},colors:{type:"boolean",description:"When true, request human terminal-color formatting"}},additionalProperties:!1},handler:async t=>MP(t??{})},{name:"observation_add",description:"Insert a manual observation directly into server storage. Calls /v1/memories \u2014 does NOT enqueue generation. Server runtime only. Params: content (required), projectId (optional, falls back to settings), serverSessionId, kind, metadata.",inputSchema:{type:"object",properties:{projectId:{type:"string",description:"Project id (falls back to CLAUDE_MEM_SERVER_PROJECT_ID)"},serverSessionId:{type:"string",description:"Optional server_session_id to attach the observation to"},kind:{type:"string",description:"Observation kind (default: manual)"},content:{type:"string",description:"Observation content (required)"},metadata:{type:"object",description:"Free-form metadata object",additionalProperties:!0}},required:["content"],additionalProperties:!1},handler:async t=>F_(t??{})},{name:"observation_record_event",description:"Record an agent event into the server. Calls /v1/events \u2014 server inserts the event row, the outbox row, and enqueues a generation job atomically. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},eventType:{type:"string",description:"Event type (required), e.g. PostToolUse, UserPromptSubmit"},sourceType:{type:"string",enum:["hook","worker","provider","server","api"]},serverSessionId:{type:"string"},contentSessionId:{type:"string"},memorySessionId:{type:"string"},platformSource:{type:"string",description:"Optional platform source for session linkage and event scoping"},payload:{description:"Event payload (any JSON value)"},occurredAtEpoch:{type:"number",description:"Unix epoch millis (defaults to now)"},generate:{type:"boolean",description:"If false, skip generation job (default: true)"}},required:["eventType"],additionalProperties:!1},handler:async t=>AP(t??{})},{name:"observation_search",description:"Full-text search across generated observations using the server's GIN tsvector index (Phase 1). Calls /v1/search. Server runtime only. Params: query (required), projectId (optional), platformSource, limit (default 20, max 100).",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max results (default 20, max 100)"}},required:["query"],additionalProperties:!1},handler:async t=>H_(t??{})},{name:"observation_context",description:"Get top-N relevant observations for context injection. Returns matched observations AND a pre-joined context string suitable for prompt injection. Calls /v1/context. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max observations (default 10, max 50)"}},required:["query"],additionalProperties:!1},handler:async t=>W_(t??{})},{name:"observation_generation_status",description:"Look up the status of an observation generation job by id. Calls /v1/jobs/:id. Server runtime only. Returns the same payload as REST.",inputSchema:{type:"object",properties:{jobId:{type:"string",description:"Generation job id (required)"}},required:["jobId"],additionalProperties:!1},handler:async t=>CP(t??{})},{name:"memory_add",description:"Compatibility alias for observation_add. Same behavior; same schema modulo the legacy field names.",inputSchema:{type:"object",properties:{projectId:{type:"string"},kind:{type:"string"},content:{type:"string"},narrative:{type:"string",description:"Legacy alias for content; mapped to content if content is missing"},title:{type:"string",description:"Legacy field; appended to metadata.title"},metadata:{type:"object",additionalProperties:!0}},required:["projectId"],additionalProperties:!0},handler:async t=>{let e={projectId:t?.projectId,content:t?.content??t?.narrative??"",kind:t?.kind,metadata:{...t?.metadata??{},...t?.title?{title:t.title}:{}}};return F_(e)}},{name:"memory_search",description:"Compatibility alias for observation_search. Same FTS path; same /v1/search REST endpoint.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string"},platformSource:{type:"string"},limit:{type:"number"}},required:["projectId","query"],additionalProperties:!0},handler:async t=>H_(t??{})},{name:"memory_context",description:"Compatibility alias for observation_context. Same /v1/context REST endpoint.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string"},platformSource:{type:"string"},limit:{type:"number"}},required:["projectId","query"],additionalProperties:!0},handler:async t=>W_(t??{})},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,tt.resolve)(t.path||process.cwd()),r=await D_(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:j_(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,tt.resolve)(t.file_path),r=await(0,Nu.readFile)(e,"utf-8"),n=Au(e)??process.cwd(),o=M_(r,e,t.symbol_name,n);if(o)return{content:[{type:"text",text:o}]};let s=Hs(r,e,n);if(s.symbols.length>0){let i=s.symbols.map(a=>` - ${a.name} (${a.kind})`).join(` +**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, platformSource, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},limit:{type:"number",description:"Max results (default 20)"},project:{type:"string",description:"Filter by project name"},platformSource:{type:"string",description:"Filter by platform source (e.g. claude, codex, cursor) \u2014 restricts results to that agent's own memory"},type:{type:"string",description:"Filter by observation type"},obs_type:{type:"string",description:"Filter by obs_type field"},dateStart:{type:"string",description:"Start date filter (ISO)"},dateEnd:{type:"string",description:"End date filter (ISO)"},offset:{type:"number",description:"Pagination offset"},orderBy:{type:"string",description:"Sort order: date_desc or date_asc"}},additionalProperties:!0},handler:async t=>await pt("/api/search",{query:t})},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{anchor:{type:"number",description:"Observation ID to center the timeline around"},query:{type:"string",description:"Query to find anchor automatically"},depth_before:{type:"number",description:"Items before anchor (default 3)"},depth_after:{type:"number",description:"Items after anchor (default 3)"},project:{type:"string",description:"Filter by project name"}},additionalProperties:!0},handler:async t=>await pt("/api/timeline",{query:t})},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await pt("/api/observations/batch",{body:t})},{name:"session_start_context",description:"Render the exact worker-mode SessionStart context for a project. Calls /api/context/inject and returns the same text hooks inject at startup. Params: project OR projects, platformSource, full, colors.",inputSchema:{type:"object",properties:{project:{type:"string",description:"Project name, e.g. claude-mem/night-parsnip"},projects:{oneOf:[{type:"array",items:{type:"string"}},{type:"string"}],description:"Project chain for context injection. Array or comma-separated string; last project is treated as primary."},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},full:{type:"boolean",description:"When true, request full context instead of configured limits"},colors:{type:"boolean",description:"When true, request human terminal-color formatting"}},additionalProperties:!1},handler:async t=>vP(t??{})},{name:"observation_add",description:"Insert a manual observation directly into server storage. Calls /v1/memories \u2014 does NOT enqueue generation. Server runtime only. Params: content (required), projectId (optional, falls back to settings), serverSessionId, kind, metadata.",inputSchema:{type:"object",properties:{projectId:{type:"string",description:"Project id (falls back to CLAUDE_MEM_SERVER_PROJECT_ID)"},serverSessionId:{type:"string",description:"Optional server_session_id to attach the observation to"},kind:{type:"string",description:"Observation kind (default: manual)"},content:{type:"string",description:"Observation content (required)"},metadata:{type:"object",description:"Free-form metadata object",additionalProperties:!0}},required:["content"],additionalProperties:!1},handler:async t=>hP(t??{})},{name:"observation_record_event",description:"Record an agent event into the server. Calls /v1/events \u2014 server inserts the event row, the outbox row, and enqueues a generation job atomically. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},eventType:{type:"string",description:"Event type (required), e.g. PostToolUse, UserPromptSubmit"},sourceType:{type:"string",enum:["hook","worker","provider","server","api"]},serverSessionId:{type:"string"},contentSessionId:{type:"string"},memorySessionId:{type:"string"},platformSource:{type:"string",description:"Optional platform source for session linkage and event scoping"},payload:{description:"Event payload (any JSON value)"},occurredAtEpoch:{type:"number",description:"Unix epoch millis (defaults to now)"},generate:{type:"boolean",description:"If false, skip generation job (default: true)"}},required:["eventType"],additionalProperties:!1},handler:async t=>gP(t??{})},{name:"observation_search",description:"Full-text search across generated observations using the server's GIN tsvector index (Phase 1). Calls /v1/search. Server runtime only. Params: query (required), projectId (optional), platformSource, limit (default 20, max 100).",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max results (default 20, max 100)"}},required:["query"],additionalProperties:!1},handler:async t=>_P(t??{})},{name:"observation_context",description:"Get top-N relevant observations for context injection. Returns matched observations AND a pre-joined context string suitable for prompt injection. Calls /v1/context. Server runtime only.",inputSchema:{type:"object",properties:{projectId:{type:"string"},query:{type:"string",description:"Search query (required)"},platformSource:{type:"string",description:"Optional platform source filter, e.g. claude, codex, cursor"},limit:{type:"number",description:"Max observations (default 10, max 50)"}},required:["query"],additionalProperties:!1},handler:async t=>yP(t??{})},{name:"observation_generation_status",description:"Look up the status of an observation generation job by id. Calls /v1/jobs/:id. Server runtime only. Returns the same payload as REST.",inputSchema:{type:"object",properties:{jobId:{type:"string",description:"Generation job id (required)"}},required:["jobId"],additionalProperties:!1},handler:async t=>bP(t??{})},{name:"smart_search",description:"Search codebase for symbols, functions, classes using tree-sitter AST parsing. Returns folded structural views with token counts. Use path parameter to scope the search.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search term \u2014 matches against symbol names, file names, and file content"},path:{type:"string",description:"Root directory to search (default: current working directory)"},max_results:{type:"number",description:"Maximum results to return (default: 20)"},file_pattern:{type:"string",description:'Substring filter for file paths (e.g. ".ts", "src/services")'}},required:["query"]},handler:async t=>{let e=(0,et.resolve)(t.path||process.cwd()),r=await P_(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:T_(r,t.query)}]}}},{name:"smart_unfold",description:"Expand a specific symbol (function, class, method) from a file. Returns the full source code of just that symbol. Use after smart_search or smart_outline to read specific code.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"},symbol_name:{type:"string",description:"Name of the symbol to unfold (function, class, method, etc.)"}},required:["file_path","symbol_name"]},handler:async t=>{let e=(0,et.resolve)(t.file_path),r=await(0,Pu.readFile)(e,"utf-8"),n=x_(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let o=Ds(r,e);if(o.symbols.length>0){let s=o.symbols.map(i=>` - ${i.name} (${i.kind})`).join(` `);return{content:[{type:"text",text:`Symbol "${t.symbol_name}" not found in ${t.file_path}. Available symbols: -${i}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,tt.resolve)(t.file_path),r=await(0,Nu.readFile)(e,"utf-8"),n=Hs(r,e,Au(e)??process.cwd());return n.symbols.length>0?{content:[{type:"text",text:Nr(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await jr("/api/corpus",t)},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await Cu("/api/corpus",t)},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/prime`,r)}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/query`,r)}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/rebuild`,r)}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await jr(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],ju=new $s({name:"claude-mem",version:$P},{capabilities:{tools:{}}});ju.setRequestHandler(ua,async()=>({tools:B_.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));ju.setRequestHandler(dn,async t=>{let e=B_.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var DP=3e4,Qn=null,V_=!1;function Js(){no("stdio-closed")}function X_(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),no("stdio-error")}function jP(){process.stdin.on("end",Js),process.stdin.on("close",Js),process.stdin.on("error",X_)}function LP(){process.stdin.off("end",Js),process.stdin.off("close",Js),process.stdin.off("error",X_)}function UP(){if(process.platform==="win32")return;let t=process.ppid;Qn=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),no())},DP),Qn.unref&&Qn.unref()}function no(t="shutdown"){V_||(V_=!0,Qn&&clearInterval(Qn),LP(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",no);process.on("SIGINT",no);function qP(){try{let t=(0,K_.homedir)(),e=[(0,tt.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,tt.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,Gs.existsSync)(i)),n=[(0,tt.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,tt.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],o=n.some(i=>i&&(0,Gs.existsSync)(i)),s=n[0];!r&&o&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:s})}catch{}}async function ZP(){let t=new Ts;jP(),await ju.connect(t),y.info("SYSTEM","Claude-mem search server started"),qP(),UP(),setTimeout(async()=>{if(Mu()==="server"){y.info("SYSTEM","MCP runtime=server \u2014 skipping worker auto-start",void 0,{});return}await NP()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}ZP().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)}); +${s}`}]}}return{content:[{type:"text",text:`Could not parse ${t.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async t=>{let e=(0,et.resolve)(t.file_path),r=await(0,Pu.readFile)(e,"utf-8"),n=Ds(r,e);return n.symbols.length>0?{content:[{type:"text",text:Cr(n)}]}:{content:[{type:"text",text:`Could not parse ${t.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async t=>await pt("/api/corpus",{body:t})},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>await pt("/api/corpus",{query:t})},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/prime`,{body:r})}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/query`,{body:r})}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/rebuild`,{body:r})}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async t=>{let{name:e,...r}=t;if(typeof e!="string"||e.trim()==="")throw new Error("Missing required argument: name");return await pt(`/api/corpus/${encodeURIComponent(e)}/reprime`,{body:r})}}],zu=new ys({name:"claude-mem",version:lP},{capabilities:{tools:{}}});zu.setRequestHandler(na,async()=>({tools:D_.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));zu.setRequestHandler(cn,async t=>{let e=D_.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return y.error("SYSTEM","Tool execution failed",{tool:t.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var wP=3e4,Vn=null,O_=!1;function Zs(){Yn("stdio-closed")}function j_(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Yn("stdio-error")}function kP(){process.stdin.on("end",Zs),process.stdin.on("close",Zs),process.stdin.on("error",j_)}function xP(){process.stdin.off("end",Zs),process.stdin.off("close",Zs),process.stdin.off("error",j_)}function $P(){if(process.platform==="win32")return;let t=process.ppid;Vn=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),Yn())},wP),Vn.unref&&Vn.unref()}function Yn(t="shutdown"){O_||(O_=!0,Vn&&clearInterval(Vn),xP(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Yn);process.on("SIGINT",Yn);function PP(){let t=(0,A_.homedir)(),e=[(0,et.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,et.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,qs.existsSync)(i)),n=[(0,et.resolve)(t,".claude","plugins","cache","thedotmack","claude-mem"),(0,et.resolve)(t,".config","claude","plugins","cache","thedotmack","claude-mem")],o=n.some(i=>i&&(0,qs.existsSync)(i)),s=n[0];!r&&o&&y.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:e,cacheRoot:s})}function TP(){try{PP()}catch(t){y.warn("SYSTEM","checkMarketplaceMarker failed (non-fatal startup check)",void 0,t instanceof Error?t:new Error(String(t)))}}async function zP(){let t=new vs;kP(),await zu.connect(t),y.info("SYSTEM","Claude-mem search server started"),TP(),$P(),setTimeout(async()=>{if($u()==="server"){y.info("SYSTEM","MCP runtime=server \u2014 skipping worker auto-start",void 0,{});return}await EP()?y.info("SYSTEM","Worker available",void 0,{}):(y.error("SYSTEM","Worker not available",void 0,{}),y.error("SYSTEM","Tools will fail until Worker is started"),y.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}zP().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)}); diff --git a/src/npx-cli/install/setup-runtime.ts b/src/npx-cli/install/setup-runtime.ts index 23d319aca..e532f087a 100644 --- a/src/npx-cli/install/setup-runtime.ts +++ b/src/npx-cli/install/setup-runtime.ts @@ -527,7 +527,8 @@ export async function installPluginDependencies(targetDir: string, bunPath: stri try { await ensureTreeSitterCliBinary(targetDir); } catch (error) { - throw new Error(`tree-sitter-cli setup failed in ${targetDir}\n${describeExecError(error)}`); + const err = error instanceof Error ? error : new Error(String(error)); + throw new Error(`tree-sitter-cli setup failed in ${targetDir}\n${describeExecError(err)}`); } verifyCriticalModules(targetDir); @@ -569,6 +570,19 @@ export function writeInstallMarker( writeFileSync(markerPath(targetDir), JSON.stringify(payload)); } +function pluginDeclaresTreeSitterCli(targetDir: string): boolean { + try { + const pkg = JSON.parse(readFileSync(join(targetDir, 'package.json'), 'utf-8')); + return Object.keys(pkg.dependencies || {}).includes('tree-sitter-cli'); + } catch { + // [ANTI-PATTERN IGNORED]: a missing or unparseable package.json in an + // incomplete/partial install is an expected negative — treat it as "does + // not declare tree-sitter-cli" so the caller re-provisions rather than + // throwing. + return false; + } +} + export function isInstallCurrent(targetDir: string, expectedVersion: string): boolean { if (!existsSync(join(targetDir, 'node_modules'))) return false; const marker = readInstallMarker(targetDir); @@ -578,5 +592,13 @@ export function isInstallCurrent(targetDir: string, expectedVersion: string): bo if (currentBun && !marker.bun) return false; if (!currentBun && marker.bun) return false; if (currentBun && marker.bun && currentBun !== marker.bun) return false; + // A present marker is not sufficient if the smart-explore runtime it vouches + // for is missing. A prior install can write .install-version and later lose + // (or never have downloaded) the tree-sitter-cli executable; without this + // check the install fast path treats that cache as current and skips the + // provisioning/validation that would repair it, leaving smart-explore broken. + if (pluginDeclaresTreeSitterCli(targetDir) && !isTreeSitterCliBinaryUsable(targetDir)) { + return false; + } return true; } diff --git a/src/services/smart-file-read/parser.ts b/src/services/smart-file-read/parser.ts index 82bbe3c0a..041f03374 100644 --- a/src/services/smart-file-read/parser.ts +++ b/src/services/smart-file-read/parser.ts @@ -355,28 +355,55 @@ function getQueryFile(queryKey: string): string { let cachedBinPath: string | null = null; let treeSitterCacheDir: string | null = null; -function getTreeSitterBin(): string { +type TreeSitterBinDeps = { + platform: NodeJS.Platform; + fileExists: typeof existsSync; + resolvePackageJson: (id: string) => string; +}; + +const treeSitterBinDeps: TreeSitterBinDeps = { + platform: process.platform, + fileExists: existsSync, + resolvePackageJson: (id: string) => _require.resolve(id), +}; + +export function resetTreeSitterBinCacheForTests(): void { + cachedBinPath = null; +} + +export function setTreeSitterBinDepsForTests( + overrides?: Partial, +): void { + treeSitterBinDeps.platform = overrides?.platform ?? process.platform; + treeSitterBinDeps.fileExists = overrides?.fileExists ?? existsSync; + treeSitterBinDeps.resolvePackageJson = overrides?.resolvePackageJson ?? ((id: string) => _require.resolve(id)); +} + +export function getTreeSitterBin(): string { if (cachedBinPath) return cachedBinPath; + let pkgPath: string; try { - const pkgPath = _require.resolve("tree-sitter-cli/package.json"); - const pkgDir = dirname(pkgPath); - // tree-sitter-cli's install.js writes `tree-sitter.exe` on Windows and an - // extensionless `tree-sitter` elsewhere. Checking only the extensionless - // name discards a valid Windows binary and falls through to a bare-PATH - // lookup that usually fails, producing silent 0-symbol results (#2910 / #1247). - const candidates = process.platform === "win32" - ? ["tree-sitter.exe", "tree-sitter"] - : ["tree-sitter"]; - for (const name of candidates) { - const binPath = join(pkgDir, name); - if (existsSync(binPath)) { - cachedBinPath = binPath; - return binPath; - } - } + pkgPath = treeSitterBinDeps.resolvePackageJson("tree-sitter-cli/package.json"); } catch { // [ANTI-PATTERN IGNORED]: tree-sitter-cli not in node_modules is expected; falls back to PATH + cachedBinPath = "tree-sitter"; + return cachedBinPath; + } + + // tree-sitter-cli's install.js writes `tree-sitter.exe` on Windows and an + // extensionless `tree-sitter` elsewhere. Checking only the extensionless + // name discards a valid Windows binary and falls through to a bare-PATH + // lookup that usually fails, producing silent 0-symbol results (#2910 / #1247). + const candidateNames = treeSitterBinDeps.platform === "win32" + ? ["tree-sitter.exe", "tree-sitter"] + : ["tree-sitter"]; + for (const candidateName of candidateNames) { + const binPath = join(dirname(pkgPath), candidateName); + if (treeSitterBinDeps.fileExists(binPath)) { + cachedBinPath = binPath; + return binPath; + } } cachedBinPath = "tree-sitter"; diff --git a/tests/services/smart-file-read/tree-sitter-bin.test.ts b/tests/services/smart-file-read/tree-sitter-bin.test.ts new file mode 100644 index 000000000..217fc24cb --- /dev/null +++ b/tests/services/smart-file-read/tree-sitter-bin.test.ts @@ -0,0 +1,62 @@ +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { dirname, join } from 'node:path'; +import { + getTreeSitterBin, + resetTreeSitterBinCacheForTests, + setTreeSitterBinDepsForTests, +} from '../../../src/services/smart-file-read/parser.js'; + +describe('tree-sitter binary resolution', () => { + const fakePackageJsonPath = join('C:', 'repo', 'node_modules', 'tree-sitter-cli', 'package.json'); + + // Reset before each test too: the module-level bin cache can be populated by + // other suites (e.g. parser.test.ts) running earlier in the same process. + beforeEach(() => { + resetTreeSitterBinCacheForTests(); + setTreeSitterBinDepsForTests(); + }); + + afterEach(() => { + resetTreeSitterBinCacheForTests(); + setTreeSitterBinDepsForTests(); + }); + + it('prefers package-local tree-sitter.exe on Windows', () => { + setTreeSitterBinDepsForTests({ + platform: 'win32', + resolvePackageJson: (id: string) => { + if (id === 'tree-sitter-cli/package.json') return fakePackageJsonPath; + throw new Error(`unexpected resolve: ${id}`); + }, + fileExists: (candidatePath: string) => { + return candidatePath === join(dirname(fakePackageJsonPath), 'tree-sitter.exe'); + }, + }); + + expect(getTreeSitterBin()).toBe(join(dirname(fakePackageJsonPath), 'tree-sitter.exe')); + }); + + it('falls back to PATH when no package-local binary exists', () => { + setTreeSitterBinDepsForTests({ + platform: 'win32', + resolvePackageJson: () => fakePackageJsonPath, + fileExists: () => false, + }); + + expect(getTreeSitterBin()).toBe('tree-sitter'); + }); + + it('uses the bare tree-sitter name on non-Windows platforms', () => { + const fakeUnixPackageJsonPath = join('/repo', 'node_modules', 'tree-sitter-cli', 'package.json'); + setTreeSitterBinDepsForTests({ + platform: 'linux', + resolvePackageJson: () => fakeUnixPackageJsonPath, + fileExists: (candidatePath: string) => { + expect(candidatePath.endsWith('tree-sitter.exe')).toBe(false); + return candidatePath === join(dirname(fakeUnixPackageJsonPath), 'tree-sitter'); + }, + }); + + expect(getTreeSitterBin()).toBe(join(dirname(fakeUnixPackageJsonPath), 'tree-sitter')); + }); +}); diff --git a/tests/setup-runtime.test.ts b/tests/setup-runtime.test.ts index 2a282fcbd..3d6bde69d 100644 --- a/tests/setup-runtime.test.ts +++ b/tests/setup-runtime.test.ts @@ -133,6 +133,23 @@ describe('setup-runtime install marker', () => { writeFileSync(join(tempDir, '.install-version'), '1.0.0\n'); expect(isInstallCurrent(tempDir, '1.0.0')).toBe(false); }); + + it('returns false when tree-sitter-cli is declared but its binary is unusable', () => { + const bunVersion = probeBunVersion(); + if (!bunVersion) { + return; + } + mkdirSync(join(tempDir, 'node_modules'), { recursive: true }); + // Plugin declares tree-sitter-cli, but no working executable is present — + // e.g. a prior install wrote the marker and later lost the binary. The + // fast path must not treat this stale cache as current. + writeFileSync( + join(tempDir, 'package.json'), + JSON.stringify({ dependencies: { 'tree-sitter-cli': '^0.26.5' } }), + ); + writeInstallMarker(tempDir, '1.0.0', bunVersion, '0.1.0'); + expect(isInstallCurrent(tempDir, '1.0.0')).toBe(false); + }); }); describe('platform remediation strings (Phase 5)', () => {