Files
JOUNGWOOK KWON 5a18f08e5f chore: merge upstream v12.4.7 + keep local fixes
Major upstream changes (v12.3.9 → v12.4.7):

v12.3.9 — Stop hook fire-and-forget (eliminates ~110s terminal block);
  hook port precedence; Telegram notifier; security_alert/security_note
  observation types

v12.4.0/12.4.1 — worker startup streamlined; consolidated DB connections;
  Chroma backfill watermark cache (422% CPU → 0% on restart)

v12.4.2 — context-overflow infinite loop fixed (clears memorySessionId
  on "Prompt is too long"); <task-notification> payload pollution blocked
  at hook + worker boundary

v12.4.3 — one-time pollution cleanup migration (CleanupV12_4_3):
  purges observer-sessions rows + cascade, stuck pending chains, Chroma
  rebuild; auto VACUUM INTO backup. Ran successfully on this DB:
  - 1463 observer-sessions purged
  - 3682 cascade rows
  - 102MB backup at ~/.claude-mem/backups/

v12.4.4 — stop draining queue on /clear (removes SessionEnd shim that
  had been abandoning pending observations for 6 months)

v12.4.5 — fix observation persistence on fresh installs (migration 28
  mirror in SessionStore)

v12.4.7 — cynical-deletion sweep (closes 27 issues); multi-account
  isolation via per-UID worker port (37700 + uid % 100, with explicit
  CLAUDE_MEM_WORKER_PORT override); CLAUDE_MEM_INTERNAL=1 trust boundary
  replaces cwd-based observer-session detection; observations.metadata
  column (migration 30); proxy env vars stripped from spawned subprocs

Local fixes preserved:
- env-sanitizer PATH extension for claude CLI lookup (auto-merged
  cleanly with upstream's new ENV_PROXY_VARS proxy stripping)
- SessionStore stale session reset (mac sleep / 4h wall-clock)

Settings: CLAUDE_MEM_WORKER_PORT=37777 explicit override preserved
through the per-UID port migration. Worker restarted to v12.4.7.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 18:13:22 +09:00

177 lines
230 KiB
JavaScript
Executable File

#!/usr/bin/env node
"use strict";var ad=Object.create;var Ji=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var ud=Object.getPrototypeOf,dd=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ld(e))!dd.call(t,s)&&s!==r&&Ji(t,s,{get:()=>e[s],enumerable:!(n=cd(e,s))||n.enumerable});return t};var se=(t,e,r)=>(r=t!=null?ad(ud(t)):{},fd(e||!t||!t.__esModule?Ji(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 nt=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=nt;var me=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 nt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};N._Code=me;N.nil=new me("");function ya(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Rs(r,e[n]),r.push(t[++n]);return new me(r)}N._=ya;var $s=new me("+");function _a(t,...e){let r=[cr(t[0])],n=0;for(;n<e.length;)r.push($s),Rs(r,e[n]),r.push($s,cr(t[++n]));return np(r),new me(r)}N.str=_a;function Rs(t,e){e instanceof me?t.push(...e._items):e instanceof nt?t.push(e):t.push(ip(e))}N.addCodeArg=Rs;function np(t){let e=1;for(;e<t.length-1;){if(t[e]===$s){let r=sp(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function sp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof nt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof nt))return`"${t}${e.slice(1)}`}function op(t,e){return e.emptyStr()?t:t.emptyStr()?e:_a`${t}${e}`}N.strConcat=op;function ip(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:cr(Array.isArray(t)?t.join(","):t)}function ap(t){return new me(cr(t))}N.stringify=ap;function cr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}N.safeStringify=cr;function cp(t){return typeof t=="string"&&N.IDENTIFIER.test(t)?new me(`.${t}`):ya`[${t}]`}N.getProperty=cp;function lp(t){if(typeof t=="string"&&N.IDENTIFIER.test(t))return new me(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}N.getEsmExportName=lp;function up(t){return new me(t.toString())}N.regexpCode=up});var Cs=b(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.ValueScope=ie.ValueScopeName=ie.Scope=ie.varKinds=ie.UsedValueState=void 0;var oe=lr(),Ms=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ln;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ln||(ie.UsedValueState=ln={}));ie.varKinds={const:new oe.Name("const"),let:new oe.Name("let"),var:new oe.Name("var")};var un=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof oe.Name?e:this.name(e)}name(e){return new oe.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}}};ie.Scope=un;var dn=class extends oe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,oe._)`.${new oe.Name(r)}[${n}]`}};ie.ValueScopeName=dn;var dp=(0,oe._)`\n`,As=class extends un{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?dp:oe.nil}}get(){return this._scope}name(e){return new dn(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,oe._)`${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=oe.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,ln.Started);let d=r(u);if(d){let f=this.opts.es5?ie.varKinds.var:ie.varKinds.const;o=(0,oe._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,oe._)`${o}${d}${this.opts._n}`;else throw new Ms(u);l.set(u,ln.Completed)})}return o}};ie.ValueScope=As});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(),we=Cs(),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 hn=Cs();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return hn.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return hn.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return hn.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return hn.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 je=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Os=class extends je{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?we.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=vt(this.rhs,e,r)),this}get names(){return this.rhs instanceof I._CodeOrName?this.rhs.names:{}}},fn=class extends je{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=vt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof I.Name?{}:{...this.lhs.names};return mn(e,this.rhs)}},Is=class extends fn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},xs=class extends je{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ds=class extends je{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ns=class extends je{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},zs=class extends je{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=vt(this.code,e,r),this}get names(){return this.code instanceof I._CodeOrName?this.code.names:{}}},ur=class extends je{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)||(fp(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>it(e,r.names),{})}},qe=class extends ur{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ls=class extends ur{},bt=class extends qe{};bt.kind="else";var st=class t extends qe{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 bt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Sa(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=vt(this.condition,e,r),this}get names(){let e=super.names;return mn(e,this.condition),this.else&&it(e,this.else.names),e}};st.kind="if";var ot=class extends qe{};ot.kind="for";var js=class extends ot{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=vt(this.iteration,e,r),this}get names(){return it(super.names,this.iteration.names)}},qs=class extends ot{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?we.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=mn(super.names,this.from);return mn(e,this.to)}},pn=class extends ot{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=vt(this.iterable,e,r),this}get names(){return it(super.names,this.iterable.names)}},dr=class extends qe{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 Us=class extends qe{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&&it(e,this.catch.names),this.finally&&it(e,this.finally.names),e}},pr=class extends qe{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};pr.kind="catch";var mr=class extends qe{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Fs=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
`:""},this._extScope=e,this._scope=new we.Scope({parent:e}),this._nodes=[new Ls]}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 Os(e,o,n)),o}const(e,r,n){return this._def(we.varKinds.const,e,r,n)}let(e,r,n){return this._def(we.varKinds.let,e,r,n)}var(e,r,n){return this._def(we.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new fn(e,r,n))}add(e,r){return this._leafNode(new Is(e,M.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==I.nil&&this._leafNode(new zs(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 st(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 st(e))}else(){return this._elseNode(new bt)}endIf(){return this._endBlockNode(st,bt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new js(e),r)}forRange(e,r,n,s,o=this.opts.es5?we.varKinds.var:we.varKinds.let){let i=this._scope.toName(e);return this._for(new qs(o,i,r,n),()=>s(i))}forOf(e,r,n,s=we.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 pn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?we.varKinds.var:we.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 pn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(ot)}label(e){return this._leafNode(new xs(e))}break(e){return this._leafNode(new Ds(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 Us;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 Ns(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 st))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=Fs;function it(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function mn(t,e){return e instanceof I._CodeOrName?it(t,e.names):t}function vt(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 fp(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Sa(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,I._)`!${Hs(t)}`}M.not=Sa;var pp=Ea(M.operators.AND);function mp(...t){return t.reduce(pp)}M.and=mp;var hp=Ea(M.operators.OR);function gp(...t){return t.reduce(hp)}M.or=gp;function Ea(t){return(e,r)=>e===I.nil?r:r===I.nil?e:(0,I._)`${Hs(e)} ${t} ${Hs(r)}`}function Hs(t){return t instanceof I.Name?t:(0,I._)`(${t})`}});var x=b(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var L=R(),yp=lr();function _p(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=_p;function Sp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(va(t,e),!ka(e,t.self.RULES.all))}C.alwaysValidSchema=Sp;function va(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]||$a(t,`unknown keyword: "${o}"`)}C.checkUnknownRules=va;function ka(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=ka;function Ep(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=Ep;function wp({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,L._)`${r}`}return(0,L._)`${t}${e}${(0,L.getProperty)(n)}`}C.schemaRefOrVal=wp;function bp(t){return Pa(decodeURIComponent(t))}C.unescapeFragment=bp;function vp(t){return encodeURIComponent(Vs(t))}C.escapeFragment=vp;function Vs(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Vs;function Pa(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=Pa;function kp(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=kp;function wa({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,c)=>{let l=i===void 0?o:i instanceof L.Name?(o instanceof L.Name?t(s,o,i):e(s,o,i),i):o instanceof L.Name?(e(s,i,o),o):r(o,i);return c===L.Name&&!(l instanceof L.Name)?n(s,l):l}}C.mergeEvaluated={props:wa({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,L._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,L._)`${r} || {}`).code((0,L._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,L._)`${r} || {}`),Gs(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ta}),items:wa({mergeNames:(t,e,r)=>t.if((0,L._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,L._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,L._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,L._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ta(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,L._)`{}`);return e!==void 0&&Gs(t,r,e),r}C.evaluatedPropsToName=Ta;function Gs(t,e,r){Object.keys(r).forEach(n=>t.assign((0,L._)`${e}${(0,L.getProperty)(n)}`,!0))}C.setEvaluated=Gs;var ba={};function Pp(t,e){return t.scopeValue("func",{ref:e,code:ba[e.code]||(ba[e.code]=new yp._Code(e.code))})}C.useFunc=Pp;var Ws;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ws||(C.Type=Ws={}));function Tp(t,e,r){if(t instanceof L.Name){let n=e===Ws.Num;return r?n?(0,L._)`"[" + ${t} + "]"`:(0,L._)`"['" + ${t} + "']"`:n?(0,L._)`"/" + ${t}`:(0,L._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,L.getProperty)(t).toString():"/"+Vs(t)}C.getErrorPath=Tp;function $a(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}C.checkStrictMode=$a});var Ue=b(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Z=R(),$p={data:new Z.Name("data"),valCxt:new Z.Name("valCxt"),instancePath:new Z.Name("instancePath"),parentData:new Z.Name("parentData"),parentDataProperty:new Z.Name("parentDataProperty"),rootData:new Z.Name("rootData"),dynamicAnchors:new Z.Name("dynamicAnchors"),vErrors:new Z.Name("vErrors"),errors:new Z.Name("errors"),this:new Z.Name("this"),self:new Z.Name("self"),scope:new Z.Name("scope"),json:new Z.Name("json"),jsonPos:new Z.Name("jsonPos"),jsonLen:new Z.Name("jsonLen"),jsonPart:new Z.Name("jsonPart")};Ks.default=$p});var hr=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.extendErrors=X.resetErrorsCount=X.reportExtraError=X.reportError=X.keyword$DataError=X.keywordError=void 0;var D=R(),gn=x(),te=Ue();X.keywordError={message:({keyword:t})=>(0,D.str)`must pass "${t}" keyword validation`};X.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 Rp(t,e=X.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:c}=s,l=Aa(t,e,r);n??(i||c)?Ra(o,l):Ma(s,(0,D._)`[${l}]`)}X.reportError=Rp;function Mp(t,e=X.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,c=Aa(t,e,r);Ra(s,c),o||i||Ma(n,te.default.vErrors)}X.reportExtraError=Mp;function Ap(t,e){t.assign(te.default.errors,e),t.if((0,D._)`${te.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,D._)`${te.default.vErrors}.length`,e),()=>t.assign(te.default.vErrors,null)))}X.resetErrorsCount=Ap;function Cp({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,te.default.errors,c=>{t.const(i,(0,D._)`${te.default.vErrors}[${c}]`),t.if((0,D._)`${i}.instancePath === undefined`,()=>t.assign((0,D._)`${i}.instancePath`,(0,D.strConcat)(te.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))})}X.extendErrors=Cp;function Ra(t,e){let r=t.const("err",e);t.if((0,D._)`${te.default.vErrors} === null`,()=>t.assign(te.default.vErrors,(0,D._)`[${r}]`),(0,D._)`${te.default.vErrors}.push(${r})`),t.code((0,D._)`${te.default.errors}++`)}function Ma(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 at={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 Aa(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,D._)`{}`:Op(t,e,r)}function Op(t,e,r={}){let{gen:n,it:s}=t,o=[Ip(s,r),xp(t,r)];return Dp(t,e,o),n.object(...o)}function Ip({errorPath:t},{instancePath:e}){let r=e?(0,D.str)`${t}${(0,gn.getErrorPath)(e,gn.Type.Str)}`:t;return[te.default.instancePath,(0,D.strConcat)(te.default.instancePath,r)]}function xp({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,gn.getErrorPath)(r,gn.Type.Str)}`),[at.schemaPath,s]}function Dp(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([at.keyword,s],[at.params,typeof e=="function"?e(t):e||(0,D._)`{}`]),l.messages&&n.push([at.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([at.schema,i],[at.parentSchema,(0,D._)`${d}${f}`],[te.default.data,o]),u&&n.push([at.propertyName,u])}});var Oa=b(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.boolOrEmptySchema=kt.topBoolOrEmptySchema=void 0;var Np=hr(),zp=R(),Lp=Ue(),jp={message:"boolean schema is false"};function qp(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ca(t,!1):typeof r=="object"&&r.$async===!0?e.return(Lp.default.data):(e.assign((0,zp._)`${n}.errors`,null),e.return(!0))}kt.topBoolOrEmptySchema=qp;function Up(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ca(t)):r.var(e,!0)}kt.boolOrEmptySchema=Up;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,Np.reportError)(s,jp,void 0,e)}});var Ys=b(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getRules=Pt.isJSONType=void 0;var Fp=["string","number","integer","boolean","null","object","array"],Hp=new Set(Fp);function Wp(t){return typeof t=="string"&&Hp.has(t)}Pt.isJSONType=Wp;function Vp(){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:{}}}Pt.getRules=Vp});var Js=b(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.shouldUseRule=Be.shouldUseGroup=Be.schemaHasRulesForType=void 0;function Gp({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ia(t,n)}Be.schemaHasRulesForType=Gp;function Ia(t,e){return e.rules.some(r=>xa(t,r))}Be.shouldUseGroup=Ia;function xa(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))}Be.shouldUseRule=xa});var gr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.reportTypeError=Q.checkDataTypes=Q.checkDataType=Q.coerceAndCheckDataType=Q.getJSONTypes=Q.getSchemaTypes=Q.DataType=void 0;var Kp=Ys(),Yp=Js(),Jp=hr(),$=R(),Da=x(),Tt;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Tt||(Q.DataType=Tt={}));function Bp(t){let e=Na(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}Q.getSchemaTypes=Bp;function Na(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Kp.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Q.getJSONTypes=Na;function Zp(t,e){let{gen:r,data:n,opts:s}=t,o=Xp(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,Yp.schemaHasRulesForType)(t,e[0]));if(i){let c=Zs(e,n,s.strictNumbers,Tt.Wrong);r.if(c,()=>{o.length?Qp(t,e,o):Xs(t)})}return i}Q.coerceAndCheckDataType=Zp;var za=new Set(["string","number","integer","boolean","null"]);function Xp(t,e){return e?t.filter(r=>za.has(r)||e==="array"&&r==="array"):[]}function Qp(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(Zs(e,s,o.strictNumbers),()=>n.assign(c,s))),n.if((0,$._)`${c} !== undefined`);for(let u of r)(za.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),Xs(t),n.endIf(),n.if((0,$._)`${c} !== undefined`,()=>{n.assign(s,c),em(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 em({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,$._)`${e} !== undefined`,()=>t.assign((0,$._)`${e}[${r}]`,n))}function Bs(t,e,r,n=Tt.Correct){let s=n===Tt.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===Tt.Correct?o:(0,$.not)(o);function i(c=$.nil){return(0,$.and)((0,$._)`typeof ${e} == "number"`,c,r?(0,$._)`isFinite(${e})`:$.nil)}}Q.checkDataType=Bs;function Zs(t,e,r,n){if(t.length===1)return Bs(t[0],e,r,n);let s,o=(0,Da.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,Bs(i,e,r,n));return s}Q.checkDataTypes=Zs;var tm={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,$._)`{type: ${t}}`:(0,$._)`{type: ${e}}`};function Xs(t){let e=rm(t);(0,Jp.reportError)(e,tm)}Q.reportTypeError=Xs;function rm(t){let{gen:e,data:r,schema:n}=t,s=(0,Da.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var ja=b(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.assignDefaults=void 0;var $t=R(),nm=x();function sm(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)La(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>La(t,o,s.default))}yn.assignDefaults=sm;function La(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let c=(0,$t._)`${o}${(0,$t.getProperty)(e)}`;if(s){(0,nm.checkStrictMode)(t,`default is ignored for: ${c}`);return}let l=(0,$t._)`${c} === undefined`;i.useDefaults==="empty"&&(l=(0,$t._)`${l} || ${c} === null || ${c} === ""`),n.if(l,(0,$t._)`${c} = ${(0,$t.stringify)(r)}`)}});var he=b(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.validateUnion=z.validateArray=z.usePattern=z.callValidateCode=z.schemaProperties=z.allSchemaProperties=z.noPropertyInData=z.propertyInData=z.isOwnProperty=z.hasPropFunc=z.reportMissingProp=z.checkMissingProp=z.checkReportMissingProp=void 0;var j=R(),Qs=x(),Ze=Ue(),om=x();function im(t,e){let{gen:r,data:n,it:s}=t;r.if(to(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,j._)`${e}`},!0),t.error()})}z.checkReportMissingProp=im;function am({gen:t,data:e,it:{opts:r}},n,s){return(0,j.or)(...n.map(o=>(0,j.and)(to(t,e,o,r.ownProperties),(0,j._)`${s} = ${o}`)))}z.checkMissingProp=am;function cm(t,e){t.setParams({missingProperty:e},!0),t.error()}z.reportMissingProp=cm;function qa(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,j._)`Object.prototype.hasOwnProperty`})}z.hasPropFunc=qa;function eo(t,e,r){return(0,j._)`${qa(t)}.call(${e}, ${r})`}z.isOwnProperty=eo;function lm(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} !== undefined`;return n?(0,j._)`${s} && ${eo(t,e,r)}`:s}z.propertyInData=lm;function to(t,e,r,n){let s=(0,j._)`${e}${(0,j.getProperty)(r)} === undefined`;return n?(0,j.or)(s,(0,j.not)(eo(t,e,r))):s}z.noPropertyInData=to;function Ua(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}z.allSchemaProperties=Ua;function um(t,e){return Ua(e).filter(r=>!(0,Qs.alwaysValidSchema)(t,e[r]))}z.schemaProperties=um;function dm({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},c,l,u){let d=u?(0,j._)`${t}, ${e}, ${n}${s}`:e,f=[[Ze.default.instancePath,(0,j.strConcat)(Ze.default.instancePath,o)],[Ze.default.parentData,i.parentData],[Ze.default.parentDataProperty,i.parentDataProperty],[Ze.default.rootData,Ze.default.rootData]];i.opts.dynamicRef&&f.push([Ze.default.dynamicAnchors,Ze.default.dynamicAnchors]);let p=(0,j._)`${d}, ${r.object(...f)}`;return l!==j.nil?(0,j._)`${c}.call(${l}, ${p})`:(0,j._)`${c}(${p})`}z.callValidateCode=dm;var fm=(0,j._)`new RegExp`;function pm({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,j._)`${s.code==="new RegExp"?fm:(0,om.useFunc)(t,s)}(${r}, ${n})`})}z.usePattern=pm;function mm(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,j._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Qs.Type.Num},o),e.if((0,j.not)(o),c)})}}z.validateArray=mm;function hm(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,Qs.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,j._)`${i} || ${c}`),t.mergeValidEvaluated(d,c)||e.if((0,j.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}z.validateUnion=hm});var Wa=b(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.validateKeywordUsage=Te.validSchemaType=Te.funcKeywordCode=Te.macroKeywordCode=void 0;var re=R(),ct=Ue(),gm=he(),ym=hr();function _m(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,c=e.macro.call(i.self,s,o,i),l=Ha(r,n,c);i.opts.validateSchema!==!1&&i.self.validateSchema(c,!0);let u=r.name("valid");t.subschema({schema:c,schemaPath:re.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Te.macroKeywordCode=_m;function Sm(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:c,it:l}=t;wm(l,e);let u=!c&&e.compile?e.compile.call(l.self,o,i,l):e.validate,d=Ha(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&&Fa(t),_(()=>t.error());else{let E=e.async?m():h();e.modifying&&Fa(t),_(()=>Em(t,E))}}function m(){let E=n.let("ruleErrs",null);return n.try(()=>g((0,re._)`await `),S=>n.assign(f,!1).if((0,re._)`${S} instanceof ${l.ValidationError}`,()=>n.assign(E,(0,re._)`${S}.errors`),()=>n.throw(S))),E}function h(){let E=(0,re._)`${d}.errors`;return n.assign(E,null),g(re.nil),E}function g(E=e.async?(0,re._)`await `:re.nil){let S=l.opts.passContext?ct.default.this:ct.default.self,w=!("compile"in e&&!c||e.schema===!1);n.assign(f,(0,re._)`${E}${(0,gm.callValidateCode)(t,d,S,w)}`,e.modifying)}function _(E){var S;n.if((0,re.not)((S=e.valid)!==null&&S!==void 0?S:f),E)}}Te.funcKeywordCode=Sm;function Fa(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,re._)`${n.parentData}[${n.parentDataProperty}]`))}function Em(t,e){let{gen:r}=t;r.if((0,re._)`Array.isArray(${e})`,()=>{r.assign(ct.default.vErrors,(0,re._)`${ct.default.vErrors} === null ? ${e} : ${ct.default.vErrors}.concat(${e})`).assign(ct.default.errors,(0,re._)`${ct.default.vErrors}.length`),(0,ym.extendErrors)(t)},()=>t.error())}function wm({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ha(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,re.stringify)(r)})}function bm(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")}Te.validSchemaType=bm;function vm({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)}}Te.validateKeywordUsage=vm});var Ga=b(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.extendSubschemaMode=Xe.extendSubschemaData=Xe.getSubschema=void 0;var $e=R(),Va=x();function km(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,$e._)`${t.schemaPath}${(0,$e.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:c[r],schemaPath:(0,$e._)`${t.schemaPath}${(0,$e.getProperty)(e)}${(0,$e.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Va.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')}Xe.getSubschema=km;function Pm(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,$e._)`${e.data}${(0,$e.getProperty)(r)}`,!0);l(p),t.errorPath=(0,$e.str)`${u}${(0,Va.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,$e._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof $e.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]}}Xe.extendSubschemaData=Pm;function Tm(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}Xe.extendSubschemaMode=Tm});var ro=b((lv,Ka)=>{"use strict";Ka.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 Ja=b((uv,Ya)=>{"use strict";var Qe=Ya.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(){};_n(e,n,s,t,"",t)};Qe.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Qe.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Qe.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Qe.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 _n(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 Qe.arrayKeywords)for(var p=0;p<f.length;p++)_n(t,e,r,f[p],s+"/"+d+"/"+p,o,s,d,n,p)}else if(d in Qe.propsKeywords){if(f&&typeof f=="object")for(var m in f)_n(t,e,r,f[m],s+"/"+d+"/"+$m(m),o,s,d,n,m)}else(d in Qe.keywords||t.allKeys&&!(d in Qe.skipKeywords))&&_n(t,e,r,f,s+"/"+d,o,s,d,n)}r(n,s,o,i,c,l,u)}}function $m(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var yr=b(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.getSchemaRefs=ae.resolveUrl=ae.normalizeId=ae._getFullPath=ae.getFullPath=ae.inlineRef=void 0;var Rm=x(),Mm=ro(),Am=Ja(),Cm=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Om(t,e=!0){return typeof t=="boolean"?!0:e===!0?!no(t):e?Ba(t)<=e:!1}ae.inlineRef=Om;var Im=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function no(t){for(let e in t){if(Im.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(no)||typeof r=="object"&&no(r))return!0}return!1}function Ba(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Cm.has(r)&&(typeof t[r]=="object"&&(0,Rm.eachItem)(t[r],n=>e+=Ba(n)),e===1/0))return 1/0}return e}function Za(t,e="",r){r!==!1&&(e=Rt(e));let n=t.parse(e);return Xa(t,n)}ae.getFullPath=Za;function Xa(t,e){return t.serialize(e).split("#")[0]+"#"}ae._getFullPath=Xa;var xm=/#\/?$/;function Rt(t){return t?t.replace(xm,""):""}ae.normalizeId=Rt;function Dm(t,e,r){return r=Rt(r),t.resolve(e,r)}ae.resolveUrl=Dm;var Nm=/^[a-z_][-a-z0-9._]*$/i;function zm(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Rt(t[r]||e),o={"":s},i=Za(n,s,!1),c={},l=new Set;return Am(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 A=this.opts.uriResolver.resolve;if(w=Rt(_?A(_,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!==Rt(g)&&(w[0]==="#"?(u(f,c[w],w),c[w]=f):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!Nm.test(w))throw new Error(`invalid anchor "${w}"`);E.call(this,`#${w}`)}}}),c;function u(f,p,m){if(p!==void 0&&!Mm(f,p))throw d(m)}function d(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ae.getSchemaRefs=zm});var Er=b(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getData=et.KeywordCxt=et.validateFunctionCode=void 0;var nc=Oa(),Qa=gr(),oo=Js(),Sn=gr(),Lm=ja(),Sr=Wa(),so=Ga(),v=R(),P=Ue(),jm=yr(),Fe=x(),_r=hr();function qm(t){if(ic(t)&&(ac(t),oc(t))){Hm(t);return}sc(t,()=>(0,nc.topBoolOrEmptySchema)(t))}et.validateFunctionCode=qm;function sc({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"; ${ec(r,s)}`),Fm(t,s),t.code(o)}):t.func(e,(0,v._)`${P.default.data}, ${Um(s)}`,n.$async,()=>t.code(ec(r,s)).code(o))}function Um(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 Fm(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 Hm(t){let{schema:e,opts:r,gen:n}=t;sc(t,()=>{r.$comment&&e.$comment&&lc(t),Ym(t),n.let(P.default.vErrors,null),n.let(P.default.errors,0),r.unevaluated&&Wm(t),cc(t),Zm(t)})}function Wm(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 ec(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 Vm(t,e){if(ic(t)&&(ac(t),oc(t))){Gm(t,e);return}(0,nc.boolOrEmptySchema)(t,e)}function oc({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 ic(t){return typeof t.schema!="boolean"}function Gm(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&lc(t),Jm(t),Bm(t);let o=n.const("_errs",P.default.errors);cc(t,o),n.var(e,(0,v._)`${o} === ${P.default.errors}`)}function ac(t){(0,Fe.checkUnknownRules)(t),Km(t)}function cc(t,e){if(t.opts.jtd)return tc(t,[],!1,e);let r=(0,Qa.getSchemaTypes)(t.schema),n=(0,Qa.coerceAndCheckDataType)(t,r);tc(t,r,!n,e)}function Km(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Fe.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Ym(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Fe.checkStrictMode)(t,"default is ignored in the schema root")}function Jm(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,jm.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Bm(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function lc({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 Zm(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&&Xm(t),e.return((0,v._)`${P.default.errors} === 0`))}function Xm({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 tc(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,Fe.schemaHasRulesButRef)(o,d))){s.block(()=>dc(t,"$ref",d.all.$ref.definition));return}l.jtd||Qm(t,e),s.block(()=>{for(let p of d.rules)f(p);f(d.post)});function f(p){(0,oo.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Sn.checkDataType)(p.type,i,l.strictNumbers)),rc(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Sn.reportTypeError)(t)),s.endIf()):rc(t,p),c||s.if((0,v._)`${P.default.errors} === ${n||0}`))}}function rc(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,Lm.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,oo.shouldUseRule)(n,o)&&dc(t,o.keyword,o.definition,e.type)})}function Qm(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(eh(t,e),t.opts.allowUnionTypes||th(t,e),rh(t,t.dataTypes))}function eh(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{uc(t.dataTypes,r)||io(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),sh(t,e)}}function th(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&io(t,"use allowUnionTypes to allow union type keyword")}function rh(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,oo.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>nh(e,i))&&io(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function nh(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function uc(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function sh(t,e){let r=[];for(let n of t.dataTypes)uc(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function io(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Fe.checkStrictMode)(t,e,t.opts.strictTypes)}var En=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,Fe.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",fc(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,Sn.checkDataTypes)(l,r,o.opts.strictNumbers,Sn.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,so.getSubschema)(this.it,e);(0,so.extendSubschemaData)(n,this.it,e),(0,so.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Vm(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Fe.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Fe.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}};et.KeywordCxt=En;function dc(t,e,r,n){let s=new En(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 oh=/^\/(?:[^~]|~0|~1)*$/,ih=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fc(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!oh.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=P.default.rootData}else{let u=ih.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,Fe.unescapeJsonPointer)(u))}`,i=(0,v._)`${i} && ${o}`);return i;function l(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}et.getData=fc});var wn=b(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var ao=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};co.default=ao});var wr=b(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});var lo=yr(),uo=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,lo.resolveUrl)(e,r,n),this.missingSchema=(0,lo.normalizeId)((0,lo.getFullPath)(e,this.missingRef))}};fo.default=uo});var vn=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.resolveSchema=ge.getCompilingSchema=ge.resolveRef=ge.compileSchema=ge.SchemaEnv=void 0;var be=R(),ah=wn(),lt=Ue(),ve=yr(),pc=x(),ch=Er(),Mt=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,ve.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ge.SchemaEnv=Mt;function mo(t){let e=mc.call(this,t);if(e)return e;let r=(0,ve.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new be.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),c;t.$async&&(c=i.scopeValue("Error",{ref:ah.default,code:(0,be._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:lt.default.data,parentData:lt.default.parentData,parentDataProperty:lt.default.parentDataProperty,dataNames:[lt.default.data],dataPathArr:[be.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,be.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:c,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:be.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,be._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,ch.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();d=`${i.scopeRefs(lt.default.scope)}return ${f}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let m=new Function(`${lt.default.self}`,`${lt.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 be.Name?void 0:h,items:g instanceof be.Name?void 0:g,dynamicProps:h instanceof be.Name,dynamicItems:g instanceof be.Name},m.source&&(m.source.evaluated=(0,be.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)}}ge.compileSchema=mo;function lh(t,e,r){var n;r=(0,ve.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=fh.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 Mt({schema:i,schemaId:c,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=uh.call(this,o)}ge.resolveRef=lh;function uh(t){return(0,ve.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:mo.call(this,t)}function mc(t){for(let e of this._compilations)if(dh(e,t))return e}ge.getCompilingSchema=mc;function dh(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function fh(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||bn.call(this,t,e)}function bn(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ve._getFullPath)(this.opts.uriResolver,r),s=(0,ve.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return po.call(this,r,t);let o=(0,ve.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let c=bn.call(this,t,i);return typeof c?.schema!="object"?void 0:po.call(this,r,c)}if(typeof i?.schema=="object"){if(i.validate||mo.call(this,i),o===(0,ve.normalizeId)(e)){let{schema:c}=i,{schemaId:l}=this.opts,u=c[l];return u&&(s=(0,ve.resolveUrl)(this.opts.uriResolver,s,u)),new Mt({schema:c,schemaId:l,root:t,baseId:s})}return po.call(this,r,i)}}ge.resolveSchema=bn;var ph=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function po(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,pc.unescapeFragment)(c)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!ph.has(c)&&u&&(e=(0,ve.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,pc.schemaHasRulesButRef)(r,this.RULES)){let c=(0,ve.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=bn.call(this,n,c)}let{schemaId:i}=this.opts;if(o=o||new Mt({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var hc=b((gv,mh)=>{mh.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 go=b((yv,Sc)=>{"use strict";var hh=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),yc=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 ho(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var gh=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gc(t){return t.length=0,!0}function yh(t,e,r){if(t.length){let n=ho(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function _h(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,c=yh;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!c(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!c(s,n,r))break;c=gc}else{s.push(u);continue}}return s.length&&(c===gc?r.zone=s.join(""):i?n.push(s.join("")):n.push(ho(s))),r.address=n.join(""),r}function _c(t){if(Sh(t,":")<2)return{host:t,isIPV6:!1};let e=_h(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 Sh(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Eh(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function wh(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function bh(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!yc(r)){let n=_c(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Sc.exports={nonSimpleDomain:gh,recomposeAuthority:bh,normalizeComponentEncoding:wh,removeDotSegments:Eh,isIPv4:yc,isUUID:hh,normalizeIPv6:_c,stringArrayToHexStripped:ho}});var kc=b((_v,vc)=>{"use strict";var{isUUID:vh}=go(),kh=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ph=["http","https","ws","wss","urn","urn:uuid"];function Th(t){return Ph.indexOf(t)!==-1}function yo(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 Ec(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function wc(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 $h(t){return t.secure=yo(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Rh(t){if((t.port===(yo(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 Mh(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(kh);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=_o(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Ah(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=_o(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 Ch(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!vh(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Oh(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var bc={scheme:"http",domainHost:!0,parse:Ec,serialize:wc},Ih={scheme:"https",domainHost:bc.domainHost,parse:Ec,serialize:wc},kn={scheme:"ws",domainHost:!0,parse:$h,serialize:Rh},xh={scheme:"wss",domainHost:kn.domainHost,parse:kn.parse,serialize:kn.serialize},Dh={scheme:"urn",parse:Mh,serialize:Ah,skipNormalize:!0},Nh={scheme:"urn:uuid",parse:Ch,serialize:Oh,skipNormalize:!0},Pn={http:bc,https:Ih,ws:kn,wss:xh,urn:Dh,"urn:uuid":Nh};Object.setPrototypeOf(Pn,null);function _o(t){return t&&(Pn[t]||Pn[t.toLowerCase()])||void 0}vc.exports={wsIsSecure:yo,SCHEMES:Pn,isValidSchemeName:Th,getSchemeHandler:_o}});var $c=b((Sv,$n)=>{"use strict";var{normalizeIPv6:zh,removeDotSegments:br,recomposeAuthority:Lh,normalizeComponentEncoding:Tn,isIPv4:jh,nonSimpleDomain:qh}=go(),{SCHEMES:Uh,getSchemeHandler:Pc}=kc();function Fh(t,e){return typeof t=="string"?t=Re(He(t,e),e):typeof t=="object"&&(t=He(Re(t,e),e)),t}function Hh(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Tc(He(t,n),He(e,n),n,!0);return n.skipEscape=!0,Re(s,n)}function Tc(t,e,r,n){let s={};return n||(t=He(Re(t,r),r),e=He(Re(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 Wh(t,e,r){return typeof t=="string"?(t=unescape(t),t=Re(Tn(He(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Re(Tn(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Re(Tn(He(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Re(Tn(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Re(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=Pc(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=Lh(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 Vh=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function He(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(Vh);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(jh(n.host)===!1){let l=zh(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=Pc(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&qh(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 So={SCHEMES:Uh,normalize:Fh,resolve:Hh,resolveComponent:Tc,equal:Wh,serialize:Re,parse:He};$n.exports=So;$n.exports.default=So;$n.exports.fastUri=So});var Mc=b(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var Rc=$c();Rc.code='require("ajv/dist/runtime/uri").default';Eo.default=Rc});var zc=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=void 0;var Gh=Er();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return Gh.KeywordCxt}});var At=R();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return At._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return At.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return At.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return At.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return At.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return At.CodeGen}});var Kh=wn(),xc=wr(),Yh=Ys(),vr=vn(),Jh=R(),kr=yr(),Rn=gr(),bo=x(),Ac=hc(),Bh=Mc(),Dc=(t,e)=>new RegExp(t,e);Dc.code="new RegExp";var Zh=["removeAdditional","useDefaults","coerceTypes"],Xh=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Qh={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."},eg={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Cc=200;function tg(t){var e,r,n,s,o,i,c,l,u,d,f,p,m,h,g,_,E,S,w,A,k,le,de,Gt,gt;let H=t.strict,Ve=(e=t.code)===null||e===void 0?void 0:e.optimize,Ee=Ve===!0||Ve===void 0?1:Ve||0,Kt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Dc,id=(s=t.uriResolver)!==null&&s!==void 0?s:Bh.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:H)!==null&&i!==void 0?i:!0,strictNumbers:(l=(c=t.strictNumbers)!==null&&c!==void 0?c:H)!==null&&l!==void 0?l:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:H)!==null&&d!==void 0?d:"log",strictTuples:(p=(f=t.strictTuples)!==null&&f!==void 0?f:H)!==null&&p!==void 0?p:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:H)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Ee,regExp:Kt}:{optimize:Ee,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:(A=t.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(le=t.validateSchema)!==null&&le!==void 0?le:!0,validateFormats:(de=t.validateFormats)!==null&&de!==void 0?de:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(gt=t.int32range)!==null&&gt!==void 0?gt:!0,uriResolver:id}}var Pr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...tg(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Jh.ValueScope({scope:{},prefixes:Xh,es5:r,lines:n}),this.logger=ag(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Yh.getRules)(),Oc.call(this,Qh,e,"NOT SUPPORTED"),Oc.call(this,eg,e,"DEPRECATED","warn"),this._metaOpts=og.call(this),e.formats&&ng.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&sg.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),rg.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Ac;n==="id"&&(s={...Ac},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 xc.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=Ic.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=Ic.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(lg.call(this,n,r),!r)return(0,bo.eachItem)(n,o=>wo.call(this,o)),this;dg.call(this,r);let s={...r,type:(0,Rn.getJSONTypes)(r.type),schemaType:(0,Rn.getJSONTypes)(r.schemaType)};return(0,bo.eachItem)(n,s.type.length===0?o=>wo.call(this,o,s):o=>s.type.forEach(i=>wo.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]=Nc(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=Kh.default;Pr.MissingRefError=xc.default;Y.default=Pr;function Oc(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 Ic(t){return t=(0,kr.normalizeId)(t),this.schemas[t]||this.refs[t]}function rg(){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 ng(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function sg(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 og(){let t={...this.opts};for(let e of Zh)delete t[e];return t}var ig={log(){},warn(){},error(){}};function ag(t){if(t===!1)return ig;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 cg=/^[a-z_$][a-z0-9_$:-]*$/i;function lg(t,e){let{RULES:r}=this;if((0,bo.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!cg.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 wo(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,Rn.getJSONTypes)(e.type),schemaType:(0,Rn.getJSONTypes)(e.schemaType)}};e.before?ug.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 ug(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 dg(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Nc(e)),t.validateSchema=this.compile(e,!0))}var fg={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Nc(t){return{anyOf:[t,fg]}}});var Lc=b(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});var pg={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vo.default=pg});var Fc=b(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.callRef=ut.getValidate=void 0;var mg=wr(),jc=he(),ce=R(),Ct=Ue(),qc=vn(),Mn=x(),hg={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=qc.resolveRef.call(l,u,s,r);if(d===void 0)throw new mg.default(n.opts.uriResolver,s,r);if(d instanceof qc.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,ce._)`${h}.validate`,u,u.$async)}function p(h){let g=Uc(t,h);An(t,g,h,h.$async)}function m(h){let g=e.scopeValue("schema",c.code.source===!0?{ref:h,code:(0,ce.stringify)(h)}:{ref:h}),_=e.name("valid"),E=t.subschema({schema:h,dataTypes:[],schemaPath:ce.nil,topSchemaRef:g,errSchemaPath:r},_);t.mergeEvaluated(E),t.ok(_)}}};function Uc(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ce._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ut.getValidate=Uc;function An(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:c,opts:l}=o,u=l.passContext?Ct.default.this:ce.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,ce._)`await ${(0,jc.callValidateCode)(t,e,u)}`),m(e),i||s.assign(h,!0)},g=>{s.if((0,ce._)`!(${g} instanceof ${o.ValidationError})`,()=>s.throw(g)),p(g),i||s.assign(h,!1)}),t.ok(h)}function f(){t.result((0,jc.callValidateCode)(t,e,u),()=>m(e),()=>p(e))}function p(h){let g=(0,ce._)`${h}.errors`;s.assign(Ct.default.vErrors,(0,ce._)`${Ct.default.vErrors} === null ? ${g} : ${Ct.default.vErrors}.concat(${g})`),s.assign(Ct.default.errors,(0,ce._)`${Ct.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=Mn.mergeEvaluated.props(s,_.props,o.props));else{let E=s.var("props",(0,ce._)`${h}.evaluated.props`);o.props=Mn.mergeEvaluated.props(s,E,o.props,ce.Name)}if(o.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(o.items=Mn.mergeEvaluated.items(s,_.items,o.items));else{let E=s.var("items",(0,ce._)`${h}.evaluated.items`);o.items=Mn.mergeEvaluated.items(s,E,o.items,ce.Name)}}}ut.callRef=An;ut.default=hg});var Hc=b(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var gg=Lc(),yg=Fc(),_g=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gg.default,yg.default];ko.default=_g});var Wc=b(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});var Cn=R(),tt=Cn.operators,On={maximum:{okStr:"<=",ok:tt.LTE,fail:tt.GT},minimum:{okStr:">=",ok:tt.GTE,fail:tt.LT},exclusiveMaximum:{okStr:"<",ok:tt.LT,fail:tt.GTE},exclusiveMinimum:{okStr:">",ok:tt.GT,fail:tt.LTE}},Sg={message:({keyword:t,schemaCode:e})=>(0,Cn.str)`must be ${On[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Cn._)`{comparison: ${On[t].okStr}, limit: ${e}}`},Eg={keyword:Object.keys(On),type:"number",schemaType:"number",$data:!0,error:Sg,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Cn._)`${r} ${On[e].fail} ${n} || isNaN(${r})`)}};Po.default=Eg});var Vc=b(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var Tr=R(),wg={message:({schemaCode:t})=>(0,Tr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Tr._)`{multipleOf: ${t}}`},bg={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wg,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}))`)}};To.default=bg});var Kc=b($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});function Gc(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}$o.default=Gc;Gc.code='require("ajv/dist/runtime/ucs2length").default'});var Yc=b(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});var dt=R(),vg=x(),kg=Kc(),Pg={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,dt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,dt._)`{limit: ${t}}`},Tg={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Pg,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?dt.operators.GT:dt.operators.LT,i=s.opts.unicode===!1?(0,dt._)`${r}.length`:(0,dt._)`${(0,vg.useFunc)(t.gen,kg.default)}(${r})`;t.fail$data((0,dt._)`${i} ${o} ${n}`)}};Ro.default=Tg});var Jc=b(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var $g=he(),Rg=x(),Ot=R(),Mg={message:({schemaCode:t})=>(0,Ot.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ot._)`{pattern: ${t}}`},Ag={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Mg,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,Ot._)`new RegExp`:(0,Rg.useFunc)(e,l),d=e.let("valid");e.try(()=>e.assign(d,(0,Ot._)`${u}(${o}, ${c}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ot._)`!${d}`)}else{let l=(0,$g.usePattern)(t,s);t.fail$data((0,Ot._)`!${l}.test(${r})`)}}};Mo.default=Ag});var Bc=b(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});var $r=R(),Cg={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}}`},Og={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Cg,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}`)}};Ao.default=Og});var Zc=b(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var Rr=he(),Mr=R(),Ig=x(),xg={message:({params:{missingProperty:t}})=>(0,Mr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mr._)`{missingProperty: ${t}}`},Dg={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xg,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,Ig.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)}}};Co.default=Dg});var Xc=b(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Ar=R(),Ng={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ar.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},zg={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Ng,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`${r}.length ${s} ${n}`)}};Oo.default=zg});var In=b(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Qc=ro();Qc.code='require("ajv/dist/runtime/equal").default';Io.default=Qc});var el=b(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});var xo=gr(),J=R(),Lg=x(),jg=In(),qg={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}}`},Ug={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:qg,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,xo.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,xo.checkDataTypes)(u,_,c.opts.strictNumbers,xo.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,Lg.useFunc)(e,jg.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)})))}}};Do.default=Ug});var tl=b(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});var No=R(),Fg=x(),Hg=In(),Wg={message:"must be equal to constant",params:({schemaCode:t})=>(0,No._)`{allowedValue: ${t}}`},Vg={keyword:"const",$data:!0,error:Wg,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,No._)`!${(0,Fg.useFunc)(e,Hg.default)}(${r}, ${s})`):t.fail((0,No._)`${o} !== ${r}`)}};zo.default=Vg});var rl=b(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});var Cr=R(),Gg=x(),Kg=In(),Yg={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Cr._)`{allowedValues: ${t}}`},Jg={keyword:"enum",schemaType:"array",$data:!0,error:Yg,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,Gg.useFunc)(e,Kg.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,Cr.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,Cr._)`${u()}(${r}, ${m})`,()=>e.assign(d,!0).break()))}function p(m,h){let g=s[h];return typeof g=="object"&&g!==null?(0,Cr._)`${u()}(${r}, ${m}[${h}])`:(0,Cr._)`${r} === ${g}`}}};Lo.default=Jg});var nl=b(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});var Bg=Wc(),Zg=Vc(),Xg=Yc(),Qg=Jc(),ey=Bc(),ty=Zc(),ry=Xc(),ny=el(),sy=tl(),oy=rl(),iy=[Bg.default,Zg.default,Xg.default,Qg.default,ey.default,ty.default,ry.default,ny.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sy.default,oy.default];jo.default=iy});var Uo=b(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateAdditionalItems=void 0;var ft=R(),qo=x(),ay={message:({params:{len:t}})=>(0,ft.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ft._)`{limit: ${t}}`},cy={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ay,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,qo.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}sl(t,n)}};function sl(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let c=r.const("len",(0,ft._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ft._)`${c} <= ${e.length}`);else if(typeof n=="object"&&!(0,qo.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ft._)`${c} <= ${e.length}`);r.if((0,ft.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,c,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:qo.Type.Num},u),i.allErrors||r.if((0,ft.not)(u),()=>r.break())})}}Or.validateAdditionalItems=sl;Or.default=cy});var Fo=b(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var ol=R(),xn=x(),ly=he(),uy={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return il(t,"additionalItems",e);r.items=!0,!(0,xn.alwaysValidSchema)(r,e)&&t.ok((0,ly.validateArray)(t))}};function il(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=xn.mergeEvaluated.items(n,r.length,c.items));let l=n.name("valid"),u=n.const("len",(0,ol._)`${o}.length`);r.forEach((f,p)=>{(0,xn.alwaysValidSchema)(c,f)||(n.if((0,ol._)`${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,xn.checkStrictMode)(c,_,p.strictTuples)}}}Ir.validateTuple=il;Ir.default=uy});var al=b(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});var dy=Fo(),fy={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,dy.validateTuple)(t,"items")};Ho.default=fy});var ll=b(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});var cl=R(),py=x(),my=he(),hy=Uo(),gy={message:({params:{len:t}})=>(0,cl.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cl._)`{limit: ${t}}`},yy={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gy,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,py.alwaysValidSchema)(n,e)&&(s?(0,hy.validateAdditionalItems)(t,s):t.ok((0,my.validateArray)(t)))}};Wo.default=yy});var ul=b(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var ye=R(),Dn=x(),_y={message:({params:{min:t,max:e}})=>e===void 0?(0,ye.str)`must contain at least ${t} valid item(s)`:(0,ye.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ye._)`{minContains: ${t}}`:(0,ye._)`{minContains: ${t}, maxContains: ${e}}`},Sy={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:_y,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,ye._)`${s}.length`);if(t.setParams({min:i,max:c}),c===void 0&&i===0){(0,Dn.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&i>c){(0,Dn.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Dn.alwaysValidSchema)(o,r)){let g=(0,ye._)`${d} >= ${i}`;c!==void 0&&(g=(0,ye._)`${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,ye._)`${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:Dn.Type.Num,compositeRule:!0},g),_()})}function h(g){e.code((0,ye._)`${g}++`),c===void 0?e.if((0,ye._)`${g} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,ye._)`${g} > ${c}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,ye._)`${g} >= ${i}`,()=>e.assign(f,!0)))}}};Vo.default=Sy});var pl=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.validateSchemaDeps=Me.validatePropertyDeps=Me.error=void 0;var Go=R(),Ey=x(),xr=he();Me.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Go.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Go._)`{property: ${t},
missingProperty: ${n},
depsCount: ${e},
deps: ${r}}`};var wy={keyword:"dependencies",type:"object",schemaType:"object",error:Me.error,code(t){let[e,r]=by(t);dl(t,e),fl(t,r)}};function by({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 dl(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,Go._)`${l} && (${(0,xr.checkMissingProp)(t,c,o)})`),(0,xr.reportMissingProp)(t,o),r.else())}}Me.validatePropertyDeps=dl;function fl(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let c in e)(0,Ey.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))}Me.validateSchemaDeps=fl;Me.default=wy});var hl=b(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var ml=R(),vy=x(),ky={message:"property name must be valid",params:({params:t})=>(0,ml._)`{propertyName: ${t.propertyName}}`},Py={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ky,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,vy.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,ml.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Ko.default=Py});var Jo=b(Yo=>{"use strict";Object.defineProperty(Yo,"__esModule",{value:!0});var Nn=he(),ke=R(),Ty=Ue(),zn=x(),$y={message:"must NOT have additional properties",params:({params:t})=>(0,ke._)`{additionalProperty: ${t.additionalProperty}}`},Ry={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$y,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,zn.alwaysValidSchema)(i,r))return;let u=(0,Nn.allSchemaProperties)(n.properties),d=(0,Nn.allSchemaProperties)(n.patternProperties);f(),t.ok((0,ke._)`${o} === ${Ty.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,zn.schemaRefOrVal)(i,n.properties,"properties");E=(0,Nn.isOwnProperty)(e,S,_)}else u.length?E=(0,ke.or)(...u.map(S=>(0,ke._)`${_} === ${S}`)):E=ke.nil;return d.length&&(E=(0,ke.or)(E,...d.map(S=>(0,ke._)`${(0,Nn.usePattern)(t,S)}.test(${_})`))),(0,ke.not)(E)}function m(_){e.code((0,ke._)`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,zn.alwaysValidSchema)(i,r)){let E=e.name("valid");l.removeAdditional==="failing"?(g(_,E,!1),e.if((0,ke.not)(E),()=>{t.reset(),m(_)})):(g(_,E),c||e.if((0,ke.not)(E),()=>e.break()))}}function g(_,E,S){let w={keyword:"additionalProperties",dataProp:_,dataPropType:zn.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,E)}}};Yo.default=Ry});var _l=b(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});var My=Er(),gl=he(),Bo=x(),yl=Jo(),Ay={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&&yl.default.code(new My.KeywordCxt(o,yl.default,"additionalProperties"));let i=(0,gl.allSchemaProperties)(r);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Bo.mergeEvaluated.props(e,(0,Bo.toHash)(i),o.props));let c=i.filter(f=>!(0,Bo.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,gl.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)}}};Zo.default=Ay});var bl=b(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});var Sl=he(),Ln=R(),El=x(),wl=x(),Cy={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,Sl.allSchemaProperties)(r),l=c.filter(g=>(0,El.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 Ln.Name)&&(o.props=(0,wl.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,El.checkStrictMode)(o,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,_=>{e.if((0,Ln._)`${(0,Sl.usePattern)(t,g)}.test(${_})`,()=>{let E=l.includes(g);E||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:wl.Type.Str},d),o.opts.unevaluated&&f!==!0?e.assign((0,Ln._)`${f}[${_}]`,!0):!E&&!o.allErrors&&e.if((0,Ln.not)(d),()=>e.break())})})}}};Xo.default=Cy});var vl=b(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Oy=x(),Iy={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Oy.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"}};Qo.default=Iy});var kl=b(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var xy=he(),Dy={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xy.validateUnion,error:{message:"must match a schema in anyOf"}};ei.default=Dy});var Pl=b(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var jn=R(),Ny=x(),zy={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,jn._)`{passingSchemas: ${t.passing}}`},Ly={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zy,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,Ny.alwaysValidSchema)(s,d)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,jn._)`${l} && ${i}`).assign(i,!1).assign(c,(0,jn._)`[${c}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(c,f),p&&t.mergeEvaluated(p,jn.Name)})})}}};ti.default=Ly});var Tl=b(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var jy=x(),qy={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,jy.alwaysValidSchema)(n,o))return;let c=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(c)})}};ri.default=qy});var Ml=b(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});var qn=R(),Rl=x(),Uy={message:({params:t})=>(0,qn.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,qn._)`{failingKeyword: ${t.ifClause}}`},Fy={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Uy,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Rl.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=$l(n,"then"),o=$l(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,qn.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,qn._)`${d}`):t.setParams({ifClause:d})}}}};function $l(t,e){let r=t.schema[e];return r!==void 0&&!(0,Rl.alwaysValidSchema)(t,r)}ni.default=Fy});var Al=b(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});var Hy=x(),Wy={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Hy.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};si.default=Wy});var Cl=b(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var Vy=Uo(),Gy=al(),Ky=Fo(),Yy=ll(),Jy=ul(),By=pl(),Zy=hl(),Xy=Jo(),Qy=_l(),e_=bl(),t_=vl(),r_=kl(),n_=Pl(),s_=Tl(),o_=Ml(),i_=Al();function a_(t=!1){let e=[t_.default,r_.default,n_.default,s_.default,o_.default,i_.default,Zy.default,Xy.default,By.default,Qy.default,e_.default];return t?e.push(Gy.default,Yy.default):e.push(Vy.default,Ky.default),e.push(Jy.default),e}oi.default=a_});var Ol=b(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});var U=R(),c_={message:({schemaCode:t})=>(0,U.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,U._)`{format: ${t}}`},l_={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:c_,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,U._)`${h}[${i}]`),_=r.let("fType"),E=r.let("format");r.if((0,U._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,U._)`${g}.type || "string"`).assign(E,(0,U._)`${g}.validate`),()=>r.assign(_,(0,U._)`"string"`).assign(E,g)),t.fail$data((0,U.or)(S(),w()));function S(){return l.strictSchema===!1?U.nil:(0,U._)`${i} && !${E}`}function w(){let A=d.$async?(0,U._)`(${g}.async ? await ${E}(${n}) : ${E}(${n}))`:(0,U._)`${E}(${n})`,k=(0,U._)`(typeof ${E} == "function" ? ${A} : ${E}.test(${n}))`;return(0,U._)`${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(A());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,U.regexpCode)(k):l.code.formats?(0,U._)`${l.code.formats}${(0,U.getProperty)(o)}`:void 0,de=r.scopeValue("formats",{key:o,ref:k,code:le});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,U._)`${de}.validate`]:["string",k,de]}function A(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,U._)`await ${E}(${n})`}return typeof _=="function"?(0,U._)`${E}(${n})`:(0,U._)`${E}.test(${n})`}}}};ii.default=l_});var Il=b(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});var u_=Ol(),d_=[u_.default];ai.default=d_});var xl=b(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.contentVocabulary=It.metadataVocabulary=void 0;It.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];It.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Nl=b(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});var f_=Hc(),p_=nl(),m_=Cl(),h_=Il(),Dl=xl(),g_=[f_.default,p_.default,(0,m_.default)(),h_.default,Dl.metadataVocabulary,Dl.contentVocabulary];ci.default=g_});var Ll=b(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.DiscrError=void 0;var zl;(function(t){t.Tag="tag",t.Mapping="mapping"})(zl||(Un.DiscrError=zl={}))});var ql=b(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var xt=R(),li=Ll(),jl=vn(),y_=wr(),__=x(),S_={message:({params:{discrError:t,tagName:e}})=>t===li.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,xt._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},E_={keyword:"discriminator",type:"object",schemaType:"object",error:S_,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,xt._)`${r}${(0,xt.getProperty)(c)}`);e.if((0,xt._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:li.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,xt._)`${u} === ${h}`),e.assign(l,f(m[h]));e.else(),t.error(!1,{discrError:li.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,xt.Name),h}function p(){var m;let h={},g=E(s),_=!0;for(let A=0;A<i.length;A++){let k=i[A];if(k?.$ref&&!(0,__.schemaHasRulesButRef)(k,o.self.RULES)){let de=k.$ref;if(k=jl.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,de),k instanceof jl.SchemaEnv&&(k=k.schema),k===void 0)throw new y_.default(o.opts.uriResolver,o.baseId,de)}let le=(m=k?.properties)===null||m===void 0?void 0:m[c];if(typeof le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(g||E(k)),S(le,A)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return h;function E({required:A}){return Array.isArray(A)&&A.includes(c)}function S(A,k){if(A.const)w(A.const,k);else if(A.enum)for(let le of A.enum)w(le,k);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function w(A,k){if(typeof A!="string"||A in h)throw new Error(`discriminator: "${c}" values must be unique strings`);h[A]=k}}}};ui.default=E_});var Ul=b((ak,w_)=>{w_.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 fi=b((q,di)=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.MissingRefError=q.ValidationError=q.CodeGen=q.Name=q.nil=q.stringify=q.str=q._=q.KeywordCxt=q.Ajv=void 0;var b_=zc(),v_=Nl(),k_=ql(),Fl=Ul(),P_=["/properties"],Fn="http://json-schema.org/draft-07/schema",Dt=class extends b_.default{_addVocabularies(){super._addVocabularies(),v_.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(k_.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Fl,P_):Fl;this.addMetaSchema(e,Fn,!1),this.refs["http://json-schema.org/schema"]=Fn}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fn)?Fn:void 0)}};q.Ajv=Dt;di.exports=q=Dt;di.exports.Ajv=Dt;Object.defineProperty(q,"__esModule",{value:!0});q.default=Dt;var T_=Er();Object.defineProperty(q,"KeywordCxt",{enumerable:!0,get:function(){return T_.KeywordCxt}});var Nt=R();Object.defineProperty(q,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(q,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(q,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(q,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(q,"Name",{enumerable:!0,get:function(){return Nt.Name}});Object.defineProperty(q,"CodeGen",{enumerable:!0,get:function(){return Nt.CodeGen}});var $_=wn();Object.defineProperty(q,"ValidationError",{enumerable:!0,get:function(){return $_.default}});var R_=wr();Object.defineProperty(q,"MissingRefError",{enumerable:!0,get:function(){return R_.default}})});var Bl=b(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.formatNames=Ce.fastFormats=Ce.fullFormats=void 0;function Ae(t,e){return{validate:t,compare:e}}Ce.fullFormats={date:Ae(Gl,gi),time:Ae(mi(!0),yi),"date-time":Ae(Hl(!0),Yl),"iso-time":Ae(mi(),Kl),"iso-date-time":Ae(Hl(),Jl),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:x_,"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:U_,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:D_,int32:{type:"number",validate:L_},int64:{type:"number",validate:j_},float:{type:"number",validate:Vl},double:{type:"number",validate:Vl},password:!0,binary:!0};Ce.fastFormats={...Ce.fullFormats,date:Ae(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,gi),time:Ae(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,yi),"date-time":Ae(/^\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,Yl),"iso-time":Ae(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Kl),"iso-date-time":Ae(/^\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,Jl),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};Ce.formatNames=Object.keys(Ce.fullFormats);function M_(t){return t%4===0&&(t%100!==0||t%400===0)}var A_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,C_=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gl(t){let e=A_.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&&M_(r)?29:C_[n])}function gi(t,e){if(t&&e)return t>e?1:t<e?-1:0}var pi=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function mi(t){return function(r){let n=pi.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],c=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||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 yi(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 Kl(t,e){if(!(t&&e))return;let r=pi.exec(t),n=pi.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var hi=/t|\s/i;function Hl(t){let e=mi(t);return function(n){let s=n.split(hi);return s.length===2&&Gl(s[0])&&e(s[1])}}function Yl(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Jl(t,e){if(!(t&&e))return;let[r,n]=t.split(hi),[s,o]=e.split(hi),i=gi(r,s);if(i!==void 0)return i||yi(n,o)}var O_=/\/|:/,I_=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function x_(t){return O_.test(t)&&I_.test(t)}var Wl=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function D_(t){return Wl.lastIndex=0,Wl.test(t)}var N_=-(2**31),z_=2**31-1;function L_(t){return Number.isInteger(t)&&t<=z_&&t>=N_}function j_(t){return Number.isInteger(t)}function Vl(){return!0}var q_=/[^\\]\\Z/;function U_(t){if(q_.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Zl=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.formatLimitDefinition=void 0;var F_=fi(),Pe=R(),rt=Pe.operators,Hn={formatMaximum:{okStr:"<=",ok:rt.LTE,fail:rt.GT},formatMinimum:{okStr:">=",ok:rt.GTE,fail:rt.LT},formatExclusiveMaximum:{okStr:"<",ok:rt.LT,fail:rt.GTE},formatExclusiveMinimum:{okStr:">",ok:rt.GT,fail:rt.LTE}},H_={message:({keyword:t,schemaCode:e})=>(0,Pe.str)`should be ${Hn[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pe._)`{comparison: ${Hn[t].okStr}, limit: ${e}}`};zt.formatLimitDefinition={keyword:Object.keys(Hn),type:"string",schemaType:"string",$data:!0,error:H_,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 F_.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,Pe._)`${p}[${l.schemaCode}]`);t.fail$data((0,Pe.or)((0,Pe._)`typeof ${m} != "object"`,(0,Pe._)`${m} instanceof RegExp`,(0,Pe._)`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,Pe._)`${i.code.formats}${(0,Pe.getProperty)(p)}`:void 0});t.fail$data(f(h))}function f(p){return(0,Pe._)`${p}.compare(${r}, ${n}) ${Hn[s].fail} 0`}},dependencies:["format"]};var W_=t=>(t.addKeyword(zt.formatLimitDefinition),t);zt.default=W_});var tu=b((Dr,eu)=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});var Lt=Bl(),V_=Zl(),_i=R(),Xl=new _i.Name("fullFormats"),G_=new _i.Name("fastFormats"),Si=(t,e={keywords:!0})=>{if(Array.isArray(e))return Ql(t,e,Lt.fullFormats,Xl),t;let[r,n]=e.mode==="fast"?[Lt.fastFormats,G_]:[Lt.fullFormats,Xl],s=e.formats||Lt.formatNames;return Ql(t,s,r,n),e.keywords&&(0,V_.default)(t),t};Si.get=(t,e="full")=>{let n=(e==="fast"?Lt.fastFormats:Lt.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Ql(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,_i._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}eu.exports=Dr=Si;Object.defineProperty(Dr,"__esModule",{value:!0});Dr.default=Si});var ze=require("fs"),Yt=require("path"),Zi=require("os"),os=(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))(os||{}),Bi=(0,Yt.join)((0,Zi.homedir)(),".claude-mem"),is=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=(0,Yt.join)(Bi,"logs");(0,ze.existsSync)(e)||(0,ze.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Yt.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=(0,Yt.join)(Bi,"settings.json");if((0,ze.existsSync)(e)){let r=(0,ze.readFileSync)(e,"utf-8"),s=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=os[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(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),c=os[e].padEnd(5),l=r.padEnd(6),u="";s?.correlationId?u=`[${s.correlationId}] `:s?.sessionId&&(u=`[session-${s.sessionId}] `);let d="";o!=null&&(o instanceof Error?d=this.getLevel()===0?`
${o.message}
${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?d=`
`+JSON.stringify(o,null,2):d=" "+this.formatData(o));let f="";if(s){let{sessionId:m,memorySessionId:h,correlationId:g,..._}=s;Object.keys(_).length>0&&(f=` {${Object.entries(_).map(([S,w])=>`${S}=${w}`).join(", ")}}`)}let p=`[${i}] [${c}] [${l}] ${u}${n}${f}${d}`;if(this.logFilePath)try{(0,ze.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 is;var pd=se(require("zod/v3"),1),Vr=se(require("zod/v4-mini"),1);function yt(t){return!!t._zod}function Ge(t,e){return yt(t)?Vr.safeParse(t,e):t.safeParse(e)}function Gr(t){if(!t)return;let e;if(yt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Xi(t){if(yt(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=se(require("zod/v4"),1),cs="2025-11-25";var Qi=[cs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ke="io.modelcontextprotocol/related-task",Yr="2.0",W=a.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ea=a.union([a.string(),a.number().int()]),ta=a.string(),aE=a.looseObject({ttl:a.number().optional(),pollInterval:a.number().optional()}),md=a.object({ttl:a.number().optional()}),hd=a.object({taskId:a.string()}),ls=a.looseObject({progressToken:ea.optional(),[Ke]:hd.optional()}),ue=a.object({_meta:ls.optional()}),Jt=ue.extend({task:md.optional()}),ra=t=>Jt.safeParse(t).success,V=a.object({method:a.string(),params:ue.loose().optional()}),fe=a.object({_meta:ls.optional()}),pe=a.object({method:a.string(),params:fe.loose().optional()}),G=a.looseObject({_meta:ls.optional()}),Jr=a.union([a.string(),a.number().int()]),na=a.object({jsonrpc:a.literal(Yr),id:Jr,...V.shape}).strict(),us=t=>na.safeParse(t).success,sa=a.object({jsonrpc:a.literal(Yr),...pe.shape}).strict(),oa=t=>sa.safeParse(t).success,ds=a.object({jsonrpc:a.literal(Yr),id:Jr,result:G}).strict(),Bt=t=>ds.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 fs=a.object({jsonrpc:a.literal(Yr),id:Jr.optional(),error:a.object({code:a.number().int(),message:a.string(),data:a.unknown().optional()})}).strict();var ia=t=>fs.safeParse(t).success;var aa=a.union([na,sa,ds,fs]),cE=a.union([ds,fs]),Br=G.strict(),gd=fe.extend({requestId:Jr.optional(),reason:a.string().optional()}),Zr=pe.extend({method:a.literal("notifications/cancelled"),params:gd}),yd=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(yd).optional()}),_t=a.object({name:a.string(),title:a.string().optional()}),ca=_t.extend({..._t.shape,...Zt.shape,version:a.string(),websiteUrl:a.string().optional(),description:a.string().optional()}),_d=a.intersection(a.object({applyDefaults:a.boolean().optional()}),a.record(a.string(),a.unknown())),Sd=a.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,a.intersection(a.object({form:_d.optional(),url:W.optional()}),a.record(a.string(),a.unknown()).optional())),Ed=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({sampling:a.looseObject({createMessage:W.optional()}).optional(),elicitation:a.looseObject({create:W.optional()}).optional()}).optional()}),wd=a.looseObject({list:W.optional(),cancel:W.optional(),requests:a.looseObject({tools:a.looseObject({call:W.optional()}).optional()}).optional()}),bd=a.object({experimental:a.record(a.string(),W).optional(),sampling:a.object({context:W.optional(),tools:W.optional()}).optional(),elicitation:Sd.optional(),roots:a.object({listChanged:a.boolean().optional()}).optional(),tasks:Ed.optional(),extensions:a.record(a.string(),W).optional()}),vd=ue.extend({protocolVersion:a.string(),capabilities:bd,clientInfo:ca}),ps=V.extend({method:a.literal("initialize"),params:vd});var kd=a.object({experimental:a.record(a.string(),W).optional(),logging:W.optional(),completions:W.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:wd.optional(),extensions:a.record(a.string(),W).optional()}),Pd=G.extend({protocolVersion:a.string(),capabilities:kd,serverInfo:ca,instructions:a.string().optional()}),ms=pe.extend({method:a.literal("notifications/initialized"),params:fe.optional()});var Xr=V.extend({method:a.literal("ping"),params:ue.optional()}),Td=a.object({progress:a.number(),total:a.optional(a.number()),message:a.optional(a.string())}),$d=a.object({...fe.shape,...Td.shape,progressToken:ea}),Qr=pe.extend({method:a.literal("notifications/progress"),params:$d}),Rd=ue.extend({cursor:ta.optional()}),Xt=V.extend({params:Rd.optional()}),Qt=G.extend({nextCursor:ta.optional()}),Md=a.enum(["working","input_required","completed","failed","cancelled"]),er=a.object({taskId:a.string(),status:Md,ttl:a.union([a.number(),a.null()]),createdAt:a.string(),lastUpdatedAt:a.string(),pollInterval:a.optional(a.number()),statusMessage:a.optional(a.string())}),St=G.extend({task:er}),Ad=fe.merge(er),tr=pe.extend({method:a.literal("notifications/tasks/status"),params:Ad}),en=V.extend({method:a.literal("tasks/get"),params:ue.extend({taskId:a.string()})}),tn=G.merge(er),rn=V.extend({method:a.literal("tasks/result"),params:ue.extend({taskId:a.string()})}),lE=G.loose(),nn=Xt.extend({method:a.literal("tasks/list")}),sn=Qt.extend({tasks:a.array(er)}),on=V.extend({method:a.literal("tasks/cancel"),params:ue.extend({taskId:a.string()})}),la=G.merge(er),ua=a.object({uri:a.string(),mimeType:a.optional(a.string()),_meta:a.record(a.string(),a.unknown()).optional()}),da=ua.extend({text:a.string()}),hs=a.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),fa=ua.extend({blob:hs}),rr=a.enum(["user","assistant"]),Et=a.object({audience:a.array(rr).optional(),priority:a.number().min(0).max(1).optional(),lastModified:a.iso.datetime({offset:!0}).optional()}),pa=a.object({..._t.shape,...Zt.shape,uri:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),size:a.optional(a.number()),annotations:Et.optional(),_meta:a.optional(a.looseObject({}))}),Cd=a.object({..._t.shape,...Zt.shape,uriTemplate:a.string(),description:a.optional(a.string()),mimeType:a.optional(a.string()),annotations:Et.optional(),_meta:a.optional(a.looseObject({}))}),Od=Xt.extend({method:a.literal("resources/list")}),Id=Qt.extend({resources:a.array(pa)}),xd=Xt.extend({method:a.literal("resources/templates/list")}),Dd=Qt.extend({resourceTemplates:a.array(Cd)}),gs=ue.extend({uri:a.string()}),Nd=gs,zd=V.extend({method:a.literal("resources/read"),params:Nd}),Ld=G.extend({contents:a.array(a.union([da,fa]))}),jd=pe.extend({method:a.literal("notifications/resources/list_changed"),params:fe.optional()}),qd=gs,Ud=V.extend({method:a.literal("resources/subscribe"),params:qd}),Fd=gs,Hd=V.extend({method:a.literal("resources/unsubscribe"),params:Fd}),Wd=fe.extend({uri:a.string()}),Vd=pe.extend({method:a.literal("notifications/resources/updated"),params:Wd}),Gd=a.object({name:a.string(),description:a.optional(a.string()),required:a.optional(a.boolean())}),Kd=a.object({..._t.shape,...Zt.shape,description:a.optional(a.string()),arguments:a.optional(a.array(Gd)),_meta:a.optional(a.looseObject({}))}),Yd=Xt.extend({method:a.literal("prompts/list")}),Jd=Qt.extend({prompts:a.array(Kd)}),Bd=ue.extend({name:a.string(),arguments:a.record(a.string(),a.string()).optional()}),Zd=V.extend({method:a.literal("prompts/get"),params:Bd}),ys=a.object({type:a.literal("text"),text:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),_s=a.object({type:a.literal("image"),data:hs,mimeType:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Ss=a.object({type:a.literal("audio"),data:hs,mimeType:a.string(),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Xd=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()}),Qd=a.object({type:a.literal("resource"),resource:a.union([da,fa]),annotations:Et.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ef=pa.extend({type:a.literal("resource_link")}),Es=a.union([ys,_s,Ss,ef,Qd]),tf=a.object({role:rr,content:Es}),rf=G.extend({description:a.string().optional(),messages:a.array(tf)}),nf=pe.extend({method:a.literal("notifications/prompts/list_changed"),params:fe.optional()}),sf=a.object({title:a.string().optional(),readOnlyHint:a.boolean().optional(),destructiveHint:a.boolean().optional(),idempotentHint:a.boolean().optional(),openWorldHint:a.boolean().optional()}),of=a.object({taskSupport:a.enum(["required","optional","forbidden"]).optional()}),ma=a.object({..._t.shape,...Zt.shape,description:a.string().optional(),inputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()),outputSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),W).optional(),required:a.array(a.string()).optional()}).catchall(a.unknown()).optional(),annotations:sf.optional(),execution:of.optional(),_meta:a.record(a.string(),a.unknown()).optional()}),ws=Xt.extend({method:a.literal("tools/list")}),af=Qt.extend({tools:a.array(ma)}),an=G.extend({content:a.array(Es).default([]),structuredContent:a.record(a.string(),a.unknown()).optional(),isError:a.boolean().optional()}),uE=an.or(G.extend({toolResult:a.unknown()})),cf=Jt.extend({name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),nr=V.extend({method:a.literal("tools/call"),params:cf}),lf=pe.extend({method:a.literal("notifications/tools/list_changed"),params:fe.optional()}),dE=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"]),uf=ue.extend({level:sr}),bs=V.extend({method:a.literal("logging/setLevel"),params:uf}),df=fe.extend({level:sr,logger:a.string().optional(),data:a.unknown()}),ff=pe.extend({method:a.literal("notifications/message"),params:df}),pf=a.object({name:a.string().optional()}),mf=a.object({hints:a.array(pf).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()}),hf=a.object({mode:a.enum(["auto","required","none"]).optional()}),gf=a.object({type:a.literal("tool_result"),toolUseId:a.string().describe("The unique identifier for the corresponding tool call."),content:a.array(Es).default([]),structuredContent:a.object({}).loose().optional(),isError:a.boolean().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),yf=a.discriminatedUnion("type",[ys,_s,Ss]),Kr=a.discriminatedUnion("type",[ys,_s,Ss,Xd,gf]),_f=a.object({role:rr,content:a.union([Kr,a.array(Kr)]),_meta:a.record(a.string(),a.unknown()).optional()}),Sf=Jt.extend({messages:a.array(_f),modelPreferences:mf.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:W.optional(),tools:a.array(ma).optional(),toolChoice:hf.optional()}),Ef=V.extend({method:a.literal("sampling/createMessage"),params:Sf}),or=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens"]).or(a.string())),role:rr,content:yf}),vs=G.extend({model:a.string(),stopReason:a.optional(a.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(a.string())),role:rr,content:a.union([Kr,a.array(Kr)])}),wf=a.object({type:a.literal("boolean"),title:a.string().optional(),description:a.string().optional(),default:a.boolean().optional()}),bf=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()}),vf=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()}),kf=a.object({type:a.literal("string"),title:a.string().optional(),description:a.string().optional(),enum:a.array(a.string()),default:a.string().optional()}),Pf=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()}),Tf=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()}),$f=a.union([kf,Pf]),Rf=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()}),Mf=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()}),Af=a.union([Rf,Mf]),Cf=a.union([Tf,$f,Af]),Of=a.union([Cf,wf,bf,vf]),If=Jt.extend({mode:a.literal("form").optional(),message:a.string(),requestedSchema:a.object({type:a.literal("object"),properties:a.record(a.string(),Of),required:a.array(a.string()).optional()})}),xf=Jt.extend({mode:a.literal("url"),message:a.string(),elicitationId:a.string(),url:a.string().url()}),Df=a.union([If,xf]),Nf=V.extend({method:a.literal("elicitation/create"),params:Df}),zf=fe.extend({elicitationId:a.string()}),Lf=pe.extend({method:a.literal("notifications/elicitation/complete"),params:zf}),wt=G.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())}),jf=a.object({type:a.literal("ref/resource"),uri:a.string()});var qf=a.object({type:a.literal("ref/prompt"),name:a.string()}),Uf=ue.extend({ref:a.union([qf,jf]),argument:a.object({name:a.string(),value:a.string()}),context:a.object({arguments:a.record(a.string(),a.string()).optional()}).optional()}),Ff=V.extend({method:a.literal("completion/complete"),params:Uf});var Hf=G.extend({completion:a.looseObject({values:a.array(a.string()).max(100),total:a.optional(a.number().int()),hasMore:a.optional(a.boolean())})}),Wf=a.object({uri:a.string().startsWith("file://"),name:a.string().optional(),_meta:a.record(a.string(),a.unknown()).optional()}),Vf=V.extend({method:a.literal("roots/list"),params:ue.optional()}),ks=G.extend({roots:a.array(Wf)}),Gf=pe.extend({method:a.literal("notifications/roots/list_changed"),params:fe.optional()}),fE=a.union([Xr,ps,Ff,bs,Zd,Yd,Od,xd,zd,Ud,Hd,nr,ws,en,rn,nn,on]),pE=a.union([Zr,Qr,ms,Gf,tr]),mE=a.union([Br,or,vs,wt,ks,tn,sn,St]),hE=a.union([Xr,Ef,Nf,Vf,en,rn,nn,on]),gE=a.union([Zr,Qr,ff,Vd,jd,lf,nf,tr,Lf]),yE=a.union([Br,Pd,Hf,rf,Jd,Id,Dd,Ld,an,af,tn,sn,St]),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 as(s.elicitations,r)}return new t(e,r,n)}},as=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 Ye(t){return t==="completed"||t==="failed"||t==="cancelled"}var tp=se(require("zod/v4-mini"),1);var Qf=require("zod/v3");var Yf=require("zod/v3");var Zf=require("zod/v3");var BE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ps(t){let r=Gr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Xi(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ts(t,e){let r=Ge(t,e);if(!r.success)throw r.error;return r.data}var rp=6e4,cn=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(Zr,r=>{this._oncancel(r)}),this.setNotificationHandler(Qr,r=>{this._onprogress(r)}),this.setRequestHandler(Xr,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(en,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(rn,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(!Ye(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Ye(i.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Ke]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(nn,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(on,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(Ye(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),Bt(o)||ia(o)?this._onresponse(o):us(o)?this._onrequest(o,i):oa(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?.[Ke]?.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=ra(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),Bt(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(Bt(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),Bt(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,St,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},Ye(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||{},[Ke]: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(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`)));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=Ge(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??rp,_=()=>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 A=this._responseHandlers.get(p);A?A(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},tn,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},sn,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},la,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||{},[Ke]: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||{},[Ke]: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||{},[Ke]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ps(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Ts(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=Ps(e);this._notificationHandlers.set(n,s=>{let o=Ts(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"&&us(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),Ye(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(Ye(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),Ye(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ha(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ga(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];ha(i)&&ha(o)?r[s]={...i,...o}:r[s]=o}return r}var ru=se(fi(),1),nu=se(tu(),1);function K_(){let t=new ru.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,nu.default)(t),t}var Wn=class{constructor(e){this._ajv=e??K_()}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 Vn=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},wt,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 su(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 ou(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 Gn=class extends cn{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.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Wn,this.setRequestHandler(ps,n=>this._oninitialize(n)),this.setNotificationHandler(ms,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(bs,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 Vn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ga(this._capabilities,e)}setRequestHandler(e,r){let s=Gr(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(yt(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=Ge(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=Ge(St,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=Ge(an,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){ou(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&su(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:Qi.includes(r)?r:cs,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"},Br)}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},vs,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},wt,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},wt,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},ks,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 Ei=se(require("node:process"),1);var Kn=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),Y_(r)}clear(){this._buffer=void 0}};function Y_(t){return aa.parse(JSON.parse(t))}function iu(t){return JSON.stringify(t)+`
`}var Yn=class{constructor(e=Ei.default.stdin,r=Ei.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Kn,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=iu(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Oi=se(require("path"),1);var _e={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*_e.WINDOWS_MULTIPLIER):t}var Oe=require("fs"),Nr=require("path"),wi=require("os"),Ie=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-6",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Nr.join)((0,wi.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Nr.join)((0,wi.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:""};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,Oe.existsSync)(e)){let i=this.getAllDefaults();try{let c=(0,Nr.dirname)(e);(0,Oe.existsSync)(c)||(0,Oe.mkdirSync)(c,{recursive:!0}),(0,Oe.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,Oe.readFileSync)(e,"utf-8"),n=JSON.parse(r),s=n;if(n.env&&typeof n.env=="object"){s=n.env;try{(0,Oe.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 F=require("path"),bi=require("os"),vi=require("fs");var cu=require("url");var Q_={};function J_(){return typeof __dirname<"u"?__dirname:(0,F.dirname)((0,cu.fileURLToPath)(Q_.url))}var Mk=J_();function B_(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,F.join)((0,bi.homedir)(),".claude-mem"),e=(0,F.join)(t,"settings.json");try{if((0,vi.existsSync)(e)){let{readFileSync:r}=require("fs"),n=JSON.parse(r(e,"utf-8")),s=n.env??n;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var xe=B_(),Jn=process.env.CLAUDE_CONFIG_DIR||(0,F.join)((0,bi.homedir)(),".claude"),lu=(0,F.join)(Jn,"plugins","marketplaces","thedotmack"),Ak=(0,F.join)(xe,"archives"),Ck=(0,F.join)(xe,"logs"),Ok=(0,F.join)(xe,"trash"),Ik=(0,F.join)(xe,"backups"),xk=(0,F.join)(xe,"modes"),Z_=(0,F.join)(xe,"settings.json"),Dk=(0,F.join)(xe,"claude-mem.db"),Nk=(0,F.join)(xe,"vector-db"),X_=(0,F.join)(xe,"observer-sessions"),zk=(0,F.basename)(X_),Lk=(0,F.join)(Jn,"settings.json"),jk=(0,F.join)(Jn,"commands"),qk=(0,F.join)(Jn,"CLAUDE.md");var pt=require("fs"),bu=require("os"),Ci=se(require("path"),1);var $i=require("child_process"),Ne=require("fs"),uu=require("os"),zr=se(require("path"),1);var eS=["CLAUDECODE_","CLAUDE_CODE_"],tS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),rS=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"]),nS=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH"]);function sS(t){let e=t.HOME||t.USERPROFILE;return e?process.platform==="win32"?[`${e}\\AppData\\Local\\Programs\\claude`,`${e}\\.bun\\bin`,`${e}\\.local\\bin`]:[`${e}/.local/bin`,`${e}/.bun/bin`,`${e}/bin`,"/opt/homebrew/bin","/usr/local/bin"]:["/opt/homebrew/bin","/usr/local/bin"]}function ki(t=process.env){let e={};for(let[i,c]of Object.entries(t))if(c!==void 0){if(nS.has(i)){e[i]=c;continue}tS.has(i)||rS.has(i)||eS.some(l=>i.startsWith(l))||(e[i]=c)}let r=process.platform==="win32"?";":":",n=e.PATH||e.Path||"",s=new Set(n.split(r).filter(Boolean)),o=sS(t).filter(i=>!s.has(i));return o.length>0&&(e.PATH=[...o,n].filter(Boolean).join(r)),e}var oS=5e3,iS=1e3,aS=zr.default.join((0,uu.homedir)(),".claude-mem"),cS=zr.default.join(aS,"supervisor.json");function De(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 du(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Ne.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,$i.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 Ri(t){if(!t||!De(t.pid))return!1;if(!t.startToken)return!0;let e=du(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 Ti=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,Ne.mkdirSync)(zr.default.dirname(this.registryPath),{recursive:!0}),!(0,Ne.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ne.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)De(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=>De(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()+oS;for(;Date.now()<o&&s.filter(l=>De(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let i=s.filter(c=>De(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()+iS;for(;Date.now()<c&&i.filter(u=>De(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,Ne.mkdirSync)(zr.default.dirname(this.registryPath),{recursive:!0}),(0,Ne.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Pi=null;function Bn(){return Pi||(Pi=new Ti),Pi}var mu=require("child_process"),hu=require("fs"),gu=require("os"),Mi=se(require("path"),1),yu=require("util");var lS=(0,yu.promisify)(mu.execFile),uS=Mi.default.join((0,gu.homedir)(),".claude-mem"),dS=Mi.default.join(uS,"worker.pid");async function _u(t){let e=t.currentPid??process.pid,r=t.pidFilePath??dS,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(!De(i.pid)){t.registry.unregister(i.id);continue}try{await pu(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 fu(s,5e3);let o=s.filter(i=>De(i.pid));for(let i of o)try{await pu(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 fu(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,hu.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 fu(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(s=>De(s.pid)).length===0)return;await new Promise(s=>setTimeout(s,100))}}async function pu(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){try{typeof n=="number"?process.kill(-n,e):process.kill(r,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;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 fS();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:_e.POWERSHELL_COMMAND,windowsHide:!0})}async function fS(){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 Su=3e4,jt=null;function pS(){let e=Bn().pruneDeadEntries();e>0&&y.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Eu(){jt===null&&(jt=setInterval(pS,Su),jt.unref(),y.debug("SYSTEM","Health checker started",{intervalMs:Su}))}function wu(){jt!==null&&(clearInterval(jt),jt=null,y.debug("SYSTEM","Health checker stopped"))}var mS=Ci.default.join((0,bu.homedir)(),".claude-mem"),hS=Ci.default.join(mS,"worker.pid"),Ai=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(),Zn({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Eu()}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}wu(),this.stopPromise=_u({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}},gS=new Ai(Bn());function vu(){return gS}function Zn(t={}){let e=t.pidFilePath??hS;if(!(0,pt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,pt.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,pt.rmSync)(e,{force:!0}),"invalid"}return Ri(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,pt.rmSync)(e,{force:!0}),"stale")}var yS=(()=>{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(_e.HEALTH_CHECK)})();function _S(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 Xn=null,Qn=null;function Ii(){if(Xn!==null)return Xn;let t=Oi.default.join(Ie.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Ie.loadFromFile(t);return Xn=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Xn}function SS(){if(Qn!==null)return Qn;let t=Oi.default.join(Ie.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return Qn=Ie.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,Qn}function ES(t){return`http://${SS()}:${Ii()}${t}`}function es(t,e={}){let r=e.method??"GET",n=e.timeoutMs??yS,s=ES(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),n>0?_S(s,o,n):fetch(s,o)}var zi=se(require("path"),1),Se=require("fs");var We=se(require("path"),1),Di=require("os"),ne=require("fs"),mt=require("child_process"),Pu=require("util");var wP=(0,Pu.promisify)(mt.exec),wS=We.default.join((0,Di.homedir)(),".claude-mem"),qt=We.default.join(wS,"worker.pid");function ku(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function bS(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,n;try{n=(0,mt.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 xi;function vS(t={}){let e=Object.keys(t).length===0;if(e&&xi!==void 0)return xi;let r=kS(t);return e&&r!==null&&(xi=r),r}function kS(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(ku(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,Di.homedir)(),o=t.pathExists??ne.existsSync,i=t.lookupInPath??bS,c=e==="win32"?[n.BUN,n.BUN_PATH,We.default.join(s,".bun","bin","bun.exe"),We.default.join(s,".bun","bin","bun"),n.USERPROFILE?We.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?We.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?We.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,We.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&&(ku(u)&&o(u)||u.toLowerCase()==="bun"))return u}return i("bun",e)}function Tu(){if((0,ne.existsSync)(qt))try{(0,ne.unlinkSync)(qt)}catch(t){t instanceof Error?y.warn("SYSTEM","Failed to remove PID file",{path:qt},t):y.warn("SYSTEM","Failed to remove PID file",{path:qt},new Error(String(t)))}}function Ut(t){return process.platform==="win32"?Math.round(t*2):t}function $u(t,e,r={}){vu().assertCanSpawn("worker daemon");let n=ki({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),s=vS();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}let o="/usr/bin/setsid",i=process.platform!=="win32"&&(0,ne.existsSync)(o),u=(0,mt.spawn)(i?o:s,i?[s,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",windowsHide:!0,env:n});if(u.pid!==void 0)return u.unref(),u.pid}function Ru(){try{if(!(0,ne.existsSync)(qt))return;let t=new Date;(0,ne.utimesSync)(qt,t,t)}catch{}}function Mu(){return Zn({logAlive:!1})}var Au=se(require("net"),1);async function PS(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 Cu(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=Au.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 Ou(t,e,r,n){let s=Date.now();for(;Date.now()-s<r;){try{if((await PS(t,e)).ok)return!0}catch(o){o instanceof Error?y.debug("SYSTEM",n,{},o):y.debug("SYSTEM",n,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Lr(t,e=3e4){return Ou(t,"/api/health",e,"Service not ready yet, will retry")}function Ni(t,e=3e4){return Ou(t,"/api/readiness",e,"Worker not ready yet, will retry")}var TS=120*1e3;function Li(){return zi.default.join(Ie.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function $S(){if(process.platform!=="win32")return!1;let t=Li();if(!(0,Se.existsSync)(t))return!1;try{let e=(0,Se.statSync)(t).mtimeMs;return Date.now()-e<TS}catch(e){return e instanceof Error?y.debug("SYSTEM","Could not stat worker spawn lock file",{},e):y.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function RS(){if(process.platform==="win32")try{let t=Li();(0,Se.mkdirSync)(zi.default.dirname(t),{recursive:!0}),(0,Se.writeFileSync)(t,"","utf-8")}catch{}}function ts(){if(process.platform==="win32")try{let t=Li();(0,Se.existsSync)(t)&&(0,Se.unlinkSync)(t)}catch{}}async function Iu(t,e){return e?(0,Se.existsSync)(e)?Mu()==="alive"?(y.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Lr(t,Ut(_e.PORT_IN_USE_WAIT))?(ts(),y.info("SYSTEM","Worker became healthy while waiting on live PID"),!0):(y.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout"),!1)):await Lr(t,1e3)?(ts(),await Ni(t,Ut(_e.READINESS_WAIT))||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),y.info("SYSTEM","Worker already running and healthy"),!0):await Cu(t)?(y.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Lr(t,Ut(_e.PORT_IN_USE_WAIT))?(ts(),y.info("SYSTEM","Worker is now healthy"),!0):(y.error("SYSTEM","Port in use but worker not responding to health checks"),!1)):$S()?(y.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),!1):(y.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),RS(),$u(e,t)===void 0?(y.error("SYSTEM","Failed to spawn worker daemon"),!1):await Lr(t,Ut(_e.POST_SPAWN_WAIT))?(await Ni(t,Ut(_e.READINESS_WAIT))||y.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),ts(),Ru(),y.info("SYSTEM","Worker started successfully"),!0):(Tu(),y.error("SYSTEM","Worker failed to start (health check timeout)"),!1)):(y.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),!1):(y.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),!1)}var Wt=require("node:fs/promises"),Fr=require("node:path");var Nu=require("node:child_process"),ee=require("node:fs"),B=require("node:path"),Wi=require("node:os"),Ui=require("node:module");var FS={},Fi=typeof __filename<"u"?(0,Ui.createRequire)(__filename):(0,Ui.createRequire)(FS.url),Hi={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".ex":"elixir",".exs":"elixir",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function zu(t,e){let r=t.slice(t.lastIndexOf("."));return Hi[r]?Hi[r]:e.extensionToLanguage[r]?e.extensionToLanguage[r]:"unknown"}function Lu(t,e){return e.languageToQueryKey[t]?e.languageToQueryKey[t]:CS(t)}var jr=new Map,Ft={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};function Ur(t){if(jr.has(t))return jr.get(t);let e=(0,B.join)(t,".claude-mem.json"),r;try{let o=(0,ee.readFileSync)(e,"utf-8");r=JSON.parse(o)}catch{return jr.set(t,Ft),Ft}let n=r.grammars;if(!n||typeof n!="object"||Array.isArray(n))return jr.set(t,Ft),Ft;let s={grammars:{},extensionToLanguage:{},languageToQueryKey:{}};for(let[o,i]of Object.entries(n)){if(ju[o]||!i||typeof i!="object"||Array.isArray(i))continue;let c=i,l=c.package,u=c.extensions,d=c.query;if(!(typeof l!="string"||!Array.isArray(u))&&u.every(f=>typeof f=="string")){s.grammars[o]={package:l,extensions:u,query:typeof d=="string"?d:void 0};for(let f of u)Hi[f]||(s.extensionToLanguage[f]=o);if(typeof d=="string"){let f=(0,B.join)(t,d);try{let p=(0,ee.readFileSync)(f,"utf-8"),m=`user_${o}`;Uu[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 ju={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"},MS={markdown:"tree-sitter-markdown"};function AS(t){let e=ju[t];if(!e)return null;let r=MS[t];if(r){try{let n=Fi.resolve(e+"/package.json"),s=(0,B.join)((0,B.dirname)(n),r);if((0,ee.existsSync)((0,B.join)(s,"src")))return s}catch{}return null}try{let n=Fi.resolve(e+"/package.json");return(0,B.dirname)(n)}catch{return null}}function qu(t,e){let r=AS(t);if(r)return r;if(!e)return null;let s=Ur(e).grammars[t];if(!s)return null;try{let o=(0,B.join)(e,"node_modules",s.package,"package.json");if((0,ee.existsSync)(o)){let i=(0,B.dirname)(o);if((0,ee.existsSync)((0,B.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 Uu={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 CS(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 ji=null,qi=new Map;function Fu(t){if(qi.has(t))return qi.get(t);ji||(ji=(0,ee.mkdtempSync)((0,B.join)((0,Wi.tmpdir)(),"smart-read-queries-")));let e=(0,B.join)(ji,`${t}.scm`);return(0,ee.writeFileSync)(e,Uu[t]),qi.set(t,e),e}var qr=null;function OS(){if(qr)return qr;try{let t=Fi.resolve("tree-sitter-cli/package.json"),e=(0,B.join)((0,B.dirname)(t),"tree-sitter");if((0,ee.existsSync)(e))return qr=e,e}catch{}return qr="tree-sitter",qr}function IS(t,e,r){return Hu(t,[e],r).get(e)||[]}function Hu(t,e,r){if(e.length===0)return new Map;let n=OS(),s=["query","-p",r,t,...e],o;try{o=(0,Nu.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 xS(o)}function xS(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 xu={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"},DS=new Set(["class","struct","impl","trait"]);function NS(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 zS(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 LS(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 jS(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 Wu(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=>xu[w.tag]),d=l.captures.find(w=>w.tag==="name");if(!u)continue;let f=u.startRow,p=u.endRow,m=xu[u.tag],h=d?.text||"anonymous",g;if(r==="markdown"&&m==="section"){let A=(e[f]||"").match(/^(#{1,6})\s/),k=A?A[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=NS(e,f,p);let _=r==="markdown"?void 0:zS(e,f),E=r==="python"?LS(e,f,p):void 0,S={name:h,kind:m,signature:g,jsdoc:_||E,lineStart:f,lineEnd:p,exported:jS(h,f,p,o,e,r)};DS.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 rs(t,e,r){let n=r?Ur(r):Ft,s=zu(e,n),o=t.split(`
`),i=qu(s,r);if(!i)return{filePath:e,language:s,symbols:[],imports:[],totalLines:o.length,foldedTokenEstimate:50};let c=Lu(s,n),l=Fu(c),u=e.slice(e.lastIndexOf("."))||".txt",d=(0,ee.mkdtempSync)((0,B.join)((0,Wi.tmpdir)(),"smart-src-")),f=(0,B.join)(d,`source${u}`);(0,ee.writeFileSync)(f,t);try{let p=IS(l,f,i),m=Wu(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,ee.rmSync)(d,{recursive:!0,force:!0})}}function Vu(t,e){let r=new Map,n=e?Ur(e):Ft,s=new Map;for(let o of t){let i=zu(o.relativePath,n);s.has(i)||s.set(i,[]),s.get(i).push(o)}for(let[o,i]of s){let c=qu(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=Lu(o,n),u=Fu(l),d=i.map(p=>p.absolutePath),f=Hu(u,d,c);for(let p of i){let m=p.content.split(`
`),h=f.get(p.absolutePath)||[],g=Wu(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 qS(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(Gu(r," "));return e.join(`
`)}function qS(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=Du(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=Du(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 Du(t,e){let r=0;for(let n of t)if(n.kind==="section"&&n.lineStart<e){let s=n.signature.match(/^(#{1,6})\s/);r=s?s[1].length:1}return r}function Gu(t,e){let r=[],n=US(t.kind),s=t.exported?" [exported]":"",o=t.lineStart===t.lineEnd?`L${t.lineStart+1}`:`L${t.lineStart+1}-${t.lineEnd+1}`;if(r.push(`${e}${n} ${t.name}${s} (${o})`),r.push(`${e} ${t.signature}`),t.jsdoc){let c=t.jsdoc.split(`
`).find(l=>{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(Gu(i,e+" "));return r.join(`
`)}function US(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 Ku(t,e,r){let n=rs(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`<!-- \u{1F4CD} ${e} L${f+1}-${p+1} -->
${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 Yu=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"]),HS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),WS=512*1024;async function*Ju(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!=="."||HS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Ju(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Yu.has(c)||n&&n.has(c))&&(yield i)}}}async function VS(t){try{let e=await(0,Wt.stat)(t);if(e.size>WS||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 Bu(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)Yu.has(w)||l.add(w);let u=[];for await(let S of Ju(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 VS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Vu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=GS(w);let k=ns(S.toLowerCase(),o)>0,le=[],de=(Gt,gt)=>{for(let H of Gt){let Ve=0,Ee="",Kt=ns(H.name.toLowerCase(),o);Kt>0&&(Ve+=Kt*3,Ee="name match"),H.signature.toLowerCase().includes(s)&&(Ve+=2,Ee=Ee?`${Ee} + signature`:"signature match"),H.jsdoc&&H.jsdoc.toLowerCase().includes(s)&&(Ve+=1,Ee=Ee?`${Ee} + jsdoc`:"jsdoc match"),Ve>0&&(k=!0,le.push({filePath:S,symbolName:gt?`${gt}.${H.name}`:H.name,kind:H.kind,signature:H.signature,jsdoc:H.jsdoc,lineStart:H.lineStart,lineEnd:H.lineEnd,matchReason:Ee})),H.children&&de(H.children,H.name)}};de(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let A=ns(S.symbolName.toLowerCase(),o);return ns(w.symbolName.toLowerCase(),o)-A});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 ns(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 GS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Zu(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 Gi=require("node:fs/promises"),ed=require("node:fs"),ht=require("node:path"),td=require("node:url"),nE={},KS="12.4.7";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var rd=!1,nd=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,ht.dirname)((0,td.fileURLToPath)(nE.url))}catch{return rd=!0,process.cwd()}})(),Ki=(0,ht.resolve)(nd,"worker-service.cjs");function YS(){rd&&((0,ed.existsSync)(Ki)||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:Ki,mcpServerDir:nd}))}var Xu={search:"/api/search",timeline:"/api/timeline"};async function Vi(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 es(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 JS(t,e){let r=await es(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});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 JS(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 BS(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function ZS(){if(await BS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),YS();try{let t=Ii(),e=await Iu(t,Ki);return e||y.error("SYSTEM","Worker auto-start returned false \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}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 sd=[{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=<ID>, 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=Xu.search;return await Vi(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=Xu.timeline;return await Vi(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,ht.resolve)(t.path||process.cwd()),r=await Bu(e,t.query,{maxResults:t.max_results||20,filePattern:t.file_pattern});return{content:[{type:"text",text:Zu(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,ht.resolve)(t.file_path),r=await(0,Gi.readFile)(e,"utf-8"),n=Ku(r,e,t.symbol_name);if(n)return{content:[{type:"text",text:n}]};let s=rs(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,ht.resolve)(t.file_path),r=await(0,Gi.readFile)(e,"utf-8"),n=rs(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 Vi("/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)}},{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)}}],Yi=new Gn({name:"claude-mem",version:KS},{capabilities:{tools:{}}});Yi.setRequestHandler(ws,async()=>({tools:sd.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));Yi.setRequestHandler(nr,async t=>{let e=sd.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 XS=3e4,Hr=null,Qu=!1;function ss(){Wr("stdio-closed")}function od(t){y.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:t.message}),Wr("stdio-error")}function QS(){process.stdin.on("end",ss),process.stdin.on("close",ss),process.stdin.on("error",od)}function eE(){process.stdin.off("end",ss),process.stdin.off("close",ss),process.stdin.off("error",od)}function tE(){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())},XS),Hr.unref&&Hr.unref()}function Wr(t="shutdown"){Qu||(Qu=!0,Hr&&clearInterval(Hr),eE(),y.info("SYSTEM","MCP server shutting down",{reason:t}),process.exit(0))}process.on("SIGTERM",Wr);process.on("SIGINT",Wr);async function rE(){let t=new Yn;QS(),await Yi.connect(t),y.info("SYSTEM","Claude-mem search server started"),tE(),setTimeout(async()=>{await ZS()?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)}rE().catch(t=>{y.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});