#!/usr/bin/env node "use strict";var sd=Object.create;var Gi=Object.defineProperty;var od=Object.getOwnPropertyDescriptor;var id=Object.getOwnPropertyNames;var ad=Object.getPrototypeOf,cd=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ld=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of id(e))!cd.call(t,s)&&s!==r&&Gi(t,s,{get:()=>e[s],enumerable:!(n=od(e,s))||n.enumerable});return t};var pe=(t,e,r)=>(r=t!=null?sd(ad(t)):{},ld(e||!t||!t.__esModule?Gi(r,"default",{value:t,enumerable:!0}):r,t));var lr=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.regexpCode=N.getEsmExportName=N.getProperty=N.safeStringify=N.stringify=N.strConcat=N.addCodeArg=N.str=N._=N.nil=N._Code=N.Name=N.IDENTIFIER=N._CodeOrName=void 0;var ar=class{};N._CodeOrName=ar;N.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ot=class extends ar{constructor(e){if(super(),!N.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}}};N.Name=ot;var ye=class extends ar{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 ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};N._Code=ye;N.nil=new ye("");function ga(t,...e){let r=[t[0]],n=0;for(;n{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.ValueScope=oe.ValueScopeName=oe.Scope=oe.varKinds=oe.UsedValueState=void 0;var se=lr(),Os=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},un;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(un||(oe.UsedValueState=un={}));oe.varKinds={const:new se.Name("const"),let:new se.Name("let"),var:new se.Name("var")};var dn=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof se.Name?e:this.name(e)}name(e){return new se.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}}};oe.Scope=dn;var fn=class extends se.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,se._)`.${new se.Name(r)}[${n}]`}};oe.ValueScopeName=fn;var _p=(0,se._)`\n`,Is=class extends dn{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?_p:se.nil}}get(){return this._scope}name(e){return new fn(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[o];if(c){let d=c.get(i);if(d)return d}else c=this._values[o]=new Map;c.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),u=l.length;return l[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,se._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=se.nil;for(let i in e){let c=e[i];if(!c)continue;let l=n[i]=n[i]||new Map;c.forEach(u=>{if(l.has(u))return;l.set(u,un.Started);let d=r(u);if(d){let f=this.opts.es5?oe.varKinds.var:oe.varKinds.const;o=(0,se._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,se._)`${o}${d}${this.opts._n}`;else throw new Os(u);l.set(u,un.Completed)})}return o}};oe.ValueScope=Is});var R=b(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 I=lr(),ve=xs(),Je=lr();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return Je._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return Je.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return Je.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return Je.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return Je.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return Je.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return Je.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return Je.Name}});var gn=xs();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return gn.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return gn.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return gn.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return gn.varKinds}});M.operators={GT:new I._Code(">"),GTE:new I._Code(">="),LT:new I._Code("<"),LTE:new I._Code("<="),EQ:new I._Code("==="),NEQ:new I._Code("!=="),NOT:new I._Code("!"),OR:new I._Code("||"),AND:new I._Code("&&"),ADD:new I._Code("+")};var Ue=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ds=class extends Ue{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ve.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=kt(this.rhs,e,r)),this}get names(){return this.rhs instanceof I._CodeOrName?this.rhs.names:{}}},pn=class extends Ue{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 I.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=kt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof I.Name?{}:{...this.lhs.names};return hn(e,this.rhs)}},Ns=class extends pn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zs=class extends Ue{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ls=class extends Ue{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},js=class extends Ue{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},qs=class extends Ue{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=kt(this.code,e,r),this}get names(){return this.code instanceof I._CodeOrName?this.code.names:{}}},ur=class extends Ue{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(Sp(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ct(e,r.names),{})}},Fe=class extends ur{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Us=class extends ur{},vt=class extends Fe{};vt.kind="else";var it=class t extends Fe{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 vt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(_a(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=kt(this.condition,e,r),this}get names(){let e=super.names;return hn(e,this.condition),this.else&&ct(e,this.else.names),e}};it.kind="if";var at=class extends Fe{};at.kind="for";var Fs=class extends at{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=kt(this.iteration,e,r),this}get names(){return ct(super.names,this.iteration.names)}},Hs=class extends at{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ve.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=hn(super.names,this.from);return hn(e,this.to)}},mn=class extends at{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=kt(this.iterable,e,r),this}get names(){return ct(super.names,this.iterable.names)}},dr=class extends Fe{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)}};dr.kind="func";var fr=class extends ur{render(e){return"return "+super.render(e)}};fr.kind="return";var Ws=class extends Fe{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&ct(e,this.catch.names),this.finally&&ct(e,this.finally.names),e}},pr=class extends Fe{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};pr.kind="catch";var mr=class extends Fe{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Vs=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` `:""},this._extScope=e,this._scope=new ve.Scope({parent:e}),this._nodes=[new Us]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Ds(e,o,n)),o}const(e,r,n){return this._def(ve.varKinds.const,e,r,n)}let(e,r,n){return this._def(ve.varKinds.let,e,r,n)}var(e,r,n){return this._def(ve.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new pn(e,r,n))}add(e,r){return this._leafNode(new Ns(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==I.nil&&this._leafNode(new qs(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,I.addCodeArg)(r,s));return r.push("}"),new I._Code(r)}if(e,r,n){if(this._blockNode(new it(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 it(e))}else(){return this._elseNode(new vt)}endIf(){return this._endBlockNode(it,vt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Fs(e),r)}forRange(e,r,n,s,o=this.opts.es5?ve.varKinds.var:ve.varKinds.let){let i=this._scope.toName(e);return this._for(new Hs(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ve.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof I.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,I._)`${i}.length`,c=>{this.var(o,(0,I._)`${i}[${c}]`),n(o)})}return this._for(new mn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ve.varKinds.var:ve.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,I._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new mn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(at)}label(e){return this._leafNode(new zs(e))}break(e){return this._leafNode(new Ls(e))}return(e){let r=new fr;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fr)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ws;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new pr(o),r(o)}return n&&(this._currNode=s.finally=new mr,this.code(n)),this._endBlockNode(pr,mr)}throw(e){return this._leafNode(new js(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=I.nil,n,s){return this._blockNode(new dr(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(dr)}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 it))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=Vs;function ct(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function hn(t,e){return e instanceof I._CodeOrName?ct(t,e.names):t}function kt(t,e,r){if(t instanceof I.Name)return n(t);if(!s(t))return t;return new I._Code(t._items.reduce((o,i)=>(i instanceof I.Name&&(i=n(i)),i instanceof I._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof I._Code&&o._items.some(i=>i instanceof I.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Sp(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function _a(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,I._)`!${Gs(t)}`}M.not=_a;var Ep=Sa(M.operators.AND);function wp(...t){return t.reduce(Ep)}M.and=wp;var bp=Sa(M.operators.OR);function vp(...t){return t.reduce(bp)}M.or=vp;function Sa(t){return(e,r)=>e===I.nil?r:r===I.nil?e:(0,I._)`${Gs(e)} ${t} ${Gs(r)}`}function Gs(t){return t instanceof I.Name?t:(0,I._)`(${t})`}});var x=b(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.checkStrictMode=A.getErrorPath=A.Type=A.useFunc=A.setEvaluated=A.evaluatedPropsToName=A.mergeEvaluated=A.eachItem=A.unescapeJsonPointer=A.escapeJsonPointer=A.escapeFragment=A.unescapeFragment=A.schemaRefOrVal=A.schemaHasRulesButRef=A.schemaHasRules=A.checkUnknownRules=A.alwaysValidSchema=A.toHash=void 0;var j=R(),kp=lr();function Pp(t){let e={};for(let r of t)e[r]=!0;return e}A.toHash=Pp;function Tp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ba(t,e),!va(e,t.self.RULES.all))}A.alwaysValidSchema=Tp;function ba(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||Ta(t,`unknown keyword: "${o}"`)}A.checkUnknownRules=ba;function va(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}A.schemaHasRules=va;function $p(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}A.schemaHasRulesButRef=$p;function Rp({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,j._)`${r}`}return(0,j._)`${t}${e}${(0,j.getProperty)(n)}`}A.schemaRefOrVal=Rp;function Mp(t){return ka(decodeURIComponent(t))}A.unescapeFragment=Mp;function Cp(t){return encodeURIComponent(Ys(t))}A.escapeFragment=Cp;function Ys(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}A.escapeJsonPointer=Ys;function ka(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}A.unescapeJsonPointer=ka;function Ap(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}A.eachItem=Ap;function Ea({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,c)=>{let l=i===void 0?o:i instanceof j.Name?(o instanceof j.Name?t(s,o,i):e(s,o,i),i):o instanceof j.Name?(e(s,i,o),o):r(o,i);return c===j.Name&&!(l instanceof j.Name)?n(s,l):l}}A.mergeEvaluated={props:Ea({mergeNames:(t,e,r)=>t.if((0,j._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,j._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,j._)`${r} || {}`).code((0,j._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,j._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,j._)`${r} || {}`),Bs(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pa}),items:Ea({mergeNames:(t,e,r)=>t.if((0,j._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,j._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,j._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,j._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Pa(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,j._)`{}`);return e!==void 0&&Bs(t,r,e),r}A.evaluatedPropsToName=Pa;function Bs(t,e,r){Object.keys(r).forEach(n=>t.assign((0,j._)`${e}${(0,j.getProperty)(n)}`,!0))}A.setEvaluated=Bs;var wa={};function Op(t,e){return t.scopeValue("func",{ref:e,code:wa[e.code]||(wa[e.code]=new kp._Code(e.code))})}A.useFunc=Op;var Ks;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ks||(A.Type=Ks={}));function Ip(t,e,r){if(t instanceof j.Name){let n=e===Ks.Num;return r?n?(0,j._)`"[" + ${t} + "]"`:(0,j._)`"['" + ${t} + "']"`:n?(0,j._)`"/" + ${t}`:(0,j._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,j.getProperty)(t).toString():"/"+Ys(t)}A.getErrorPath=Ip;function Ta(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}A.checkStrictMode=Ta});var He=b(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var X=R(),xp={data:new X.Name("data"),valCxt:new X.Name("valCxt"),instancePath:new X.Name("instancePath"),parentData:new X.Name("parentData"),parentDataProperty:new X.Name("parentDataProperty"),rootData:new X.Name("rootData"),dynamicAnchors:new X.Name("dynamicAnchors"),vErrors:new X.Name("vErrors"),errors:new X.Name("errors"),this:new X.Name("this"),self:new X.Name("self"),scope:new X.Name("scope"),json:new X.Name("json"),jsonPos:new X.Name("jsonPos"),jsonLen:new X.Name("jsonLen"),jsonPart:new X.Name("jsonPart")};Js.default=xp});var hr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.extendErrors=Q.resetErrorsCount=Q.reportExtraError=Q.reportError=Q.keyword$DataError=Q.keywordError=void 0;var D=R(),yn=x(),re=He();Q.keywordError={message:({keyword:t})=>(0,D.str)`must pass "${t}" keyword validation`};Q.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,D.str)`"${t}" keyword must be ${e} ($data)`:(0,D.str)`"${t}" keyword is invalid ($data)`};function Dp(t,e=Q.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:c}=s,l=Ma(t,e,r);n??(i||c)?$a(o,l):Ra(s,(0,D._)`[${l}]`)}Q.reportError=Dp;function Np(t,e=Q.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,c=Ma(t,e,r);$a(s,c),o||i||Ra(n,re.default.vErrors)}Q.reportExtraError=Np;function zp(t,e){t.assign(re.default.errors,e),t.if((0,D._)`${re.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,D._)`${re.default.vErrors}.length`,e),()=>t.assign(re.default.vErrors,null)))}Q.resetErrorsCount=zp;function Lp({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,re.default.errors,c=>{t.const(i,(0,D._)`${re.default.vErrors}[${c}]`),t.if((0,D._)`${i}.instancePath === undefined`,()=>t.assign((0,D._)`${i}.instancePath`,(0,D.strConcat)(re.default.instancePath,o.errorPath))),t.assign((0,D._)`${i}.schemaPath`,(0,D.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,D._)`${i}.schema`,r),t.assign((0,D._)`${i}.data`,n))})}Q.extendErrors=Lp;function $a(t,e){let r=t.const("err",e);t.if((0,D._)`${re.default.vErrors} === null`,()=>t.assign(re.default.vErrors,(0,D._)`[${r}]`),(0,D._)`${re.default.vErrors}.push(${r})`),t.code((0,D._)`${re.default.errors}++`)}function Ra(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,D._)`new ${t.ValidationError}(${e})`):(r.assign((0,D._)`${n}.errors`,e),r.return(!1))}var lt={keyword:new D.Name("keyword"),schemaPath:new D.Name("schemaPath"),params:new D.Name("params"),propertyName:new D.Name("propertyName"),message:new D.Name("message"),schema:new D.Name("schema"),parentSchema:new D.Name("parentSchema")};function Ma(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,D._)`{}`:jp(t,e,r)}function jp(t,e,r={}){let{gen:n,it:s}=t,o=[qp(s,r),Up(t,r)];return Fp(t,e,o),n.object(...o)}function qp({errorPath:t},{instancePath:e}){let r=e?(0,D.str)`${t}${(0,yn.getErrorPath)(e,yn.Type.Str)}`:t;return[re.default.instancePath,(0,D.strConcat)(re.default.instancePath,r)]}function Up({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,D.str)`${e}/${t}`;return r&&(s=(0,D.str)`${s}${(0,yn.getErrorPath)(r,yn.Type.Str)}`),[lt.schemaPath,s]}function Fp(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:c}=t,{opts:l,propertyName:u,topSchemaRef:d,schemaPath:f}=c;n.push([lt.keyword,s],[lt.params,typeof e=="function"?e(t):e||(0,D._)`{}`]),l.messages&&n.push([lt.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([lt.schema,i],[lt.parentSchema,(0,D._)`${d}${f}`],[re.default.data,o]),u&&n.push([lt.propertyName,u])}});var Aa=b(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.boolOrEmptySchema=Pt.topBoolOrEmptySchema=void 0;var Hp=hr(),Wp=R(),Vp=He(),Gp={message:"boolean schema is false"};function Kp(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ca(t,!1):typeof r=="object"&&r.$async===!0?e.return(Vp.default.data):(e.assign((0,Wp._)`${n}.errors`,null),e.return(!0))}Pt.topBoolOrEmptySchema=Kp;function Yp(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ca(t)):r.var(e,!0)}Pt.boolOrEmptySchema=Yp;function Ca(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Hp.reportError)(s,Gp,void 0,e)}});var Zs=b(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getRules=Tt.isJSONType=void 0;var Bp=["string","number","integer","boolean","null","object","array"],Jp=new Set(Bp);function Zp(t){return typeof t=="string"&&Jp.has(t)}Tt.isJSONType=Zp;function Xp(){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:{}}}Tt.getRules=Xp});var Xs=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.shouldUseRule=Ze.shouldUseGroup=Ze.schemaHasRulesForType=void 0;function Qp({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Oa(t,n)}Ze.schemaHasRulesForType=Qp;function Oa(t,e){return e.rules.some(r=>Ia(t,r))}Ze.shouldUseGroup=Oa;function Ia(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))}Ze.shouldUseRule=Ia});var gr=b(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 em=Zs(),tm=Xs(),rm=hr(),$=R(),xa=x(),$t;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})($t||(ee.DataType=$t={}));function nm(t){let e=Da(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=nm;function Da(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(em.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ee.getJSONTypes=Da;function sm(t,e){let{gen:r,data:n,opts:s}=t,o=om(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,tm.schemaHasRulesForType)(t,e[0]));if(i){let c=eo(e,n,s.strictNumbers,$t.Wrong);r.if(c,()=>{o.length?im(t,e,o):to(t)})}return i}ee.coerceAndCheckDataType=sm;var Na=new Set(["string","number","integer","boolean","null"]);function om(t,e){return e?t.filter(r=>Na.has(r)||e==="array"&&r==="array"):[]}function im(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,$._)`typeof ${s}`),c=n.let("coerced",(0,$._)`undefined`);o.coerceTypes==="array"&&n.if((0,$._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,$._)`${s}[0]`).assign(i,(0,$._)`typeof ${s}`).if(eo(e,s,o.strictNumbers),()=>n.assign(c,s))),n.if((0,$._)`${c} !== undefined`);for(let u of r)(Na.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),to(t),n.endIf(),n.if((0,$._)`${c} !== undefined`,()=>{n.assign(s,c),am(t,c)});function l(u){switch(u){case"string":n.elseIf((0,$._)`${i} == "number" || ${i} == "boolean"`).assign(c,(0,$._)`"" + ${s}`).elseIf((0,$._)`${s} === null`).assign(c,(0,$._)`""`);return;case"number":n.elseIf((0,$._)`${i} == "boolean" || ${s} === null || (${i} == "string" && ${s} && ${s} == +${s})`).assign(c,(0,$._)`+${s}`);return;case"integer":n.elseIf((0,$._)`${i} === "boolean" || ${s} === null || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(c,(0,$._)`+${s}`);return;case"boolean":n.elseIf((0,$._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(c,!1).elseIf((0,$._)`${s} === "true" || ${s} === 1`).assign(c,!0);return;case"null":n.elseIf((0,$._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(c,null);return;case"array":n.elseIf((0,$._)`${i} === "string" || ${i} === "number" || ${i} === "boolean" || ${s} === null`).assign(c,(0,$._)`[${s}]`)}}}function am({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,$._)`${e} !== undefined`,()=>t.assign((0,$._)`${e}[${r}]`,n))}function Qs(t,e,r,n=$t.Correct){let s=n===$t.Correct?$.operators.EQ:$.operators.NEQ,o;switch(t){case"null":return(0,$._)`${e} ${s} null`;case"array":o=(0,$._)`Array.isArray(${e})`;break;case"object":o=(0,$._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,$._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,$._)`typeof ${e} ${s} ${t}`}return n===$t.Correct?o:(0,$.not)(o);function i(c=$.nil){return(0,$.and)((0,$._)`typeof ${e} == "number"`,c,r?(0,$._)`isFinite(${e})`:$.nil)}}ee.checkDataType=Qs;function eo(t,e,r,n){if(t.length===1)return Qs(t[0],e,r,n);let s,o=(0,xa.toHash)(t);if(o.array&&o.object){let i=(0,$._)`typeof ${e} != "object"`;s=o.null?i:(0,$._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=$.nil;o.number&&delete o.integer;for(let i in o)s=(0,$.and)(s,Qs(i,e,r,n));return s}ee.checkDataTypes=eo;var cm={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,$._)`{type: ${t}}`:(0,$._)`{type: ${e}}`};function to(t){let e=lm(t);(0,rm.reportError)(e,cm)}ee.reportTypeError=to;function lm(t){let{gen:e,data:r,schema:n}=t,s=(0,xa.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var La=b(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.assignDefaults=void 0;var Rt=R(),um=x();function dm(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)za(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>za(t,o,s.default))}_n.assignDefaults=dm;function za(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let c=(0,Rt._)`${o}${(0,Rt.getProperty)(e)}`;if(s){(0,um.checkStrictMode)(t,`default is ignored for: ${c}`);return}let l=(0,Rt._)`${c} === undefined`;i.useDefaults==="empty"&&(l=(0,Rt._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,Rt._)`${c} = ${(0,Rt.stringify)(r)}`)}});var _e=b(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.validateUnion=L.validateArray=L.usePattern=L.callValidateCode=L.schemaProperties=L.allSchemaProperties=L.noPropertyInData=L.propertyInData=L.isOwnProperty=L.hasPropFunc=L.reportMissingProp=L.checkMissingProp=L.checkReportMissingProp=void 0;var q=R(),ro=x(),Xe=He(),fm=x();function pm(t,e){let{gen:r,data:n,it:s}=t;r.if(so(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,q._)`${e}`},!0),t.error()})}L.checkReportMissingProp=pm;function mm({gen:t,data:e,it:{opts:r}},n,s){return(0,q.or)(...n.map(o=>(0,q.and)(so(t,e,o,r.ownProperties),(0,q._)`${s} = ${o}`)))}L.checkMissingProp=mm;function hm(t,e){t.setParams({missingProperty:e},!0),t.error()}L.reportMissingProp=hm;function ja(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,q._)`Object.prototype.hasOwnProperty`})}L.hasPropFunc=ja;function no(t,e,r){return(0,q._)`${ja(t)}.call(${e}, ${r})`}L.isOwnProperty=no;function gm(t,e,r,n){let s=(0,q._)`${e}${(0,q.getProperty)(r)} !== undefined`;return n?(0,q._)`${s} && ${no(t,e,r)}`:s}L.propertyInData=gm;function so(t,e,r,n){let s=(0,q._)`${e}${(0,q.getProperty)(r)} === undefined`;return n?(0,q.or)(s,(0,q.not)(no(t,e,r))):s}L.noPropertyInData=so;function qa(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}L.allSchemaProperties=qa;function ym(t,e){return qa(e).filter(r=>!(0,ro.alwaysValidSchema)(t,e[r]))}L.schemaProperties=ym;function _m({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},c,l,u){let d=u?(0,q._)`${t}, ${e}, ${n}${s}`:e,f=[[Xe.default.instancePath,(0,q.strConcat)(Xe.default.instancePath,o)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);let p=(0,q._)`${d}, ${r.object(...f)}`;return l!==q.nil?(0,q._)`${c}.call(${l}, ${p})`:(0,q._)`${c}(${p})`}L.callValidateCode=_m;var Sm=(0,q._)`new RegExp`;function Em({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,q._)`${s.code==="new RegExp"?Sm:(0,fm.useFunc)(t,s)}(${r}, ${n})`})}L.usePattern=Em;function wm(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let c=e.let("valid",!0);return i(()=>e.assign(c,!1)),c}return e.var(o,!0),i(()=>e.break()),o;function i(c){let l=e.const("len",(0,q._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ro.Type.Num},o),e.if((0,q.not)(o),c)})}}L.validateArray=wm;function bm(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,ro.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),c=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},c);e.assign(i,(0,q._)`${i} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,q.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}L.validateUnion=bm});var Ha=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.validateKeywordUsage=Me.validSchemaType=Me.funcKeywordCode=Me.macroKeywordCode=void 0;var ne=R(),ut=He(),vm=_e(),km=hr();function Pm(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,c=e.macro.call(i.self,s,o,i),l=Fa(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let u=r.name("valid");t.subschema({schema:c,schemaPath:ne.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Me.macroKeywordCode=Pm;function Tm(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:c,it:l}=t;Rm(l,e);let u=!c&&e.compile?e.compile.call(l.self,o,i,l):e.validate,d=Fa(n,s,u),f=n.let("valid");t.block$data(f,p),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function p(){if(e.errors===!1)g(),e.modifying&&Ua(t),_(()=>t.error());else{let E=e.async?m():h();e.modifying&&Ua(t),_(()=>$m(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,ne._)`await `),S=>n.assign(f,!1).if((0,ne._)`${S} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,ne._)`${S}.errors`),()=>n.throw(S))),E}function h(){let E=(0,ne._)`${d}.errors`;return n.assign(E,null),g(ne.nil),E}function g(E=e.async?(0,ne._)`await `:ne.nil){let S=l.opts.passContext?ut.default.this:ut.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(f,(0,ne._)`${E}${(0,vm.callValidateCode)(t,d,S,w)}`,e.modifying)}function _(E){var S;n.if((0,ne.not)((S=e.valid)!==null&&S!==void 0?S:f),E)}}Me.funcKeywordCode=Tm;function Ua(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ne._)`${n.parentData}[${n.parentDataProperty}]`))}function $m(t,e){let{gen:r}=t;r.if((0,ne._)`Array.isArray(${e})`,()=>{r.assign(ut.default.vErrors,(0,ne._)`${ut.default.vErrors} === null ? ${e} : ${ut.default.vErrors}.concat(${e})`).assign(ut.default.errors,(0,ne._)`${ut.default.vErrors}.length`),(0,km.extendErrors)(t)},()=>t.error())}function Rm({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Fa(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,ne.stringify)(r)})}function Mm(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")}Me.validSchemaType=Mm;function Cm({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(c=>!Object.prototype.hasOwnProperty.call(t,c)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Me.validateKeywordUsage=Cm});var Va=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.extendSubschemaMode=Qe.extendSubschemaData=Qe.getSubschema=void 0;var Ce=R(),Wa=x();function Am(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let c=t.schema[e];return r===void 0?{schema:c,schemaPath:(0,Ce._)`${t.schemaPath}${(0,Ce.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,Ce._)`${t.schemaPath}${(0,Ce.getProperty)(e)}${(0,Ce.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Wa.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Qe.getSubschema=Am;function Om(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:f}=e,p=c.let("data",(0,Ce._)`${e.data}${(0,Ce.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Ce.str)`${u}${(0,Wa.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Ce._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Ce.Name?s:c.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Qe.extendSubschemaData=Om;function Im(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Qe.extendSubschemaMode=Im});var oo=b((yv,Ga)=>{"use strict";Ga.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ya=b((_v,Ka)=>{"use strict";var et=Ka.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Sn(e,n,s,t,"",t)};et.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};et.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};et.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};et.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 Sn(t,e,r,n,s,o,i,c,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,c,l,u);for(var d in n){var f=n[d];if(Array.isArray(f)){if(d in et.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 Dm=x(),Nm=oo(),zm=Ya(),Lm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jm(t,e=!0){return typeof t=="boolean"?!0:e===!0?!io(t):e?Ba(t)<=e:!1}ie.inlineRef=jm;var qm=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function io(t){for(let e in t){if(qm.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(io)||typeof r=="object"&&io(r))return!0}return!1}function Ba(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Lm.has(r)&&(typeof t[r]=="object"&&(0,Dm.eachItem)(t[r],n=>e+=Ba(n)),e===1/0))return 1/0}return e}function Ja(t,e="",r){r!==!1&&(e=Mt(e));let n=t.parse(e);return Za(t,n)}ie.getFullPath=Ja;function Za(t,e){return t.serialize(e).split("#")[0]+"#"}ie._getFullPath=Za;var Um=/#\/?$/;function Mt(t){return t?t.replace(Um,""):""}ie.normalizeId=Mt;function Fm(t,e,r){return r=Mt(r),t.resolve(e,r)}ie.resolveUrl=Fm;var Hm=/^[a-z_][-a-z0-9._]*$/i;function Wm(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Mt(t[r]||e),o={"":s},i=Ja(n,s,!1),c={},l=new Set;return zm(t,{allKeys:!0},(f,p,m,h)=>{if(h===void 0)return;let g=i+p,_=o[h];typeof f[r]=="string"&&(_=E.call(this,f[r])),S.call(this,f.$anchor),S.call(this,f.$dynamicAnchor),o[p]=_;function E(w){let C=this.opts.uriResolver.resolve;if(w=Mt(_?C(_,w):w),l.has(w))throw d(w);l.add(w);let k=this.refs[w];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?u(f,k.schema,w):w!==Mt(g)&&(w[0]==="#"?(u(f,c[w],w),c[w]=f):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!Hm.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}}),c;function u(f,p,m){if(p!==void 0&&!Nm(f,p))throw d(m)}function d(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ie.getSchemaRefs=Wm});var Er=b(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getData=tt.KeywordCxt=tt.validateFunctionCode=void 0;var rc=Aa(),Xa=gr(),co=Xs(),En=gr(),Vm=La(),Sr=Ha(),ao=Va(),v=R(),P=He(),Gm=yr(),We=x(),_r=hr();function Km(t){if(oc(t)&&(ic(t),sc(t))){Jm(t);return}nc(t,()=>(0,rc.topBoolOrEmptySchema)(t))}tt.validateFunctionCode=Km;function nc({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,v._)`${P.default.data}, ${P.default.valCxt}`,n.$async,()=>{t.code((0,v._)`"use strict"; ${Qa(r,s)}`),Bm(t,s),t.code(o)}):t.func(e,(0,v._)`${P.default.data}, ${Ym(s)}`,n.$async,()=>t.code(Qa(r,s)).code(o))}function Ym(t){return(0,v._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,v._)`, ${P.default.dynamicAnchors}={}`:v.nil}}={}`}function Bm(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,v._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,v._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,v._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,v._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,v._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,v._)`""`),t.var(P.default.parentData,(0,v._)`undefined`),t.var(P.default.parentDataProperty,(0,v._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,v._)`{}`)})}function Jm(t){let{schema:e,opts:r,gen:n}=t;nc(t,()=>{r.$comment&&e.$comment&&cc(t),th(t),n.let(P.default.vErrors,null),n.let(P.default.errors,0),r.unevaluated&&Zm(t),ac(t),sh(t)})}function Zm(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,v._)`${r}.evaluated`),e.if((0,v._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,v._)`${t.evaluated}.props`,(0,v._)`undefined`)),e.if((0,v._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,v._)`${t.evaluated}.items`,(0,v._)`undefined`))}function Qa(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,v._)`/*# sourceURL=${r} */`:v.nil}function Xm(t,e){if(oc(t)&&(ic(t),sc(t))){Qm(t,e);return}(0,rc.boolOrEmptySchema)(t,e)}function sc({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 oc(t){return typeof t.schema!="boolean"}function Qm(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&cc(t),rh(t),nh(t);let o=n.const("_errs",P.default.errors);ac(t,o),n.var(e,(0,v._)`${o} === ${P.default.errors}`)}function ic(t){(0,We.checkUnknownRules)(t),eh(t)}function ac(t,e){if(t.opts.jtd)return ec(t,[],!1,e);let r=(0,Xa.getSchemaTypes)(t.schema),n=(0,Xa.coerceAndCheckDataType)(t,r);ec(t,r,!n,e)}function eh(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,We.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function th(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,We.checkStrictMode)(t,"default is ignored in the schema root")}function rh(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Gm.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function nh(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function cc({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,v._)`${P.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,v.str)`${n}/$comment`,c=t.scopeValue("root",{ref:e.root});t.code((0,v._)`${P.default.self}.opts.$comment(${o}, ${i}, ${c}.schema)`)}}function sh(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,v._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,v._)`new ${s}(${P.default.vErrors})`)):(e.assign((0,v._)`${n}.errors`,P.default.vErrors),o.unevaluated&&oh(t),e.return((0,v._)`${P.default.errors} === 0`))}function oh({gen:t,evaluated:e,props:r,items:n}){r instanceof v.Name&&t.assign((0,v._)`${e}.props`,r),n instanceof v.Name&&t.assign((0,v._)`${e}.items`,n)}function ec(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:c,opts:l,self:u}=t,{RULES:d}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,We.schemaHasRulesButRef)(o,d))){s.block(()=>uc(t,"$ref",d.all.$ref.definition));return}l.jtd||ih(t,e),s.block(()=>{for(let p of d.rules)f(p);f(d.post)});function f(p){(0,co.shouldUseGroup)(o,p)&&(p.type?(s.if((0,En.checkDataType)(p.type,i,l.strictNumbers)),tc(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,En.reportTypeError)(t)),s.endIf()):tc(t,p),c||s.if((0,v._)`${P.default.errors} === ${n||0}`))}}function tc(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Vm.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,co.shouldUseRule)(n,o)&&uc(t,o.keyword,o.definition,e.type)})}function ih(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ah(t,e),t.opts.allowUnionTypes||ch(t,e),lh(t,t.dataTypes))}function ah(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lc(t.dataTypes,r)||lo(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),dh(t,e)}}function ch(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lo(t,"use allowUnionTypes to allow union type keyword")}function lh(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,co.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>uh(e,i))&&lo(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function uh(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lc(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function dh(t,e){let r=[];for(let n of t.dataTypes)lc(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function lo(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,We.checkStrictMode)(t,e,t.opts.strictTypes)}var wn=class{constructor(e,r,n){if((0,Sr.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,We.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",dc(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Sr.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",P.default.errors))}result(e,r,n){this.failResult((0,v.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,v.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,v._)`${r} !== undefined && (${(0,v.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?_r.reportExtraError:_r.reportError)(this,this.def.error,r)}$dataError(){(0,_r.reportError)(this,this.def.$dataError||_r.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,_r.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=v.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=v.nil,r=v.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,v.or)((0,v._)`${s} === undefined`,r)),e!==v.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==v.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,v.or)(i(),c());function i(){if(n.length){if(!(r instanceof v.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,v._)`${(0,En.checkDataTypes)(l,r,o.opts.strictNumbers,En.DataType.Wrong)}`}return v.nil}function c(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,v._)`!${l}(${r})`}return v.nil}}subschema(e,r){let n=(0,ao.getSubschema)(this.it,e);(0,ao.extendSubschemaData)(n,this.it,e),(0,ao.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Xm(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=We.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=We.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,v.Name)),!0}};tt.KeywordCxt=wn;function uc(t,e,r,n){let s=new wn(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Sr.funcKeywordCode)(s,r):"macro"in r?(0,Sr.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Sr.funcKeywordCode)(s,r)}var fh=/^\/(?:[^~]|~0|~1)*$/,ph=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dc(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!fh.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=P.default.rootData}else{let u=ph.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(s=u[2],s==="#"){if(d>=e)throw new Error(l("property/index",d));return n[e-d]}if(d>e)throw new Error(l("data",d));if(o=r[e-d],!s)return o}let i=o,c=s.split("/");for(let u of c)u&&(o=(0,v._)`${o}${(0,v.getProperty)((0,We.unescapeJsonPointer)(u))}`,i=(0,v._)`${i} && ${o}`);return i;function l(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}tt.getData=dc});var bn=b(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});var uo=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};fo.default=uo});var wr=b(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});var po=yr(),mo=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,po.resolveUrl)(e,r,n),this.missingSchema=(0,po.normalizeId)((0,po.getFullPath)(e,this.missingRef))}};ho.default=mo});var kn=b(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.resolveSchema=Se.getCompilingSchema=Se.resolveRef=Se.compileSchema=Se.SchemaEnv=void 0;var ke=R(),mh=bn(),dt=He(),Pe=yr(),fc=x(),hh=Er(),Ct=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,Pe.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Se.SchemaEnv=Ct;function yo(t){let e=pc.call(this,t);if(e)return e;let r=(0,Pe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ke.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),c;t.$async&&(c=i.scopeValue("Error",{ref:mh.default,code:(0,ke._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:dt.default.data,parentData:dt.default.parentData,parentDataProperty:dt.default.parentDataProperty,dataNames:[dt.default.data],dataPathArr:[ke.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ke.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ke.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ke._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,hh.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();d=`${i.scopeRefs(dt.default.scope)}return ${f}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${dt.default.self}`,`${dt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(l,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:g}=u;m.evaluated={props:h instanceof ke.Name?void 0:h,items:g instanceof ke.Name?void 0:g,dynamicProps:h instanceof ke.Name,dynamicItems:g instanceof ke.Name},m.source&&(m.source.evaluated=(0,ke.stringify)(m.evaluated))}return t.validate=m,t}catch(f){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),f}finally{this._compilations.delete(t)}}Se.compileSchema=yo;function gh(t,e,r){var n;r=(0,Pe.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=Sh.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;i&&(o=new Ct({schema:i,schemaId:c,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=yh.call(this,o)}Se.resolveRef=gh;function yh(t){return(0,Pe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:yo.call(this,t)}function pc(t){for(let e of this._compilations)if(_h(e,t))return e}Se.getCompilingSchema=pc;function _h(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Sh(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||vn.call(this,t,e)}function vn(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pe._getFullPath)(this.opts.uriResolver,r),s=(0,Pe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return go.call(this,r,t);let o=(0,Pe.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let c=vn.call(this,t,i);return typeof c?.schema!="object"?void 0:go.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||yo.call(this,i),o===(0,Pe.normalizeId)(e)){let{schema:c}=i,{schemaId:l}=this.opts,u=c[l];return u&&(s=(0,Pe.resolveUrl)(this.opts.uriResolver,s,u)),new Ct({schema:c,schemaId:l,root:t,baseId:s})}return go.call(this,r,i)}}Se.resolveSchema=vn;var Eh=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function go(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let c of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,fc.unescapeFragment)(c)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!Eh.has(c)&&u&&(e=(0,Pe.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,fc.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Pe.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=vn.call(this,n,c)}let{schemaId:i}=this.opts;if(o=o||new Ct({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var mc=b((kv,wh)=>{wh.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 So=b((Pv,_c)=>{"use strict";var bh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),gc=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 _o(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 vh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hc(t){return t.length=0,!0}function kh(t,e,r){if(t.length){let n=_o(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Ph(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,c=kh;for(let l=0;l7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!c(s,n,r))break;c=hc}else{s.push(u);continue}}return s.length&&(c===hc?r.zone=s.join(""):i?n.push(s.join("")):n.push(_o(s))),r.address=n.join(""),r}function yc(t){if(Th(t,":")<2)return{host:t,isIPV6:!1};let e=Ph(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 Th(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:Ch}=So(),Ah=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Oh=["http","https","ws","wss","urn","urn:uuid"];function Ih(t){return Oh.indexOf(t)!==-1}function Eo(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 Sc(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ec(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 xh(t){return t.secure=Eo(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Dh(t){if((t.port===(Eo(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 Nh(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Ah);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=wo(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function zh(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=wo(s);o&&(t=o.serialize(t,e));let i=t,c=t.nss;return i.path=`${n||e.nid}:${c}`,e.skipEscape=!0,i}function Lh(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Ch(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function jh(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var wc={scheme:"http",domainHost:!0,parse:Sc,serialize:Ec},qh={scheme:"https",domainHost:wc.domainHost,parse:Sc,serialize:Ec},Pn={scheme:"ws",domainHost:!0,parse:xh,serialize:Dh},Uh={scheme:"wss",domainHost:Pn.domainHost,parse:Pn.parse,serialize:Pn.serialize},Fh={scheme:"urn",parse:Nh,serialize:zh,skipNormalize:!0},Hh={scheme:"urn:uuid",parse:Lh,serialize:jh,skipNormalize:!0},Tn={http:wc,https:qh,ws:Pn,wss:Uh,urn:Fh,"urn:uuid":Hh};Object.setPrototypeOf(Tn,null);function wo(t){return t&&(Tn[t]||Tn[t.toLowerCase()])||void 0}bc.exports={wsIsSecure:Eo,SCHEMES:Tn,isValidSchemeName:Ih,getSchemeHandler:wo}});var Tc=b(($v,Rn)=>{"use strict";var{normalizeIPv6:Wh,removeDotSegments:br,recomposeAuthority:Vh,normalizeComponentEncoding:$n,isIPv4:Gh,nonSimpleDomain:Kh}=So(),{SCHEMES:Yh,getSchemeHandler:kc}=vc();function Bh(t,e){return typeof t=="string"?t=Ae(Ve(t,e),e):typeof t=="object"&&(t=Ve(Ae(t,e),e)),t}function Jh(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Pc(Ve(t,n),Ve(e,n),n,!0);return n.skipEscape=!0,Ae(s,n)}function Pc(t,e,r,n){let s={};return n||(t=Ve(Ae(t,r),r),e=Ve(Ae(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=br(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=br(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=br(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function Zh(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ae($n(Ve(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ae($n(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ae($n(Ve(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ae($n(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ae(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=kc(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=Vh(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(c=br(c)),i===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),s.push(c)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var Xh=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ve(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(Xh);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(Gh(n.host)===!1){let l=Wh(n.host);n.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=kc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&Kh(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!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 bo={SCHEMES:Yh,normalize:Bh,resolve:Jh,resolveComponent:Pc,equal:Zh,serialize:Ae,parse:Ve};Rn.exports=bo;Rn.exports.default=bo;Rn.exports.fastUri=bo});var Rc=b(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});var $c=Tc();$c.code='require("ajv/dist/runtime/uri").default';vo.default=$c});var Nc=b(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.CodeGen=B.Name=B.nil=B.stringify=B.str=B._=B.KeywordCxt=void 0;var Qh=Er();Object.defineProperty(B,"KeywordCxt",{enumerable:!0,get:function(){return Qh.KeywordCxt}});var At=R();Object.defineProperty(B,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(B,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(B,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(B,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(B,"Name",{enumerable:!0,get:function(){return At.Name}});Object.defineProperty(B,"CodeGen",{enumerable:!0,get:function(){return At.CodeGen}});var eg=bn(),Ic=wr(),tg=Zs(),vr=kn(),rg=R(),kr=yr(),Mn=gr(),Po=x(),Mc=mc(),ng=Rc(),xc=(t,e)=>new RegExp(t,e);xc.code="new RegExp";var sg=["removeAdditional","useDefaults","coerceTypes"],og=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),ig={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."},ag={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Cc=200;function cg(t){var e,r,n,s,o,i,c,l,u,d,f,p,m,h,g,_,E,S,w,C,k,le,fe,Gt,yt;let W=t.strict,Ge=(e=t.code)===null||e===void 0?void 0:e.optimize,be=Ge===!0||Ge===void 0?1:Ge||0,Kt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xc,nd=(s=t.uriResolver)!==null&&s!==void 0?s:ng.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:W)!==null&&i!==void 0?i:!0,strictNumbers:(l=(c=t.strictNumbers)!==null&&c!==void 0?c:W)!==null&&l!==void 0?l:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:W)!==null&&d!==void 0?d:"log",strictTuples:(p=(f=t.strictTuples)!==null&&f!==void 0?f:W)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:W)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:be,regExp:Kt}:{optimize:be,regExp:Kt},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:Cc,loopEnum:(_=t.loopEnum)!==null&&_!==void 0?_:Cc,meta:(E=t.meta)!==null&&E!==void 0?E:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(C=t.schemaId)!==null&&C!==void 0?C:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(le=t.validateSchema)!==null&&le!==void 0?le:!0,validateFormats:(fe=t.validateFormats)!==null&&fe!==void 0?fe:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(yt=t.int32range)!==null&&yt!==void 0?yt:!0,uriResolver:nd}}var Pr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...cg(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new rg.ValueScope({scope:{},prefixes:og,es5:r,lines:n}),this.logger=mg(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tg.getRules)(),Ac.call(this,ig,e,"NOT SUPPORTED"),Ac.call(this,ag,e,"DEPRECATED","warn"),this._metaOpts=fg.call(this),e.formats&&ug.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&dg.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lg.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Mc;n==="id"&&(s={...Mc},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(d,f){await o.call(this,d.$schema);let p=this._addSchema(d,f);return p.validate||i.call(this,p)}async function o(d){d&&!this.getSchema(d)&&await s.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(f){if(!(f instanceof Ic.default))throw f;return c.call(this,f),await l.call(this,f.missingSchema),i.call(this,d)}}function c({missingSchema:d,missingRef:f}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${f} cannot be resolved`)}async function l(d){let f=await u.call(this,d);this.refs[d]||await o.call(this,f.$schema),this.refs[d]||this.addSchema(f,d,r)}async function u(d){let f=this._loading[d];if(f)return f;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,kr.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=Oc.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new vr.SchemaEnv({schema:{},schemaId:n});if(r=vr.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Oc.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,kr.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(gg.call(this,n,r),!r)return(0,Po.eachItem)(n,o=>ko.call(this,o)),this;_g.call(this,r);let s={...r,type:(0,Mn.getJSONTypes)(r.type),schemaType:(0,Mn.getJSONTypes)(r.schemaType)};return(0,Po.eachItem)(n,s.type.length===0?o=>ko.call(this,o,s):o=>s.type.forEach(i=>ko.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let c of o)i=i[c];for(let c in n){let l=n[c];if(typeof l!="object")continue;let{$data:u}=l.definition,d=i[c];u&&d&&(i[c]=Dc(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:c}=this.opts;if(typeof e=="object")i=e[c];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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,kr.normalizeId)(i||n);let u=kr.getSchemaRefs.call(this,e,n);return l=new vr.SchemaEnv({schema:e,schemaId:c,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),s&&this.validateSchema(e,!0),l}_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):vr.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{vr.compileSchema.call(this,e)}finally{this.opts=r}}};Pr.ValidationError=eg.default;Pr.MissingRefError=Ic.default;B.default=Pr;function Ac(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Oc(t){return t=(0,kr.normalizeId)(t),this.schemas[t]||this.refs[t]}function lg(){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 ug(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function dg(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 fg(){let t={...this.opts};for(let e of sg)delete t[e];return t}var pg={log(){},warn(){},error(){}};function mg(t){if(t===!1)return pg;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 hg=/^[a-z_$][a-z0-9_$:-]*$/i;function gg(t,e){let{RULES:r}=this;if((0,Po.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hg.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 ko(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let c={keyword:t,definition:{...e,type:(0,Mn.getJSONTypes)(e.type),schemaType:(0,Mn.getJSONTypes)(e.schemaType)}};e.before?yg.call(this,i,c,e.before):i.rules.push(c),o.all[t]=c,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function yg(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function _g(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Dc(e)),t.validateSchema=this.compile(e,!0))}var Sg={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Dc(t){return{anyOf:[t,Sg]}}});var zc=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Eg={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};To.default=Eg});var Uc=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.callRef=ft.getValidate=void 0;var wg=wr(),Lc=_e(),ae=R(),Ot=He(),jc=kn(),Cn=x(),bg={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:c,self:l}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return f();let d=jc.resolveRef.call(l,u,s,r);if(d===void 0)throw new wg.default(n.opts.uriResolver,s,r);if(d instanceof jc.SchemaEnv)return p(d);return m(d);function f(){if(o===u)return An(t,i,o,o.$async);let h=e.scopeValue("root",{ref:u});return An(t,(0,ae._)`${h}.validate`,u,u.$async)}function p(h){let g=qc(t,h);An(t,g,h,h.$async)}function m(h){let g=e.scopeValue("schema",c.code.source===!0?{ref:h,code:(0,ae.stringify)(h)}:{ref:h}),_=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:ae.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(E),t.ok(_)}}};function qc(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ae._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ft.getValidate=qc;function An(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:c,opts:l}=o,u=l.passContext?Ot.default.this:ae.nil;n?d():f();function d(){if(!c.$async)throw new Error("async schema referenced by sync schema");let h=s.let("valid");s.try(()=>{s.code((0,ae._)`await ${(0,Lc.callValidateCode)(t,e,u)}`),m(e),i||s.assign(h,!0)},g=>{s.if((0,ae._)`!(${g} instanceof ${o.ValidationError})`,()=>s.throw(g)),p(g),i||s.assign(h,!1)}),t.ok(h)}function f(){t.result((0,Lc.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(h){let g=(0,ae._)`${h}.errors`;s.assign(Ot.default.vErrors,(0,ae._)`${Ot.default.vErrors} === null ? ${g} : ${Ot.default.vErrors}.concat(${g})`),s.assign(Ot.default.errors,(0,ae._)`${Ot.default.vErrors}.length`)}function m(h){var g;if(!o.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(o.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(o.props=Cn.mergeEvaluated.props(s,_.props,o.props));else{let E=s.var("props",(0,ae._)`${h}.evaluated.props`);o.props=Cn.mergeEvaluated.props(s,E,o.props,ae.Name)}if(o.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(o.items=Cn.mergeEvaluated.items(s,_.items,o.items));else{let E=s.var("items",(0,ae._)`${h}.evaluated.items`);o.items=Cn.mergeEvaluated.items(s,E,o.items,ae.Name)}}}ft.callRef=An;ft.default=bg});var Fc=b($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var vg=zc(),kg=Uc(),Pg=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vg.default,kg.default];$o.default=Pg});var Hc=b(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});var On=R(),rt=On.operators,In={maximum:{okStr:"<=",ok:rt.LTE,fail:rt.GT},minimum:{okStr:">=",ok:rt.GTE,fail:rt.LT},exclusiveMaximum:{okStr:"<",ok:rt.LT,fail:rt.GTE},exclusiveMinimum:{okStr:">",ok:rt.GT,fail:rt.LTE}},Tg={message:({keyword:t,schemaCode:e})=>(0,On.str)`must be ${In[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,On._)`{comparison: ${In[t].okStr}, limit: ${e}}`},$g={keyword:Object.keys(In),type:"number",schemaType:"number",$data:!0,error:Tg,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,On._)`${r} ${In[e].fail} ${n} || isNaN(${r})`)}};Ro.default=$g});var Wc=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var Tr=R(),Rg={message:({schemaCode:t})=>(0,Tr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Tr._)`{multipleOf: ${t}}`},Mg={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Rg,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),c=o?(0,Tr._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Tr._)`${i} !== parseInt(${i})`;t.fail$data((0,Tr._)`(${n} === 0 || (${i} = ${r}/${n}, ${c}))`)}};Mo.default=Mg});var Gc=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});function Vc(t){let e=t.length,r=0,n=0,s;for(;n=55296&&s<=56319&&n{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});var pt=R(),Cg=x(),Ag=Gc(),Og={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,pt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,pt._)`{limit: ${t}}`},Ig={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Og,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?pt.operators.GT:pt.operators.LT,i=s.opts.unicode===!1?(0,pt._)`${r}.length`:(0,pt._)`${(0,Cg.useFunc)(t.gen,Ag.default)}(${r})`;t.fail$data((0,pt._)`${i} ${o} ${n}`)}};Ao.default=Ig});var Yc=b(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var xg=_e(),Dg=x(),It=R(),Ng={message:({schemaCode:t})=>(0,It.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,It._)`{pattern: ${t}}`},zg={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ng,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,c=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,It._)`new RegExp`:(0,Dg.useFunc)(e,l),d=e.let("valid");e.try(()=>e.assign(d,(0,It._)`${u}(${o}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,It._)`!${d}`)}else{let l=(0,xg.usePattern)(t,s);t.fail$data((0,It._)`!${l}.test(${r})`)}}};Oo.default=zg});var Bc=b(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var $r=R(),Lg={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},jg={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Lg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?$r.operators.GT:$r.operators.LT;t.fail$data((0,$r._)`Object.keys(${r}).length ${s} ${n}`)}};Io.default=jg});var Jc=b(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});var Rr=_e(),Mr=R(),qg=x(),Ug={message:({params:{missingProperty:t}})=>(0,Mr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mr._)`{missingProperty: ${t}}`},Fg={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Ug,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:c}=i;if(!o&&r.length===0)return;let l=r.length>=c.loopRequired;if(i.allErrors?u():d(),c.strictRequired){let m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(m?.[g]===void 0&&!h.has(g)){let _=i.schemaEnv.baseId+i.errSchemaPath,E=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,qg.checkStrictMode)(i,E,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(Mr.nil,f);else for(let m of r)(0,Rr.checkReportMissingProp)(t,m)}function d(){let m=e.let("missing");if(l||o){let h=e.let("valid",!0);t.block$data(h,()=>p(m,h)),t.ok(h)}else e.if((0,Rr.checkMissingProp)(t,r,m)),(0,Rr.reportMissingProp)(t,m),e.else()}function f(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,Rr.noPropertyInData)(e,s,m,c.ownProperties),()=>t.error())})}function p(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,Rr.propertyInData)(e,s,m,c.ownProperties)),e.if((0,Mr.not)(h),()=>{t.error(),e.break()})},Mr.nil)}}};xo.default=Fg});var Zc=b(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var Cr=R(),Hg={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Cr.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Cr._)`{limit: ${t}}`},Wg={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Hg,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Cr.operators.GT:Cr.operators.LT;t.fail$data((0,Cr._)`${r}.length ${s} ${n}`)}};Do.default=Wg});var xn=b(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var Xc=oo();Xc.code='require("ajv/dist/runtime/equal").default';No.default=Xc});var Qc=b(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var zo=gr(),J=R(),Vg=x(),Gg=xn(),Kg={message:({params:{i:t,j:e}})=>(0,J.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,J._)`{i: ${t}, j: ${e}}`},Yg={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Kg,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:c}=t;if(!n&&!s)return;let l=e.let("valid"),u=o.items?(0,zo.getSchemaTypes)(o.items):[];t.block$data(l,d,(0,J._)`${i} === false`),t.ok(l);function d(){let h=e.let("i",(0,J._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(l,!0),e.if((0,J._)`${h} > 1`,()=>(f()?p:m)(h,g))}function f(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,g){let _=e.name("item"),E=(0,zo.checkDataTypes)(u,_,c.opts.strictNumbers,zo.DataType.Wrong),S=e.const("indices",(0,J._)`{}`);e.for((0,J._)`;${h}--;`,()=>{e.let(_,(0,J._)`${r}[${h}]`),e.if(E,(0,J._)`continue`),u.length>1&&e.if((0,J._)`typeof ${_} == "string"`,(0,J._)`${_} += "_"`),e.if((0,J._)`typeof ${S}[${_}] == "number"`,()=>{e.assign(g,(0,J._)`${S}[${_}]`),t.error(),e.assign(l,!1).break()}).code((0,J._)`${S}[${_}] = ${h}`)})}function m(h,g){let _=(0,Vg.useFunc)(e,Gg.default),E=e.name("outer");e.label(E).for((0,J._)`;${h}--;`,()=>e.for((0,J._)`${g} = ${h}; ${g}--;`,()=>e.if((0,J._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(l,!1).break(E)})))}}};Lo.default=Yg});var el=b(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});var jo=R(),Bg=x(),Jg=xn(),Zg={message:"must be equal to constant",params:({schemaCode:t})=>(0,jo._)`{allowedValue: ${t}}`},Xg={keyword:"const",$data:!0,error:Zg,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,jo._)`!${(0,Bg.useFunc)(e,Jg.default)}(${r}, ${s})`):t.fail((0,jo._)`${o} !== ${r}`)}};qo.default=Xg});var tl=b(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var Ar=R(),Qg=x(),ey=xn(),ty={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ar._)`{allowedValues: ${t}}`},ry={keyword:"enum",schemaType:"array",$data:!0,error:ty,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let c=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,Qg.useFunc)(e,ey.default)),d;if(c||n)d=e.let("valid"),t.block$data(d,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let m=e.const("vSchema",o);d=(0,Ar.or)(...s.map((h,g)=>p(m,g)))}t.pass(d);function f(){e.assign(d,!1),e.forOf("v",o,m=>e.if((0,Ar._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,h){let g=s[h];return typeof g=="object"&&g!==null?(0,Ar._)`${u()}(${r}, ${m}[${h}])`:(0,Ar._)`${r} === ${g}`}}};Uo.default=ry});var rl=b(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var ny=Hc(),sy=Wc(),oy=Kc(),iy=Yc(),ay=Bc(),cy=Jc(),ly=Zc(),uy=Qc(),dy=el(),fy=tl(),py=[ny.default,sy.default,oy.default,iy.default,ay.default,cy.default,ly.default,uy.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dy.default,fy.default];Fo.default=py});var Wo=b(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateAdditionalItems=void 0;var mt=R(),Ho=x(),my={message:({params:{len:t}})=>(0,mt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mt._)`{limit: ${t}}`},hy={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:my,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ho.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}nl(t,n)}};function nl(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let c=r.const("len",(0,mt._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,mt._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ho.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,mt._)`${c} <= ${e.length}`);r.if((0,mt.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,c,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Ho.Type.Num},u),i.allErrors||r.if((0,mt.not)(u),()=>r.break())})}}Or.validateAdditionalItems=nl;Or.default=hy});var Vo=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var sl=R(),Dn=x(),gy=_e(),yy={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ol(t,"additionalItems",e);r.items=!0,!(0,Dn.alwaysValidSchema)(r,e)&&t.ok((0,gy.validateArray)(t))}};function ol(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:c}=t;d(s),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Dn.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),u=n.const("len",(0,sl._)`${o}.length`);r.forEach((f,p)=>{(0,Dn.alwaysValidSchema)(c,f)||(n.if((0,sl._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},l)),t.ok(l))});function d(f){let{opts:p,errSchemaPath:m}=c,h=r.length,g=h===f.minItems&&(h===f.maxItems||f[e]===!1);if(p.strictTuples&&!g){let _=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Dn.checkStrictMode)(c,_,p.strictTuples)}}}Ir.validateTuple=ol;Ir.default=yy});var il=b(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var _y=Vo(),Sy={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,_y.validateTuple)(t,"items")};Go.default=Sy});var cl=b(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var al=R(),Ey=x(),wy=_e(),by=Wo(),vy={message:({params:{len:t}})=>(0,al.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,al._)`{limit: ${t}}`},ky={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:vy,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Ey.alwaysValidSchema)(n,e)&&(s?(0,by.validateAdditionalItems)(t,s):t.ok((0,wy.validateArray)(t)))}};Ko.default=ky});var ll=b(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Ee=R(),Nn=x(),Py={message:({params:{min:t,max:e}})=>e===void 0?(0,Ee.str)`must contain at least ${t} valid item(s)`:(0,Ee.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ee._)`{minContains: ${t}}`:(0,Ee._)`{minContains: ${t}, maxContains: ${e}}`},Ty={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Py,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,c,{minContains:l,maxContains:u}=n;o.opts.next?(i=l===void 0?1:l,c=u):i=1;let d=e.const("len",(0,Ee._)`${s}.length`);if(t.setParams({min:i,max:c}),c===void 0&&i===0){(0,Nn.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,Nn.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Nn.alwaysValidSchema)(o,r)){let g=(0,Ee._)`${d} >= ${i}`;c!==void 0&&(g=(0,Ee._)`${g} && ${d} <= ${c}`),t.pass(g);return}o.items=!0;let f=e.name("valid");c===void 0&&i===1?m(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),c!==void 0&&e.if((0,Ee._)`${s}.length > 0`,p)):(e.let(f,!1),p()),t.result(f,()=>t.reset());function p(){let g=e.name("_valid"),_=e.let("count",0);m(g,()=>e.if(g,()=>h(_)))}function m(g,_){e.forRange("i",0,d,E=>{t.subschema({keyword:"contains",dataProp:E,dataPropType:Nn.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,Ee._)`${g}++`),c===void 0?e.if((0,Ee._)`${g} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,Ee._)`${g} > ${c}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,Ee._)`${g} >= ${i}`,()=>e.assign(f,!0)))}}};Yo.default=Ty});var fl=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateSchemaDeps=Oe.validatePropertyDeps=Oe.error=void 0;var Bo=R(),$y=x(),xr=_e();Oe.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Bo.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Bo._)`{property: ${t}, missingProperty: ${n}, depsCount: ${e}, deps: ${r}}`};var Ry={keyword:"dependencies",type:"object",schemaType:"object",error:Oe.error,code(t){let[e,r]=My(t);ul(t,e),dl(t,r)}};function My({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function ul(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let c=e[i];if(c.length===0)continue;let l=(0,xr.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:c.length,deps:c.join(", ")}),s.allErrors?r.if(l,()=>{for(let u of c)(0,xr.checkReportMissingProp)(t,u)}):(r.if((0,Bo._)`${l} && (${(0,xr.checkMissingProp)(t,c,o)})`),(0,xr.reportMissingProp)(t,o),r.else())}}Oe.validatePropertyDeps=ul;function dl(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let c in e)(0,$y.alwaysValidSchema)(o,e[c])||(r.if((0,xr.propertyInData)(r,n,c,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:c},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}Oe.validateSchemaDeps=dl;Oe.default=Ry});var ml=b(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var pl=R(),Cy=x(),Ay={message:"property name must be valid",params:({params:t})=>(0,pl._)`{propertyName: ${t.propertyName}}`},Oy={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ay,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Cy.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,pl.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Jo.default=Oy});var Xo=b(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});var zn=_e(),Te=R(),Iy=He(),Ln=x(),xy={message:"must NOT have additional properties",params:({params:t})=>(0,Te._)`{additionalProperty: ${t.additionalProperty}}`},Dy={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:xy,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:c,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Ln.alwaysValidSchema)(i,r))return;let u=(0,zn.allSchemaProperties)(n.properties),d=(0,zn.allSchemaProperties)(n.patternProperties);f(),t.ok((0,Te._)`${o} === ${Iy.default.errors}`);function f(){e.forIn("key",s,_=>{!u.length&&!d.length?h(_):e.if(p(_),()=>h(_))})}function p(_){let E;if(u.length>8){let S=(0,Ln.schemaRefOrVal)(i,n.properties,"properties");E=(0,zn.isOwnProperty)(e,S,_)}else u.length?E=(0,Te.or)(...u.map(S=>(0,Te._)`${_} === ${S}`)):E=Te.nil;return d.length&&(E=(0,Te.or)(E,...d.map(S=>(0,Te._)`${(0,zn.usePattern)(t,S)}.test(${_})`))),(0,Te.not)(E)}function m(_){e.code((0,Te._)`delete ${s}[${_}]`)}function h(_){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){m(_);return}if(r===!1){t.setParams({additionalProperty:_}),t.error(),c||e.break();return}if(typeof r=="object"&&!(0,Ln.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?(g(_,E,!1),e.if((0,Te.not)(E),()=>{t.reset(),m(_)})):(g(_,E),c||e.if((0,Te.not)(E),()=>e.break()))}}function g(_,E,S){let w={keyword:"additionalProperties",dataProp:_,dataPropType:Ln.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}}};Zo.default=Dy});var yl=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var Ny=Er(),hl=_e(),Qo=x(),gl=Xo(),zy={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&gl.default.code(new Ny.KeywordCxt(o,gl.default,"additionalProperties"));let i=(0,hl.allSchemaProperties)(r);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Qo.mergeEvaluated.props(e,(0,Qo.toHash)(i),o.props));let c=i.filter(f=>!(0,Qo.alwaysValidSchema)(o,r[f]));if(c.length===0)return;let l=e.name("valid");for(let f of c)u(f)?d(f):(e.if((0,hl.propertyInData)(e,s,f,o.opts.ownProperties)),d(f),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return o.opts.useDefaults&&!o.compositeRule&&r[f].default!==void 0}function d(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};ei.default=zy});var wl=b(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var _l=_e(),jn=R(),Sl=x(),El=x(),Ly={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,c=(0,_l.allSchemaProperties)(r),l=c.filter(g=>(0,Sl.alwaysValidSchema)(o,r[g]));if(c.length===0||l.length===c.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof jn.Name)&&(o.props=(0,El.evaluatedPropsToName)(e,o.props));let{props:f}=o;p();function p(){for(let g of c)u&&m(g),o.allErrors?h(g):(e.var(d,!0),h(g),e.if(d))}function m(g){for(let _ in u)new RegExp(g).test(_)&&(0,Sl.checkStrictMode)(o,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,_=>{e.if((0,jn._)`${(0,_l.usePattern)(t,g)}.test(${_})`,()=>{let E=l.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:El.Type.Str},d),o.opts.unevaluated&&f!==!0?e.assign((0,jn._)`${f}[${_}]`,!0):!E&&!o.allErrors&&e.if((0,jn.not)(d),()=>e.break())})})}}};ti.default=Ly});var bl=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var jy=x(),qy={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,jy.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ri.default=qy});var vl=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var Uy=_e(),Fy={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Uy.validateUnion,error:{message:"must match a schema in anyOf"}};ni.default=Fy});var kl=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var qn=R(),Hy=x(),Wy={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,qn._)`{passingSchemas: ${t.passing}}`},Vy={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Wy,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),c=e.let("passing",null),l=e.name("_valid");t.setParams({passing:c}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((d,f)=>{let p;(0,Hy.alwaysValidSchema)(s,d)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,qn._)`${l} && ${i}`).assign(i,!1).assign(c,(0,qn._)`[${c}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(c,f),p&&t.mergeEvaluated(p,qn.Name)})})}}};si.default=Vy});var Pl=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var Gy=x(),Ky={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,Gy.alwaysValidSchema)(n,o))return;let c=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(c)})}};oi.default=Ky});var Rl=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var Un=R(),$l=x(),Yy={message:({params:t})=>(0,Un.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Un._)`{failingKeyword: ${t.ifClause}}`},By={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Yy,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,$l.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Tl(n,"then"),o=Tl(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),c=e.name("_valid");if(l(),t.reset(),s&&o){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(c,u("then",d),u("else",d))}else s?e.if(c,u("then")):e.if((0,Un.not)(c),u("else"));t.pass(i,()=>t.error(!0));function l(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);t.mergeEvaluated(d)}function u(d,f){return()=>{let p=t.subschema({keyword:d},c);e.assign(i,c),t.mergeValidEvaluated(p,i),f?e.assign(f,(0,Un._)`${d}`):t.setParams({ifClause:d})}}}};function Tl(t,e){let r=t.schema[e];return r!==void 0&&!(0,$l.alwaysValidSchema)(t,r)}ii.default=By});var Ml=b(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var Jy=x(),Zy={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Jy.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ai.default=Zy});var Cl=b(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});var Xy=Wo(),Qy=il(),e_=Vo(),t_=cl(),r_=ll(),n_=fl(),s_=ml(),o_=Xo(),i_=yl(),a_=wl(),c_=bl(),l_=vl(),u_=kl(),d_=Pl(),f_=Rl(),p_=Ml();function m_(t=!1){let e=[c_.default,l_.default,u_.default,d_.default,f_.default,p_.default,s_.default,o_.default,n_.default,i_.default,a_.default];return t?e.push(Qy.default,t_.default):e.push(Xy.default,e_.default),e.push(r_.default),e}ci.default=m_});var Al=b(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});var H=R(),h_={message:({schemaCode:t})=>(0,H.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,H._)`{format: ${t}}`},g_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:h_,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:c}=t,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;s?p():m();function p(){let h=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),g=r.const("fDef",(0,H._)`${h}[${i}]`),_=r.let("fType"),E=r.let("format");r.if((0,H._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,H._)`${g}.type || "string"`).assign(E,(0,H._)`${g}.validate`),()=>r.assign(_,(0,H._)`"string"`).assign(E,g)),t.fail$data((0,H.or)(S(),w()));function S(){return l.strictSchema===!1?H.nil:(0,H._)`${i} && !${E}`}function w(){let C=d.$async?(0,H._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,H._)`${E}(${n})`,k=(0,H._)`(typeof ${E} == "function" ? ${C} : ${E}.test(${n}))`;return(0,H._)`${E} && ${E} !== true && ${_} === ${e} && !${k}`}}function m(){let h=f.formats[o];if(!h){S();return}if(h===!0)return;let[g,_,E]=w(h);g===e&&t.pass(C());function S(){if(l.strictSchema===!1){f.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function w(k){let le=k instanceof RegExp?(0,H.regexpCode)(k):l.code.formats?(0,H._)`${l.code.formats}${(0,H.getProperty)(o)}`:void 0,fe=r.scopeValue("formats",{key:o,ref:k,code:le});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,H._)`${fe}.validate`]:["string",k,fe]}function C(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,H._)`await ${E}(${n})`}return typeof _=="function"?(0,H._)`${E}(${n})`:(0,H._)`${E}.test(${n})`}}}};li.default=g_});var Ol=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var y_=Al(),__=[y_.default];ui.default=__});var Il=b(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.contentVocabulary=xt.metadataVocabulary=void 0;xt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Dl=b(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var S_=Fc(),E_=rl(),w_=Cl(),b_=Ol(),xl=Il(),v_=[S_.default,E_.default,(0,w_.default)(),b_.default,xl.metadataVocabulary,xl.contentVocabulary];di.default=v_});var zl=b(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.DiscrError=void 0;var Nl;(function(t){t.Tag="tag",t.Mapping="mapping"})(Nl||(Fn.DiscrError=Nl={}))});var jl=b(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});var Dt=R(),fi=zl(),Ll=kn(),k_=wr(),P_=x(),T_={message:({params:{discrError:t,tagName:e}})=>t===fi.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Dt._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},$_={keyword:"discriminator",type:"object",schemaType:"object",error:T_,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="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 l=e.let("valid",!1),u=e.const("tag",(0,Dt._)`${r}${(0,Dt.getProperty)(c)}`);e.if((0,Dt._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:fi.DiscrError.Tag,tag:u,tagName:c})),t.ok(l);function d(){let m=p();e.if(!1);for(let h in m)e.elseIf((0,Dt._)`${u} === ${h}`),e.assign(l,f(m[h]));e.else(),t.error(!1,{discrError:fi.DiscrError.Mapping,tag:u,tagName:c}),e.endIf()}function f(m){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(g,Dt.Name),h}function p(){var m;let h={},g=E(s),_=!0;for(let C=0;C{R_.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 hi=b((U,mi)=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.MissingRefError=U.ValidationError=U.CodeGen=U.Name=U.nil=U.stringify=U.str=U._=U.KeywordCxt=U.Ajv=void 0;var M_=Nc(),C_=Dl(),A_=jl(),Ul=ql(),O_=["/properties"],Hn="http://json-schema.org/draft-07/schema",Nt=class extends M_.default{_addVocabularies(){super._addVocabularies(),C_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(A_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ul,O_):Ul;this.addMetaSchema(e,Hn,!1),this.refs["http://json-schema.org/schema"]=Hn}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hn)?Hn:void 0)}};U.Ajv=Nt;mi.exports=U=Nt;mi.exports.Ajv=Nt;Object.defineProperty(U,"__esModule",{value:!0});U.default=Nt;var I_=Er();Object.defineProperty(U,"KeywordCxt",{enumerable:!0,get:function(){return I_.KeywordCxt}});var zt=R();Object.defineProperty(U,"_",{enumerable:!0,get:function(){return zt._}});Object.defineProperty(U,"str",{enumerable:!0,get:function(){return zt.str}});Object.defineProperty(U,"stringify",{enumerable:!0,get:function(){return zt.stringify}});Object.defineProperty(U,"nil",{enumerable:!0,get:function(){return zt.nil}});Object.defineProperty(U,"Name",{enumerable:!0,get:function(){return zt.Name}});Object.defineProperty(U,"CodeGen",{enumerable:!0,get:function(){return zt.CodeGen}});var x_=bn();Object.defineProperty(U,"ValidationError",{enumerable:!0,get:function(){return x_.default}});var D_=wr();Object.defineProperty(U,"MissingRefError",{enumerable:!0,get:function(){return D_.default}})});var Bl=b(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.formatNames=xe.fastFormats=xe.fullFormats=void 0;function Ie(t,e){return{validate:t,compare:e}}xe.fullFormats={date:Ie(Vl,Si),time:Ie(yi(!0),Ei),"date-time":Ie(Fl(!0),Kl),"iso-time":Ie(yi(),Gl),"iso-date-time":Ie(Fl(),Yl),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:U_,"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:Y_,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:F_,int32:{type:"number",validate:V_},int64:{type:"number",validate:G_},float:{type:"number",validate:Wl},double:{type:"number",validate:Wl},password:!0,binary:!0};xe.fastFormats={...xe.fullFormats,date:Ie(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Si),time:Ie(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ei),"date-time":Ie(/^\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,Kl),"iso-time":Ie(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Gl),"iso-date-time":Ie(/^\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,Yl),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};xe.formatNames=Object.keys(xe.fullFormats);function N_(t){return t%4===0&&(t%100!==0||t%400===0)}var z_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,L_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Vl(t){let e=z_.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&N_(r)?29:L_[n])}function Si(t,e){if(t&&e)return t>e?1:t23||d>59||t&&!c)return!1;if(s<=23&&o<=59&&i<60)return!0;let f=o-d*l,p=s-u*l-(f<0?1:0);return(p===23||p===-1)&&(f===59||f===-1)&&i<61}}function Ei(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 Gl(t,e){if(!(t&&e))return;let r=gi.exec(t),n=gi.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 G_(t){return Number.isInteger(t)}function Wl(){return!0}var K_=/[^\\]\\Z/;function Y_(t){if(K_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Jl=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.formatLimitDefinition=void 0;var B_=hi(),$e=R(),nt=$e.operators,Wn={formatMaximum:{okStr:"<=",ok:nt.LTE,fail:nt.GT},formatMinimum:{okStr:">=",ok:nt.GTE,fail:nt.LT},formatExclusiveMaximum:{okStr:"<",ok:nt.LT,fail:nt.GTE},formatExclusiveMinimum:{okStr:">",ok:nt.GT,fail:nt.LTE}},J_={message:({keyword:t,schemaCode:e})=>(0,$e.str)`should be ${Wn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$e._)`{comparison: ${Wn[t].okStr}, limit: ${e}}`};Lt.formatLimitDefinition={keyword:Object.keys(Wn),type:"string",schemaType:"string",$data:!0,error:J_,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:c}=o;if(!i.validateFormats)return;let l=new B_.KeywordCxt(o,c.RULES.all.format.definition,"format");l.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:c.formats,code:i.code.formats}),m=e.const("fmt",(0,$e._)`${p}[${l.schemaCode}]`);t.fail$data((0,$e.or)((0,$e._)`typeof ${m} != "object"`,(0,$e._)`${m} instanceof RegExp`,(0,$e._)`typeof ${m}.compare != "function"`,f(m)))}function d(){let p=l.schema,m=c.formats[p];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${s}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:m,code:i.code.formats?(0,$e._)`${i.code.formats}${(0,$e.getProperty)(p)}`:void 0});t.fail$data(f(h))}function f(p){return(0,$e._)`${p}.compare(${r}, ${n}) ${Wn[s].fail} 0`}},dependencies:["format"]};var Z_=t=>(t.addKeyword(Lt.formatLimitDefinition),t);Lt.default=Z_});var eu=b((Dr,Ql)=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});var jt=Bl(),X_=Jl(),wi=R(),Zl=new wi.Name("fullFormats"),Q_=new wi.Name("fastFormats"),bi=(t,e={keywords:!0})=>{if(Array.isArray(e))return Xl(t,e,jt.fullFormats,Zl),t;let[r,n]=e.mode==="fast"?[jt.fastFormats,Q_]:[jt.fullFormats,Zl],s=e.formats||jt.formatNames;return Xl(t,s,r,n),e.keywords&&(0,X_.default)(t),t};bi.get=(t,e="full")=>{let n=(e==="fast"?jt.fastFormats:jt.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Xl(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,wi._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Ql.exports=Dr=bi;Object.defineProperty(Dr,"__esModule",{value:!0});Dr.default=bi});var je=require("fs"),Ji=require("path");var z=require("path"),as=require("os"),Yt=require("fs");var Ki=require("url");var Sd={};function ud(){return typeof __dirname<"u"?__dirname:(0,z.dirname)((0,Ki.fileURLToPath)(Sd.url))}var oE=ud();function dd(){if(process.env.CODEBUDDY_MEM_DATA_DIR)return process.env.CODEBUDDY_MEM_DATA_DIR;let t=(0,z.join)((0,as.homedir)(),".codebuddy-mem"),e=(0,z.join)(t,"settings.json");try{if((0,Yt.existsSync)(e)){let r=JSON.parse((0,Yt.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CODEBUDDY_MEM_DATA_DIR)return n.CODEBUDDY_MEM_DATA_DIR}}catch{}return t}var F=dd(),Vr=process.env.CLAUDE_CONFIG_DIR||(0,z.join)((0,as.homedir)(),".claude"),Yi=(0,z.join)(Vr,"plugins","marketplaces","thedotmack"),fd=(0,z.join)(F,"archives"),pd=(0,z.join)(F,"logs"),md=(0,z.join)(F,"trash"),hd=(0,z.join)(F,"backups"),gd=(0,z.join)(F,"modes"),yd=(0,z.join)(F,"settings.json"),iE=(0,z.join)(F,"claude-mem.db"),_d=(0,z.join)(F,"vector-db"),Bi=(0,z.join)(F,"observer-sessions"),aE=(0,z.basename)(Bi),cE=(0,z.join)(Vr,"settings.json"),lE=(0,z.join)(Vr,"commands"),uE=(0,z.join)(Vr,"CLAUDE.md");var me={dataDir:()=>F,workerPid:()=>(0,z.join)(F,"worker.pid"),settings:()=>(0,z.join)(F,"settings.json"),database:()=>(0,z.join)(F,"claude-mem.db"),chroma:()=>(0,z.join)(F,"chroma"),combinedCerts:()=>(0,z.join)(F,"combined_certs.pem"),transcriptsConfig:()=>(0,z.join)(F,"transcript-watch.json"),transcriptsState:()=>(0,z.join)(F,"transcript-watch-state.json"),corpora:()=>(0,z.join)(F,"corpora"),supervisorRegistry:()=>(0,z.join)(F,"supervisor.json"),envFile:()=>(0,z.join)(F,".env"),logsDir:()=>pd,archives:()=>fd,trash:()=>md,backups:()=>hd,modes:()=>gd,vectorDb:()=>_d,observerSessions:()=>Bi};var cs=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(cs||{}),ls=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,je.existsSync)(e)||(0,je.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Ji.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,je.existsSync)(e)){let r=(0,je.readFileSync)(e,"utf-8"),s=(JSON.parse(r).CODEBUDDY_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=cs[s]??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}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}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"),s=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${s} ${o}:${i}:${c}.${l}`}log(e,r,n,s,o){if(e0&&(f=` {${Object.entries(_).map(([S,w])=>`${S}=${w}`).join(", ")}}`)}let p=`[${i}] [${c}] [${l}] ${u}${n}${f}${d}`;if(this.logFilePath)try{(0,je.appendFileSync)(this.logFilePath,p+` `,"utf8")}catch(m){process.stderr.write(`[LOGGER] Failed to write to log file: ${m instanceof Error?m.message:String(m)} `)}else process.stderr.write(p+` `)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}error(e,r,n,s){this.log(3,e,r,n,s)}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}timing(e,r,n,s){this.info(e,`\u23F1 ${r}`,s,{duration:`${n}ms`})}happyPathError(e,r,n,s,o=""){let u=((new Error().stack||"").split(` `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),d=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",f={...n,location:d};return this.warn(e,`[HAPPY-PATH] ${r}`,f,s),o}},y=new ls;var Ed=pe(require("zod/v3"),1),Gr=pe(require("zod/v4-mini"),1);function _t(t){return!!t._zod}function Ke(t,e){return _t(t)?Gr.safeParse(t,e):t.safeParse(e)}function Kr(t){if(!t)return;let e;if(_t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Zi(t){if(_t(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var a=pe(require("zod/v4"),1),ds="2025-11-25";var Xi=[ds,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ye="io.modelcontextprotocol/related-task",Br="2.0",V=a.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Qi=a.union([a.string(),a.number().int()]),ea=a.string(),hE=a.looseObject({ttl:a.number().optional(),pollInterval:a.number().optional()}),wd=a.object({ttl:a.number().optional()}),bd=a.object({taskId:a.string()}),fs=a.looseObject({progressToken:Qi.optional(),[Ye]:bd.optional()}),ue=a.object({_meta:fs.optional()}),Bt=ue.extend({task:wd.optional()}),ta=t=>Bt.safeParse(t).success,G=a.object({method:a.string(),params:ue.loose().optional()}),he=a.object({_meta:fs.optional()}),ge=a.object({method:a.string(),params:he.loose().optional()}),K=a.looseObject({_meta:fs.optional()}),Jr=a.union([a.string(),a.number().int()]),ra=a.object({jsonrpc:a.literal(Br),id:Jr,...G.shape}).strict(),ps=t=>ra.safeParse(t).success,na=a.object({jsonrpc:a.literal(Br),...ge.shape}).strict(),sa=t=>na.safeParse(t).success,ms=a.object({jsonrpc:a.literal(Br),id:Jr,result:K}).strict(),Jt=t=>ms.safeParse(t).success;var O;(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"})(O||(O={}));var hs=a.object({jsonrpc:a.literal(Br),id:Jr.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict();var oa=t=>hs.safeParse(t).success;var ia=a.union([ra,na,ms,hs]),gE=a.union([ms,hs]),Zr=K.strict(),vd=he.extend({requestId:Jr.optional(),reason:a.string().optional()}),Xr=ge.extend({method:a.literal("notifications/cancelled"),params:vd}),kd=a.object({src:a.string(),mimeType:a.string().optional(),sizes:a.array(a.string()).optional(),theme:a.enum(["light","dark"]).optional()}),Zt=a.object({icons:a.array(kd).optional()}),St=a.object({name:a.string(),title:a.string().optional()}),aa=St.extend({...St.shape,...Zt.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()}),Pd=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),Td=a.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,a.intersection(a.object({form:Pd.optional(),url:V.optional()}),a.record(a.string(),a.unknown()).optional())),$d=a.looseObject({list:V.optional(),cancel:V.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:V.optional()}).optional(),elicitation:a.looseObject({create:V.optional()}).optional()}).optional()}),Rd=a.looseObject({list:V.optional(),cancel:V.optional(),requests:a.looseObject({tools:a.looseObject({call:V.optional()}).optional()}).optional()}),Md=a.object({experimental:a.record(a.string(),V).optional(),sampling:a.object({context:V.optional(),tools:V.optional()}).optional(),elicitation:Td.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:$d.optional(),extensions:a.record(a.string(),V).optional()}),Cd=ue.extend({protocolVersion:a.string(),capabilities:Md,clientInfo:aa}),gs=G.extend({method:a.literal("initialize"),params:Cd});var Ad=a.object({experimental:a.record(a.string(),V).optional(),logging:V.optional(),completions:V.optional(),prompts:a.object({listChanged:a.boolean().optional()}).optional(),resources:a.object({subscribe:a.boolean().optional(),listChanged:a.boolean().optional()}).optional(),tools:a.object({listChanged:a.boolean().optional()}).optional(),tasks:Rd.optional(),extensions:a.record(a.string(),V).optional()}),Od=K.extend({protocolVersion:a.string(),capabilities:Ad,serverInfo:aa,instructions:a.string().optional()}),ys=ge.extend({method:a.literal("notifications/initialized"),params:he.optional()});var Qr=G.extend({method:a.literal("ping"),params:ue.optional()}),Id=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),xd=a.object({...he.shape,...Id.shape,progressToken:Qi}),en=ge.extend({method:a.literal("notifications/progress"),params:xd}),Dd=ue.extend({cursor:ea.optional()}),Xt=G.extend({params:Dd.optional()}),Qt=K.extend({nextCursor:ea.optional()}),Nd=a.enum(["working","input_required","completed","failed","cancelled"]),er=a.object({taskId:a.string(),status:Nd,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),Et=K.extend({task:er}),zd=he.merge(er),tr=ge.extend({method:a.literal("notifications/tasks/status"),params:zd}),tn=G.extend({method:a.literal("tasks/get"),params:ue.extend({taskId:a.string()})}),rn=K.merge(er),nn=G.extend({method:a.literal("tasks/result"),params:ue.extend({taskId:a.string()})}),yE=K.loose(),sn=Xt.extend({method:a.literal("tasks/list")}),on=Qt.extend({tasks:a.array(er)}),an=G.extend({method:a.literal("tasks/cancel"),params:ue.extend({taskId:a.string()})}),ca=K.merge(er),la=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),ua=la.extend({text:a.string()}),_s=a.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),da=la.extend({blob:_s}),rr=a.enum(["user","assistant"]),wt=a.object({audience:a.array(rr).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),fa=a.object({...St.shape,...Zt.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),Ld=a.object({...St.shape,...Zt.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:wt.optional(),_meta:a.optional(a.looseObject({}))}),jd=Xt.extend({method:a.literal("resources/list")}),qd=Qt.extend({resources:a.array(fa)}),Ud=Xt.extend({method:a.literal("resources/templates/list")}),Fd=Qt.extend({resourceTemplates:a.array(Ld)}),Ss=ue.extend({uri:a.string()}),Hd=Ss,Wd=G.extend({method:a.literal("resources/read"),params:Hd}),Vd=K.extend({contents:a.array(a.union([ua,da]))}),Gd=ge.extend({method:a.literal("notifications/resources/list_changed"),params:he.optional()}),Kd=Ss,Yd=G.extend({method:a.literal("resources/subscribe"),params:Kd}),Bd=Ss,Jd=G.extend({method:a.literal("resources/unsubscribe"),params:Bd}),Zd=he.extend({uri:a.string()}),Xd=ge.extend({method:a.literal("notifications/resources/updated"),params:Zd}),Qd=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),ef=a.object({...St.shape,...Zt.shape,description:a.optional(a.string()),arguments:a.optional(a.array(Qd)),_meta:a.optional(a.looseObject({}))}),tf=Xt.extend({method:a.literal("prompts/list")}),rf=Qt.extend({prompts:a.array(ef)}),nf=ue.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),sf=G.extend({method:a.literal("prompts/get"),params:nf}),Es=a.object({type:a.literal("text"),text:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ws=a.object({type:a.literal("image"),data:_s,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),bs=a.object({type:a.literal("audio"),data:_s,mimeType:a.string(),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),of=a.object({type:a.literal("tool_use"),name:a.string(),id:a.string(),input:a.record(a.string(),a.unknown()),_meta:a.record(a.string(),a.unknown()).optional()}),af=a.object({type:a.literal("resource"),resource:a.union([ua,da]),annotations:wt.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),cf=fa.extend({type:a.literal("resource_link")}),vs=a.union([Es,ws,bs,cf,af]),lf=a.object({role:rr,content:vs}),uf=K.extend({description:a.string().optional(),messages:a.array(lf)}),df=ge.extend({method:a.literal("notifications/prompts/list_changed"),params:he.optional()}),ff=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),pf=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),pa=a.object({...St.shape,...Zt.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),V).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),V).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:ff.optional(),execution:pf.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ks=Xt.extend({method:a.literal("tools/list")}),mf=Qt.extend({tools:a.array(pa)}),cn=K.extend({content:a.array(vs).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),_E=cn.or(K.extend({toolResult:a.unknown()})),hf=Bt.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),nr=G.extend({method:a.literal("tools/call"),params:hf}),gf=ge.extend({method:a.literal("notifications/tools/list_changed"),params:he.optional()}),SE=a.object({autoRefresh:a.boolean().default(!0),debounceMs:a.number().int().nonnegative().default(300)}),sr=a.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),yf=ue.extend({level:sr}),Ps=G.extend({method:a.literal("logging/setLevel"),params:yf}),_f=he.extend({level:sr,logger:a.string().optional(),data:a.unknown()}),Sf=ge.extend({method:a.literal("notifications/message"),params:_f}),Ef=a.object({name:a.string().optional()}),wf=a.object({hints:a.array(Ef).optional(),costPriority:a.number().min(0).max(1).optional(),speedPriority:a.number().min(0).max(1).optional(),intelligencePriority:a.number().min(0).max(1).optional()}),bf=a.object({mode:a.enum(["auto","required","none"]).optional()}),vf=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(vs).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),kf=a.discriminatedUnion("type",[Es,ws,bs]),Yr=a.discriminatedUnion("type",[Es,ws,bs,of,vf]),Pf=a.object({role:rr,content:a.union([Yr,a.array(Yr)]),_meta:a.record(a.string(),a.unknown()).optional()}),Tf=Bt.extend({messages:a.array(Pf),modelPreferences:wf.optional(),systemPrompt:a.string().optional(),includeContext:a.enum(["none","thisServer","allServers"]).optional(),temperature:a.number().optional(),maxTokens:a.number().int(),stopSequences:a.array(a.string()).optional(),metadata:V.optional(),tools:a.array(pa).optional(),toolChoice:bf.optional()}),$f=G.extend({method:a.literal("sampling/createMessage"),params:Tf}),or=K.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:rr,content:kf}),Ts=K.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:rr,content:a.union([Yr,a.array(Yr)])}),Rf=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),Mf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),minLength:a.number().optional(),maxLength:a.number().optional(),format:a.enum(["email","uri","date","date-time"]).optional(),default:a.string().optional()}),Cf=a.object({type:a.enum(["number","integer"]),title:a.string().optional(),description:a.string().optional(),minimum:a.number().optional(),maximum:a.number().optional(),default:a.number().optional()}),Af=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),Of=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),oneOf:a.array(a.object({const:a.string(),title:a.string()})),default:a.string().optional()}),If=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),enumNames:a.array(a.string()).optional(),default:a.string().optional()}),xf=a.union([Af,Of]),Df=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({type:a.literal("string"),enum:a.array(a.string())}),default:a.array(a.string()).optional()}),Nf=a.object({type:a.literal("array"),title:a.string().optional(),description:a.string().optional(),minItems:a.number().optional(),maxItems:a.number().optional(),items:a.object({anyOf:a.array(a.object({const:a.string(),title:a.string()}))}),default:a.array(a.string()).optional()}),zf=a.union([Df,Nf]),Lf=a.union([If,xf,zf]),jf=a.union([Lf,Rf,Mf,Cf]),qf=Bt.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),jf),required:a.array(a.string()).optional()})}),Uf=Bt.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),Ff=a.union([qf,Uf]),Hf=G.extend({method:a.literal("elicitation/create"),params:Ff}),Wf=he.extend({elicitationId:a.string()}),Vf=ge.extend({method:a.literal("notifications/elicitation/complete"),params:Wf}),bt=K.extend({action:a.enum(["accept","decline","cancel"]),content:a.preprocess(t=>t===null?void 0:t,a.record(a.string(),a.union([a.string(),a.number(),a.boolean(),a.array(a.string())])).optional())}),Gf=a.object({type:a.literal("ref/resource"),uri:a.string()});var Kf=a.object({type:a.literal("ref/prompt"),name:a.string()}),Yf=ue.extend({ref:a.union([Kf,Gf]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),Bf=G.extend({method:a.literal("completion/complete"),params:Yf});var Jf=K.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),Zf=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Xf=G.extend({method:a.literal("roots/list"),params:ue.optional()}),$s=K.extend({roots:a.array(Zf)}),Qf=ge.extend({method:a.literal("notifications/roots/list_changed"),params:he.optional()}),EE=a.union([Qr,gs,Bf,Ps,sf,tf,jd,Ud,Wd,Yd,Jd,nr,ks,tn,nn,sn,an]),wE=a.union([Xr,en,ys,Qf,tr]),bE=a.union([Zr,or,Ts,bt,$s,rn,on,Et]),vE=a.union([Qr,$f,Hf,Xf,tn,nn,sn,an]),kE=a.union([Xr,en,Sf,Xd,Gd,gf,df,tr,Vf]),PE=a.union([Zr,Od,Jf,uf,rf,qd,Fd,Vd,cn,mf,rn,on,Et]),T=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===O.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new us(s.elicitations,r)}return new t(e,r,n)}},us=class extends T{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Be(t){return t==="completed"||t==="failed"||t==="cancelled"}var cp=pe(require("zod/v4-mini"),1);var ip=require("zod/v3");var tp=require("zod/v3");var sp=require("zod/v3");var sw=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rs(t){let r=Kr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ms(t,e){let r=Ke(t,e);if(!r.success)throw r.error;return r.data}var lp=6e4,ln=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(Xr,r=>{this._oncancel(r)}),this.setNotificationHandler(en,r=>{this._onprogress(r)}),this.setRequestHandler(Qr,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(tn,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new T(O.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(nn,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(c.type==="response"||c.type==="error"){let l=c.message,u=l.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),c.type==="response")d(l);else{let f=l,p=new T(f.error.code,f.error.message,f.error.data);d(p)}else{let f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new T(O.InvalidParams,`Task not found: ${o}`);if(!Be(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Be(i.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Ye]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(sn,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new T(O.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(an,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new T(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(Be(s.status))throw new T(O.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof T?s:new T(O.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),T.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Jt(o)||oa(o)?this._onresponse(o):ps(o)?this._onrequest(o,i):sa(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=T.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ye]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):s?.send(d).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let c=ta(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(d,f)},sendRequest:async(d,f,p)=>{if(i.signal.aborted)throw new T(O.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let h=m.relatedTask?.taskId??o;return h&&l&&await l.updateTaskStatus(h,"input_required"),await this.request(d,f,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let f={result:d,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)},async d=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:O.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},s?.sessionId):await s?.send(f)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),c=this._timeoutInfo.get(s);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Jt(e))n(e);else{let i=new T(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Jt(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let c=i.task;typeof c.taskId=="string"&&(o=!0,this._taskProgressTokens.set(c.taskId,r))}}if(o||this._progressHandlers.delete(r),Jt(e))s(e);else{let i=T.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof T?i:new T(O.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Et,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new T(O.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:c},Be(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:c.status==="failed"?yield{type:"error",error:new T(O.InternalError,`Task ${o} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new T(O.InternalError,`Task ${o} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof T?i:new T(O.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:c,relatedTask:l}=n??{};return new Promise((u,d)=>{let f=S=>{d(S)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),c&&this.assertTaskCapability(e.method)}catch(S){f(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),c&&(m.params={...m.params,task:c}),l&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Ye]:l}});let h=S=>{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(S)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));let w=S instanceof T?S:new T(O.RequestTimeout,String(S));d(w)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return d(S);try{let w=Ke(r,S.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??lp,_=()=>h(T.fromError(O.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let E=l?.taskId;if(E){let S=w=>{let C=this._responseHandlers.get(p);C?C(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(E,{type:"request",message:m,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),d(w)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),d(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},rn,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},on,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ca,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 c={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ye]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,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 c={...e,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[Ye]:r.relatedTask}}}),this._transport?.send(c,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ye]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Rs(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Ms(e,s);return Promise.resolve(r(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Rs(e);this._notificationHandlers.set(n,s=>{let o=Ms(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&ps(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new T(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new T(O.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new T(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new T(O.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let c=await n.getTask(s,r);if(c){let l=tr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Be(c.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let c=await n.getTask(s,r);if(!c)throw new T(O.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Be(c.status))throw new T(O.InvalidParams,`Cannot update task "${s}" from terminal status "${c.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let u=tr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Be(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ma(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ha(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];ma(i)&&ma(o)?r[s]={...i,...o}:r[s]=o}return r}var tu=pe(hi(),1),ru=pe(eu(),1);function eS(){let t=new tu.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,ru.default)(t),t}var Vn=class{constructor(e){this._ajv=e??eS()}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 Gn=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=c?Array.isArray(c.content)?c.content:[c.content]:[],u=l.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(l.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==f.size||![...d].every(p=>f.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},or,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},bt,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 nu(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 su(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 Kn=class extends ln{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sr.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(ys,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ps,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,c=sr.safeParse(i);return c.success&&this._loggingLevels.set(o,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Gn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ha(this._capabilities,e)}setRequestHandler(e,r){let s=Kr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(_t(s)){let c=s;o=c._zod?.def?.value??c.value}else{let c=s;o=c._def?.value??c.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let c=async(l,u)=>{let d=Ke(nr,l);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new T(O.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:f}=d.data,p=await Promise.resolve(r(l,u));if(f.task){let h=Ke(Et,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new T(O.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let m=Ke(cn,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new T(O.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,c)}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){su(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nu(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:Xi.includes(r)?r:ds,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"},Zr)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=i?Array.isArray(i.content)?i.content:[i.content]:[],l=c.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))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},Ts,r):this.request({method:"sampling/createMessage",params:e},or,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},bt,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},bt,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!c.valid)throw new T(O.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(i){throw i instanceof T?i:new T(O.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},$s,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 vi=pe(require("node:process"),1);var Yn=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),tS(r)}clear(){this._buffer=void 0}};function tS(t){return ia.parse(JSON.parse(t))}function ou(t){return JSON.stringify(t)+` `}var Bn=class{constructor(e=vi.default.stdin,r=vi.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Yn,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=ou(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Ai=pe(require("path"),1);var iu=require("node:child_process");function Jn(t,e,r){return(0,iu.spawn)(t,e??[],{windowsHide:!0,...r})}var ce={DEFAULT:3e5,HEALTH_CHECK:3e3,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 au(t){return process.platform==="win32"?Math.round(t*ce.WINDOWS_MULTIPLIER):t}var De=require("fs"),Nr=require("path"),ki=require("os"),Ne=class{static DEFAULTS={CODEBUDDY_MEM_MODEL:"claude-haiku-4-5-20251001",CODEBUDDY_MEM_CONTEXT_OBSERVATIONS:"50",CODEBUDDY_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CODEBUDDY_MEM_WORKER_HOST:"127.0.0.1",CODEBUDDY_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CODEBUDDY_MEM_PROVIDER:"claude",CODEBUDDY_MEM_CLAUDE_AUTH_METHOD:"cli",CODEBUDDY_MEM_GEMINI_API_KEY:"",CODEBUDDY_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CODEBUDDY_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CODEBUDDY_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CODEBUDDY_MEM_GEMINI_MAX_TOKENS:"100000",CODEBUDDY_MEM_OPENROUTER_API_KEY:"",CODEBUDDY_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CODEBUDDY_MEM_OPENROUTER_SITE_URL:"",CODEBUDDY_MEM_OPENROUTER_APP_NAME:"codebuddy-mem",CODEBUDDY_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CODEBUDDY_MEM_OPENROUTER_MAX_TOKENS:"100000",CODEBUDDY_MEM_DATA_DIR:(0,Nr.join)((0,ki.homedir)(),".codebuddy-mem"),CODEBUDDY_MEM_LOG_LEVEL:"INFO",CODEBUDDY_MEM_PYTHON_VERSION:"3.13",CODEBUDDY_CODE_PATH:"",CODEBUDDY_MEM_MODE:"code",CODEBUDDY_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CODEBUDDY_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CODEBUDDY_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CODEBUDDY_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CODEBUDDY_MEM_CONTEXT_FULL_COUNT:"0",CODEBUDDY_MEM_CONTEXT_FULL_FIELD:"narrative",CODEBUDDY_MEM_CONTEXT_SESSION_COUNT:"10",CODEBUDDY_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CODEBUDDY_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CODEBUDDY_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CODEBUDDY_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CODEBUDDY_MEM_FOLDER_USE_LOCAL_MD:"false",CODEBUDDY_MEM_TRANSCRIPTS_ENABLED:"true",CODEBUDDY_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Nr.join)((0,ki.homedir)(),".codebuddy-mem","transcript-watch.json"),CODEBUDDY_MEM_MAX_CONCURRENT_AGENTS:"2",CODEBUDDY_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CODEBUDDY_MEM_EXCLUDED_PROJECTS:"",CODEBUDDY_MEM_FOLDER_MD_EXCLUDE:"[]",CODEBUDDY_MEM_SEMANTIC_INJECT:"false",CODEBUDDY_MEM_SEMANTIC_INJECT_LIMIT:"5",CODEBUDDY_MEM_TIER_ROUTING_ENABLED:"true",CODEBUDDY_MEM_TIER_SIMPLE_MODEL:"haiku",CODEBUDDY_MEM_TIER_SUMMARY_MODEL:"",CODEBUDDY_MEM_CHROMA_ENABLED:"true",CODEBUDDY_MEM_CHROMA_MODE:"local",CODEBUDDY_MEM_CHROMA_HOST:"127.0.0.1",CODEBUDDY_MEM_CHROMA_PORT:"8000",CODEBUDDY_MEM_CHROMA_SSL:"false",CODEBUDDY_MEM_CHROMA_API_KEY:"",CODEBUDDY_MEM_CHROMA_TENANT:"default_tenant",CODEBUDDY_MEM_CHROMA_DATABASE:"default_database",CODEBUDDY_MEM_TELEGRAM_ENABLED:"true",CODEBUDDY_MEM_TELEGRAM_BOT_TOKEN:"",CODEBUDDY_MEM_TELEGRAM_CHAT_ID:"",CODEBUDDY_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CODEBUDDY_MEM_TELEGRAM_TRIGGER_CONCEPTS:""};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){try{if(!(0,De.existsSync)(e)){let i=this.getAllDefaults();try{let c=(0,Nr.dirname)(e);(0,De.existsSync)(c)||(0,De.mkdirSync)(c,{recursive:!0}),(0,De.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[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 this.applyEnvOverrides(i)}let r=(0,De.readFileSync)(e,"utf-8"),n=JSON.parse(r),s=n;if(n.env&&typeof n.env=="object"){s=n.env;try{(0,De.writeFileSync)(e,JSON.stringify(s,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))s[i]!==void 0&&(o[i]=s[i]);return this.applyEnvOverrides(o)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r instanceof Error?r.message:String(r)),this.applyEnvOverrides(this.getAllDefaults())}}};var ht=require("fs");var cu=require("child_process");var Le=require("fs"),$i=pe(require("path"),1);var rS=["CLAUDECODE_","CLAUDE_CODE_"],nS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),sS=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),oS=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 Pi(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(oS.has(r)){e[r]=n;continue}nS.has(r)||sS.has(r)||rS.some(s=>r.startsWith(s))||(e[r]=n)}return e}var iS=5e3,aS=1e3,cS=me.supervisorRegistry();function ze(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}}function lu(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Le.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let s=e.slice(r+2).split(" ")[19];return s&&/^\d+$/.test(s)?s: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 null;try{let e=(0,cu.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...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 Mi(t){if(!t||!ze(t.pid))return!1;if(!t.startToken)return!0;let e=lu(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 Ri=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=cS){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Le.mkdirSync)($i.default.dirname(this.registryPath),{recursive:!0}),!(0,Le.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Le.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,o]of Object.entries(n))this.entries.set(s,o)}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(),this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist()}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),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}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;for(let[r,n]of this.entries)ze(n.pid)||(this.entries.delete(r),this.runtimeProcesses.delete(r),e+=1);return e>0&&this.persist(),e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;y.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(c=>c.pid)});let s=r.filter(c=>ze(c.pid));for(let c of s)try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGTERM"):process.kill(c.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGTERM session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGTERM session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}let o=Date.now()+iS;for(;Date.now()ze(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let i=s.filter(c=>ze(c.pid));for(let c of i){y.warn("SYSTEM",`Session process PID ${c.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:c.pid,pgid:c.pgid,sessionId:n});try{typeof c.pgid=="number"&&process.platform!=="win32"?process.kill(-c.pgid,"SIGKILL"):process.kill(c.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&y.debug("SYSTEM",`Failed to SIGKILL session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},l):y.warn("SYSTEM",`Failed to SIGKILL session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(l)})}}if(i.length>0){let c=Date.now()+aS;for(;Date.now()ze(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let c of r)this.entries.delete(c.id),this.runtimeProcesses.delete(c.id);return this.persist(),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,Le.mkdirSync)($i.default.dirname(this.registryPath),{recursive:!0}),(0,Le.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ti=null;function Zn(){return Ti||(Ti=new Ri),Ti}var fu=require("child_process"),pu=require("fs"),mu=require("util");var lS=(0,mu.promisify)(fu.execFile),uS=me.workerPid();async function hu(t){let e=t.currentPid??process.pid,r=t.pidFilePath??uS,n=t.registry.getAll(),s=[...n].filter(i=>i.pid!==e).sort((i,c)=>Date.parse(c.startedAt)-Date.parse(i.startedAt));for(let i of s){if(!ze(i.pid)){t.registry.unregister(i.id);continue}try{await du(i,"SIGTERM")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}}await uu(s,5e3);let o=s.filter(i=>ze(i.pid));for(let i of o)try{await du(i,"SIGKILL")}catch(c){c instanceof Error?y.debug("SYSTEM","Failed to force kill child process",{pid:i.pid,pgid:i.pgid,type:i.type},c):y.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:i.pid,pgid:i.pgid,type:i.type,error:String(c)})}await uu(o,1e3);for(let i of s)t.registry.unregister(i.id);for(let i of n.filter(c=>c.pid===e))t.registry.unregister(i.id);try{(0,pu.rmSync)(r,{force:!0})}catch(i){i instanceof Error?y.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},i):y.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(i)})}t.registry.pruneDeadEntries()}async function uu(t,e){let r=Date.now()+e;for(;Date.now()ze(s.pid)).length===0)return;await new Promise(s=>setTimeout(s,100))}}async function du(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 s=await dS();if(s){await new Promise((i,c)=>{s(r,e,l=>{if(!l){i();return}if(l.code==="ESRCH"){i();return}c(l)})});return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await lS("taskkill",o,{timeout:ce.POWERSHELL_COMMAND,windowsHide:!0})}async function dS(){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 gu=3e4,qt=null;function fS(){let e=Zn().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function yu(){qt===null&&(qt=setInterval(fS,gu),qt.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:gu}))}function _u(){qt!==null&&(clearInterval(qt),qt=null,y.debug("SYSTEM","Health checker stopped"))}var pS=me.workerPid(),Ci=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(),Xn({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,yu()}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(s){s instanceof Error?y.error("SYSTEM","Error during shutdown",{},s):y.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(o){o instanceof Error?y.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):y.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}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}_u(),this.stopPromise=hu({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}},mS=new Ci(Zn());function Su(){return mS}function Xn(t={}){let e=t.pidFilePath??pS;if(!(0,ht.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ht.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):y.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,ht.rmSync)(e,{force:!0}),"invalid"}return Mi(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,ht.rmSync)(e,{force:!0}),"stale")}var hS=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;y.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return au(ce.HEALTH_CHECK)})();function gS(t,e={},r){return new Promise((n,s)=>{let o=setTimeout(()=>s(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),s(i)})})}var Qn=null,es=null;function Oi(){if(Qn!==null)return Qn;let t=Ai.default.join(Ne.get("CODEBUDDY_MEM_DATA_DIR"),"settings.json"),e=Ne.loadFromFile(t);return Qn=parseInt(e.CODEBUDDY_MEM_WORKER_PORT,10),Qn}function yS(){if(es!==null)return es;let t=Ai.default.join(Ne.get("CODEBUDDY_MEM_DATA_DIR"),"settings.json");return es=Ne.loadFromFile(t).CODEBUDDY_MEM_WORKER_HOST,es}function _S(t){return`http://${yS()}:${Oi()}${t}`}function ts(t,e={}){let r=e.method??"GET",n=e.timeoutMs??hS,s=_S(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),n>0?gS(s,o,n):fetch(s,o)}var xi=pe(require("path"),1),we=require("fs");var gt=pe(require("path"),1),bu=require("os"),de=require("fs"),Ut=require("child_process");var vu=require("util");var bP=(0,vu.promisify)(Ut.exec),vP=me.dataDir(),Eu=me.workerPid();function wu(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function SS(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,Ut.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):y.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(o))),null}return n.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var Ii;function ES(t={}){let e=Object.keys(t).length===0;if(e&&Ii!==void 0)return Ii;let r=wS(t);return e&&r!==null&&(Ii=r),r}function wS(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(wu(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,bu.homedir)(),o=t.pathExists??de.existsSync,i=t.lookupInPath??SS,c=e==="win32"?[n.BUN,n.BUN_PATH,gt.default.join(s,".bun","bin","bun.exe"),gt.default.join(s,".bun","bin","bun"),n.USERPROFILE?gt.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?gt.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?gt.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,gt.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of c){let u=l?.trim();if(u&&(wu(u)&&o(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function st(t){return process.platform==="win32"?Math.round(t*2):t}function ku(t,e,r={}){Su().assertCanSpawn("worker daemon");let n=Pi({...process.env,CODEBUDDY_MEM_WORKER_PORT:String(e),...r}),s=ES();if(!s){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 d=`Start-Process -FilePath '${s.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,f=Buffer.from(d,"utf16le").toString("base64");try{return(0,Ut.execSync)(`powershell -NoProfile -EncodedCommand ${f}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(p){y.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:s},p instanceof Error?p:new Error(String(p)));return}}let o="/usr/bin/setsid",i=(0,de.existsSync)(o),u=Jn(i?o:s,i?[s,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:n});if(u.pid!==void 0)return u.unref(),u.pid}function Pu(){try{if(!(0,de.existsSync)(Eu))return;let t=new Date;(0,de.utimesSync)(Eu,t,t)}catch{}}function Tu(){return Xn({logAlive:!1})}var $u=pe(require("net"),1);async function bS(t,e,r="GET"){let n=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),s="";try{s=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:s}}async function Ru(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=$u.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 Mu(t,e,r,n){let s=Date.now();for(;Date.now()-ssetTimeout(o,500))}return!1}function zr(t,e=3e4){return Mu(t,"/api/health",e,"Service not ready yet, will retry")}function Lr(t,e=3e4){return Mu(t,"/api/readiness",e,"Worker not ready yet, will retry")}var vS=120*1e3;function Di(){return xi.default.join(Ne.get("CODEBUDDY_MEM_DATA_DIR"),".worker-start-attempted")}function kS(){if(process.platform!=="win32")return!1;let t=Di();if(!(0,we.existsSync)(t))return!1;try{let e=(0,we.statSync)(t).mtimeMs;return Date.now()-etypeof f=="string")){s.grammars[o]={package:l,extensions:u,query:typeof d=="string"?d:void 0};for(let f of u)qi[f]||(s.extensionToLanguage[f]=o);if(typeof d=="string"){let f=(0,Z.join)(t,d);try{let p=(0,te.readFileSync)(f,"utf-8"),m=`user_${o}`;Lu[m]=p,s.languageToQueryKey[o]=m}catch{console.error(`[smart-file-read] Custom query file not found: ${f}, falling back to generic`),s.languageToQueryKey[o]="generic"}}else s.languageToQueryKey[o]="generic"}}return jr.set(t,s),s}var Nu={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"},TS={markdown:"tree-sitter-markdown"};function $S(t){let e=Nu[t];if(!e)return null;let r=TS[t];if(r){try{let n=ji.resolve(e+"/package.json"),s=(0,Z.join)((0,Z.dirname)(n),r);if((0,te.existsSync)((0,Z.join)(s,"src")))return s}catch{}return null}try{let n=ji.resolve(e+"/package.json");return(0,Z.dirname)(n)}catch{return null}}function zu(t,e){let r=$S(t);if(r)return r;if(!e)return null;let s=Ur(e).grammars[t];if(!s)return null;try{let o=(0,Z.join)(e,"node_modules",s.package,"package.json");if((0,te.existsSync)(o)){let i=(0,Z.dirname)(o);if((0,te.existsSync)((0,Z.join)(i,"src")))return i}}catch{}return console.error(`[smart-file-read] Grammar package not found for "${t}": ${s.package} (install it in your project's node_modules)`),null}var Lu={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 (method_definition name: (property_identifier) @name) @method (interface_declaration name: (type_identifier) @name) @iface (type_alias_declaration name: (type_identifier) @name) @tdef (enum_declaration name: (identifier) @name) @enm (import_statement) @imp (export_statement) @exp `,python:` (function_definition name: (identifier) @name) @func (class_definition name: (identifier) @name) @cls (import_statement) @imp (import_from_statement) @imp `,go:` (function_declaration name: (identifier) @name) @func (method_declaration name: (field_identifier) @name) @method (type_declaration (type_spec name: (type_identifier) @name)) @tdef (import_declaration) @imp `,rust:` (function_item name: (identifier) @name) @func (struct_item name: (type_identifier) @name) @struct_def (enum_item name: (type_identifier) @name) @enm (trait_item name: (type_identifier) @name) @trait_def (impl_item type: (type_identifier) @name) @impl_def (use_declaration) @imp `,ruby:` (method name: (identifier) @name) @func (class name: (constant) @name) @cls (module name: (constant) @name) @cls (call method: (identifier) @name) @imp `,java:` (method_declaration name: (identifier) @name) @method (class_declaration name: (identifier) @name) @cls (interface_declaration name: (identifier) @name) @iface (enum_declaration name: (identifier) @name) @enm (import_declaration) @imp `,kotlin:` (function_declaration (simple_identifier) @name) @func (class_declaration (type_identifier) @name) @cls (object_declaration (type_identifier) @name) @cls (import_header) @imp `,swift:` (function_declaration name: (simple_identifier) @name) @func (class_declaration name: (type_identifier) @name) @cls (protocol_declaration name: (type_identifier) @name) @iface (import_declaration) @imp `,php:` (function_definition name: (name) @name) @func (class_declaration name: (name) @name) @cls (interface_declaration name: (name) @name) @iface (trait_declaration name: (name) @name) @trait_def (method_declaration name: (name) @name) @method (namespace_use_declaration) @imp `,lua:` (function_declaration name: (identifier) @name) @func (function_declaration name: (dot_index_expression) @name) @func (function_declaration name: (method_index_expression) @name) @func `,scala:` (function_definition name: (identifier) @name) @func (class_definition name: (identifier) @name) @cls (object_definition name: (identifier) @name) @cls (trait_definition name: (identifier) @name) @trait_def (import_declaration) @imp `,bash:` (function_definition name: (word) @name) @func `,haskell:` (function name: (variable) @name) @func (type_synomym name: (name) @name) @tdef (newtype name: (name) @name) @tdef (data_type name: (name) @name) @tdef (class name: (name) @name) @cls (import) @imp `,zig:` (function_declaration name: (identifier) @name) @func (test_declaration) @func `,css:` (rule_set (selectors) @name) @func (media_statement) @cls (keyframes_statement (keyframes_name) @name) @cls (import_statement) @imp `,scss:` (rule_set (selectors) @name) @func (media_statement) @cls (keyframes_statement (keyframes_name) @name) @cls (import_statement) @imp (mixin_statement name: (identifier) @name) @mixin_def (function_statement name: (identifier) @name) @func (include_statement) @imp `,toml:` (table (bare_key) @name) @cls (table (dotted_key) @name) @cls (table_array_element (bare_key) @name) @cls (table_array_element (dotted_key) @name) @cls `,yaml:` (block_mapping_pair key: (flow_node) @name) @func `,sql:` (create_table (object_reference) @name) @cls (create_function (object_reference) @name) @func (create_view (object_reference) @name) @cls `,markdown:` (atx_heading heading_content: (inline) @name) @heading (setext_heading heading_content: (paragraph) @name) @heading (fenced_code_block (info_string (language) @name)) @code_block (fenced_code_block) @code_block (minus_metadata) @frontmatter (link_reference_definition (link_label) @name) @ref `,generic:` (function_declaration name: (identifier) @name) @func (function_definition name: (identifier) @name) @func (class_declaration name: (identifier) @name) @cls (class_definition name: (identifier) @name) @cls (import_statement) @imp (import_declaration) @imp `};function RS(t){switch(t){case"javascript":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 Ni=null,zi=new Map;function ju(t){if(zi.has(t))return zi.get(t);Ni||(Ni=(0,te.mkdtempSync)((0,Z.join)((0,Ui.tmpdir)(),"smart-read-queries-")));let e=(0,Z.join)(Ni,`${t}.scm`);return(0,te.writeFileSync)(e,Lu[t]),zi.set(t,e),e}var qr=null;function MS(){if(qr)return qr;try{let t=ji.resolve("tree-sitter-cli/package.json"),e=(0,Z.join)((0,Z.dirname)(t),"tree-sitter");if((0,te.existsSync)(e))return qr=e,e}catch{}return qr="tree-sitter",qr}function CS(t,e,r){return qu(t,[e],r).get(e)||[]}function qu(t,e,r){if(e.length===0)return new Map;let n=MS(),s=["query","-p",r,t,...e],o;try{o=(0,Iu.execFileSync)(n,s,{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 AS(o)}function AS(t){let e=new Map,r=null,n=null;for(let s of t.split(` `)){if(s.length>0&&!s.startsWith(" ")&&!s.startsWith(" ")){r=s.trim(),e.has(r)||e.set(r,[]),n=null;continue}if(!r)continue;let o=s.match(/^\s+pattern:\s+(\d+)/);if(o){n={pattern:parseInt(o[1]),captures:[]},e.get(r).push(n);continue}let i=s.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 Au={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"},OS=new Set(["class","struct","impl","trait"]);function IS(t,e,r,n=200){let o=t[e]||"";if(!o.trimEnd().endsWith("{")&&!o.trimEnd().endsWith(":")){let i=t.slice(e,Math.min(e+10,r+1)).join(` `),c=i.indexOf("{");c!==-1&&c<500&&(o=i.slice(0,c).replace(/\n/g," ").replace(/\s+/g," ").trim())}return o=o.replace(/\s*[{:]\s*$/,"").trim(),o.length>n&&(o=o.slice(0,n-3)+"..."),o}function xS(t,e){let r=[],n=!1;for(let s=e-1;s>=0;s--){let o=t[s].trim();if(o===""){if(n)break;continue}if(o.startsWith("/**")||o.startsWith("*")||o.startsWith("*/")||o.startsWith("//")||o.startsWith("///")||o.startsWith("//!")||o.startsWith("#")||o.startsWith("@"))r.unshift(t[s]),n=!0;else break}return r.length>0?r.join(` `).trim():void 0}function DS(t,e,r){for(let n=e+1;n<=Math.min(e+3,r);n++){let s=t[n]?.trim();if(s){if(s.startsWith('"""')||s.startsWith("'''"))return s;break}}}function NS(t,e,r,n,s,o){switch(o){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 s[e]?.trimStart().startsWith("pub")??!1;default:return!0}}function Uu(t,e,r){let n=[],s=[],o=[],i=[];for(let l of t)for(let u of l.captures)u.tag==="exp"&&o.push({startRow:u.startRow,endRow:u.endRow}),u.tag==="imp"&&s.push(u.text||e[u.startRow]?.trim()||"");for(let l of t){let u=l.captures.find(w=>Au[w.tag]),d=l.captures.find(w=>w.tag==="name");if(!u)continue;let f=u.startRow,p=u.endRow,m=Au[u.tag],h=d?.text||"anonymous",g;if(r==="markdown"&&m==="section"){let C=(e[f]||"").match(/^(#{1,6})\s/),k=C?C[1].length:1;g=`${"#".repeat(k)} ${h}`}else if(r==="markdown"&&m==="code"){let w=h!=="anonymous"?h:"";g=w?"```"+w:"```"}else r==="markdown"&&m==="metadata"?g="---frontmatter---":r==="markdown"&&m==="reference"?g=e[f]?.trim()||h:g=IS(e,f,p);let _=r==="markdown"?void 0:xS(e,f),E=r==="python"?DS(e,f,p):void 0,S={name:h,kind:m,signature:g,jsdoc:_||E,lineStart:f,lineEnd:p,exported:NS(h,f,p,o,e,r)};OS.has(m)&&(S.children=[],i.push({sym:S,startRow:f,endRow:p})),n.push(S)}if(r==="markdown"){let l=new Map,u=new Set;for(let d of n){if(d.kind!=="code")continue;let f=`${d.lineStart}:${d.lineEnd}`,p=l.get(f);p?d.name!=="anonymous"?(u.add(p),l.set(f,d)):u.add(d):l.set(f,d)}if(u.size>0){let d=n.filter(f=>!u.has(f));n.length=0,n.push(...d)}}let c=new Set;for(let l of i)for(let u of n)u!==l.sym&&u.lineStart>l.startRow&&u.lineEnd<=l.endRow&&(u.kind==="function"&&(u.kind="method"),l.sym.children.push(u),c.add(u));return{symbols:n.filter(l=>!c.has(l)),imports:s}}function ns(t,e,r){let n=r?Ur(r):Ft,s=xu(e,n),o=t.split(` `),i=zu(s,r);if(!i)return{filePath:e,language:s,symbols:[],imports:[],totalLines:o.length,foldedTokenEstimate:50};let c=Du(s,n),l=ju(c),u=e.slice(e.lastIndexOf("."))||".txt",d=(0,te.mkdtempSync)((0,Z.join)((0,Ui.tmpdir)(),"smart-src-")),f=(0,Z.join)(d,`source${u}`);(0,te.writeFileSync)(f,t);try{let p=CS(l,f,i),m=Uu(p,o,s),h=Ht({filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:0});return{filePath:e,language:s,symbols:m.symbols,imports:m.imports,totalLines:o.length,foldedTokenEstimate:Math.ceil(h.length/4)}}finally{(0,te.rmSync)(d,{recursive:!0,force:!0})}}function Fu(t,e){let r=new Map,n=e?Ur(e):Ft,s=new Map;for(let o of t){let i=xu(o.relativePath,n);s.has(i)||s.set(i,[]),s.get(i).push(o)}for(let[o,i]of s){let c=zu(o,e);if(!c){for(let p of i){let m=p.content.split(` `);r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:[],imports:[],totalLines:m.length,foldedTokenEstimate:50})}continue}let l=Du(o,n),u=ju(l),d=i.map(p=>p.absolutePath),f=qu(u,d,c);for(let p of i){let m=p.content.split(` `),h=f.get(p.absolutePath)||[],g=Uu(h,m,o),_=Ht({filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:0});r.set(p.relativePath,{filePath:p.relativePath,language:o,symbols:g.symbols,imports:g.imports,totalLines:m.length,foldedTokenEstimate:Math.ceil(_.length/4)})}}return r}function Ht(t){if(t.language==="markdown")return zS(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(Hu(r," "));return e.join(` `)}function zS(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 s=n.signature.match(/^(#{1,6})\s/),o=s?s[1].length:1,i=" ".repeat(o),c=`L${n.lineStart+1}`,l=`${i}${n.signature}`;e.push(`${l.padEnd(56)}${c}`)}else if(n.kind==="code"){let s=Ou(t.symbols,n.lineStart),o=" ".repeat(s+1),i=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,c=`${o}${n.signature}`;e.push(`${c.padEnd(56)}${i}`)}else if(n.kind==="metadata"){let s=n.lineStart===n.lineEnd?`L${n.lineStart+1}`:`L${n.lineStart+1}-${n.lineEnd+1}`,o=` ${n.signature}`;e.push(`${o.padEnd(56)}${s}`)}else if(n.kind==="reference"){let s=Ou(t.symbols,n.lineStart),o=" ".repeat(s+1),i=`L${n.lineStart+1}`,c=`${o}\u2197 ${n.name}`;e.push(`${c.padEnd(56)}${i}`)}return e.join(` `)}function Ou(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart{let u=l.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").trim();return u.length>0&&!u.startsWith("/**")});if(c){let l=c.replace(/^[\s*/]+/,"").replace(/^['"`]{3}/,"").replace(/['"`]{3}$/,"").trim();l&&r.push(`${e} \u{1F4AC} ${l}`)}}if(t.children&&t.children.length>0)for(let i of t.children)r.push(Hu(i,e+" "));return r.join(` `)}function LS(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 Wu(t,e,r){let n=ns(t,e),s=u=>{for(let d of u){if(d.name===r)return d;if(d.children){let f=s(d.children);if(f)return f}}return null},o=s(n.symbols);if(!o)return null;let i=t.split(` `);if(n.language==="markdown"&&o.kind==="section"){let u=o.signature.match(/^(#{1,6})\s/),d=u?u[1].length:1,f=o.lineStart,p=i.length-1;for(let h of n.symbols)if(h.kind==="section"&&h.lineStart>f){let g=h.signature.match(/^(#{1,6})\s/);if((g?g[1].length:1)<=d){for(p=h.lineStart-1;p>f&&i[p].trim()==="";)p--;break}}let m=i.slice(f,p+1).join(` `);return` ${m}`}let c=o.lineStart;for(let u=o.lineStart-1;u>=0;u--){let d=i[u].trim();if(d===""||d.startsWith("*")||d.startsWith("/**")||d.startsWith("///")||d.startsWith("//")||d.startsWith("#")||d.startsWith("@")||d==="*/")c=u;else break}let l=i.slice(c,o.lineEnd+1).join(` `);return`// \u{1F4CD} ${e} L${c+1}-${o.lineEnd+1} ${l}`}var Vu=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"]),qS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),US=512*1024;async function*Gu(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Wt.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 s){if(o.name.startsWith(".")&&o.name!=="."||qS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Gu(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Vu.has(c)||n&&n.has(c))&&(yield i)}}}async function FS(t){try{let e=await(0,Wt.stat)(t);if(e.size>US||e.size===0)return null;let r=await(0,Wt.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 Ku(t,e,r={}){let n=r.maxResults||20,s=e.toLowerCase(),o=s.split(/[\s_\-./]+/).filter(S=>S.length>0),i=r.projectRoot||t,c=Ur(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Vu.has(w)||l.add(w);let u=[];for await(let S of Gu(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Fr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await FS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Fu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=HS(w);let k=ss(S.toLowerCase(),o)>0,le=[],fe=(Gt,yt)=>{for(let W of Gt){let Ge=0,be="",Kt=ss(W.name.toLowerCase(),o);Kt>0&&(Ge+=Kt*3,be="name match"),W.signature.toLowerCase().includes(s)&&(Ge+=2,be=be?`${be} + signature`:"signature match"),W.jsdoc&&W.jsdoc.toLowerCase().includes(s)&&(Ge+=1,be=be?`${be} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:yt?`${yt}.${W.name}`:W.name,kind:W.kind,signature:W.signature,jsdoc:W.jsdoc,lineStart:W.lineStart,lineEnd:W.lineEnd,matchReason:be})),W.children&&fe(W.children,W.name)}};fe(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let C=ss(S.symbolName.toLowerCase(),o);return ss(w.symbolName.toLowerCase(),o)-C});let h=p.slice(0,n),g=new Set(h.map(S=>S.filePath)),_=f.filter(S=>g.has(S.filePath)).slice(0,n),E=_.reduce((S,w)=>S+w.foldedTokenEstimate,0);return{foldedFiles:_,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:m,tokenEstimate:E}}function ss(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let s=0,o=0;for(let i of n){let c=t.indexOf(i,s);c!==-1&&(o++,s=c+1)}o===n.length&&(r+=1)}return r}function HS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Yu(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 s=n.jsdoc.split(` `).find(o=>o.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ht(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 Hi=require("node:fs/promises"),os=require("node:fs"),Re=require("node:path"),Zu=require("node:os"),Xu=require("node:url"),tE={},WS="12.6.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var Qu=!1,ed=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Re.dirname)((0,Xu.fileURLToPath)(tE.url))}catch{return Qu=!0,process.cwd()}})(),Wi=(0,Re.resolve)(ed,"worker-service.cjs");function VS(){Qu&&((0,os.existsSync)(Wi)||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:Wi,mcpServerDir:ed}))}var Bu={search:"/api/search",timeline:"/api/timeline"};async function Fi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await ts(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function GS(t,e){let o=e.timeoutMs;if(o!==void 0)delete e.timeoutMs;let r=await ts(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),timeoutMs:o});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}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 Vt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await GS(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 KS(){try{return(await ts("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function YS(){if(await KS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),VS();try{let t=Oi(),e=await Cu(t,Wi);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 td=[{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 NEVER fetch full details without filtering first. 10x token savings.`,inputSchema:{type:"object",properties:{}},handler:async()=>({content:[{type:"text",text:`# Memory Search Workflow **3-Layer Pattern (ALWAYS follow this):** 1. **Search** - Get index of results with IDs \`search(query="...", limit=20, project="...")\` Returns: Table with IDs, titles, dates (~50-100 tokens/result) 2. **Timeline** - Get context around interesting results \`timeline(anchor=, depth_before=3, depth_after=3)\` Returns: Chronological context showing what was happening 3. **Fetch** - Get full details ONLY for relevant IDs \`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, 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"},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=Bu.search;return await Fi(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=Bu.timeline;return await Fi(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 Vt("/api/observations/batch",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,Re.resolve)(t.path||process.cwd()),r=await Ku(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:Yu(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,Re.resolve)(t.file_path),r=await(0,Hi.readFile)(e,"utf-8"),n=Wu(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let s=ns(r,e);if(s.symbols.length>0){let o=s.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: ${o}`}]}}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,Re.resolve)(t.file_path),r=await(0,Hi.readFile)(e,"utf-8"),n=ns(r,e);return n.symbols.length>0?{content:[{type:"text",text:Ht(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 Vt("/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 Fi("/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 Vt(`/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 Vt(`/api/corpus/${encodeURIComponent(e)}/query`,{...r,timeoutMs:60000})}},{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 Vt(`/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 Vt(`/api/corpus/${encodeURIComponent(e)}/reprime`,r)}}],Vi=new Kn({name:"codebuddy-mem",version:WS},{capabilities:{tools:{}}});Vi.setRequestHandler(ks,async()=>({tools:td.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Vi.setRequestHandler(nr,async t=>{let e=td.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 BS=3e4,Hr=null,Ju=!1;function is(){Wr("stdio-closed")}function rd(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Wr("stdio-error")}function JS(){process.stdin.on("end",is),process.stdin.on("close",is),process.stdin.on("error",rd)}function ZS(){process.stdin.off("end",is),process.stdin.off("close",is),process.stdin.off("error",rd)}function XS(){if(process.platform==="win32")return;let t=process.ppid;Hr=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(y.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),Wr())},BS),Hr.unref&&Hr.unref()}function Wr(t="shutdown"){Ju||(Ju=!0,Hr&&clearInterval(Hr),ZS(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Wr);process.on("SIGINT",Wr);function QS(){try{let t=(0,Zu.homedir)(),e=[(0,Re.resolve)(t,".claude","plugins","marketplaces","thedotmack"),(0,Re.resolve)(t,".config","claude","plugins","marketplaces","thedotmack")],r=e.some(i=>i&&(0,os.existsSync)(i)),n=[(0,Re.resolve)(t,".claude","plugins","cache","thedotmack","codebuddy-mem"),(0,Re.resolve)(t,".config","claude","plugins","cache","thedotmack","codebuddy-mem")],s=n.some(i=>i&&(0,os.existsSync)(i)),o=n[0];!r&&s&&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:o})}catch{}}async function eE(){let t=new Bn;JS(),await Vi.connect(t),y.info("SYSTEM","Claude-mem search server started"),QS(),XS(),setTimeout(async()=>{await YS()?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)}eE().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});