@reddb-io/red-skills 2.55.4 → 2.55.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var By=Object.create;var _i=Object.defineProperty;var Ly=Object.getOwnPropertyDescriptor;var Zy=Object.getOwnPropertyNames;var Uy=Object.getPrototypeOf,Fy=Object.prototype.hasOwnProperty;var ct=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gu=(e,t)=>{for(var r in t)_i(e,r,{get:t[r],enumerable:!0})},Vy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zy(t))!Fy.call(e,o)&&o!==r&&_i(e,o,{get:()=>t[o],enumerable:!(n=Ly(t,o))||n.enumerable});return e};var vi=(e,t,r)=>(r=e!=null?By(Uy(e)):{},Vy(t||!e||!e.__esModule?_i(r,"default",{value:e,enumerable:!0}):r,e));var Hr=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var Vr=class{};Z._CodeOrName=Vr;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zt=class extends Vr{constructor(t){if(super(),!Z.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Z.Name=zt;var Ne=class extends Vr{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof zt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Ne;Z.nil=new Ne("");function Lp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)qs(r,t[n]),r.push(e[++n]);return new Ne(r)}Z._=Lp;var Ms=new Ne("+");function Zp(e,...t){let r=[Kr(e[0])],n=0;for(;n<t.length;)r.push(Ms),qs(r,t[n]),r.push(Ms,Kr(e[++n]));return Hw(r),new Ne(r)}Z.str=Zp;function qs(e,t){t instanceof Ne?e.push(...t._items):t instanceof zt?e.push(t):e.push(Jw(t))}Z.addCodeArg=qs;function Hw(e){let t=1;for(;t<e.length-1;){if(e[t]===Ms){let r=Gw(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Gw(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof zt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof zt))return`"${e}${t.slice(1)}`}function Ww(e,t){return t.emptyStr()?e:e.emptyStr()?t:Zp`${e}${t}`}Z.strConcat=Ww;function Jw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Kr(Array.isArray(e)?e.join(","):e)}function Qw(e){return new Ne(Kr(e))}Z.stringify=Qw;function Kr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=Kr;function Yw(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Ne(`.${e}`):Lp`[${e}]`}Z.getProperty=Yw;function Xw(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Ne(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=Xw;function eb(e){return new Ne(e.toString())}Z.regexpCode=eb});var Zs=v(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.ValueScope=Se.ValueScopeName=Se.Scope=Se.varKinds=Se.UsedValueState=void 0;var ke=Hr(),Bs=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},co;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(co||(Se.UsedValueState=co={}));Se.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var uo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof ke.Name?t:this.name(t)}name(t){return new ke.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Se.Scope=uo;var lo=class extends ke.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,ke._)`.${new ke.Name(r)}[${n}]`}};Se.ValueScopeName=lo;var tb=(0,ke._)`\n`,Ls=class extends uo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?tb:ke.nil}}get(){return this._scope}name(t){return new lo(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ke._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=ke.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,co.Started);let u=r(l);if(u){let d=this.opts.es5?Se.varKinds.var:Se.varKinds.const;i=(0,ke._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,ke._)`${i}${u}${this.opts._n}`;else throw new Bs(l);c.set(l,co.Completed)})}return i}};Se.ValueScope=Ls});var C=v(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.or=O.and=O.not=O.CodeGen=O.operators=O.varKinds=O.ValueScopeName=O.ValueScope=O.Scope=O.Name=O.regexpCode=O.stringify=O.getProperty=O.nil=O.strConcat=O.str=O._=void 0;var q=Hr(),Be=Zs(),ft=Hr();Object.defineProperty(O,"_",{enumerable:!0,get:function(){return ft._}});Object.defineProperty(O,"str",{enumerable:!0,get:function(){return ft.str}});Object.defineProperty(O,"strConcat",{enumerable:!0,get:function(){return ft.strConcat}});Object.defineProperty(O,"nil",{enumerable:!0,get:function(){return ft.nil}});Object.defineProperty(O,"getProperty",{enumerable:!0,get:function(){return ft.getProperty}});Object.defineProperty(O,"stringify",{enumerable:!0,get:function(){return ft.stringify}});Object.defineProperty(O,"regexpCode",{enumerable:!0,get:function(){return ft.regexpCode}});Object.defineProperty(O,"Name",{enumerable:!0,get:function(){return ft.Name}});var ho=Zs();Object.defineProperty(O,"Scope",{enumerable:!0,get:function(){return ho.Scope}});Object.defineProperty(O,"ValueScope",{enumerable:!0,get:function(){return ho.ValueScope}});Object.defineProperty(O,"ValueScopeName",{enumerable:!0,get:function(){return ho.ValueScopeName}});Object.defineProperty(O,"varKinds",{enumerable:!0,get:function(){return ho.varKinds}});O.operators={GT:new q._Code(">"),GTE:new q._Code(">="),LT:new q._Code("<"),LTE:new q._Code("<="),EQ:new q._Code("==="),NEQ:new q._Code("!=="),NOT:new q._Code("!"),OR:new q._Code("||"),AND:new q._Code("&&"),ADD:new q._Code("+")};var nt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Us=class extends nt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Be.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Jt(this.rhs,t,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},po=class extends nt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof q.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Jt(this.rhs,t,r),this}get names(){let t=this.lhs instanceof q.Name?{}:{...this.lhs.names};return mo(t,this.rhs)}},Fs=class extends po{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Vs=class extends nt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ks=class extends nt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Hs=class extends nt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Gs=class extends nt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Jt(this.code,t,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Gr=class extends nt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(rb(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>It(t,r.names),{})}},ot=class extends Gr{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ws=class extends Gr{},Wt=class extends ot{};Wt.kind="else";var Tt=class e extends ot{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Wt(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Up(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Jt(this.condition,t,r),this}get names(){let t=super.names;return mo(t,this.condition),this.else&&It(t,this.else.names),t}};Tt.kind="if";var Rt=class extends ot{};Rt.kind="for";var Js=class extends Rt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Jt(this.iteration,t,r),this}get names(){return It(super.names,this.iteration.names)}},Qs=class extends Rt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Be.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=mo(super.names,this.from);return mo(t,this.to)}},fo=class extends Rt{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Jt(this.iterable,t,r),this}get names(){return It(super.names,this.iterable.names)}},Wr=class extends ot{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Wr.kind="func";var Jr=class extends Gr{render(t){return"return "+super.render(t)}};Jr.kind="return";var Ys=class extends ot{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&It(t,this.catch.names),this.finally&&It(t,this.finally.names),t}},Qr=class extends ot{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Qr.kind="catch";var Yr=class extends ot{render(t){return"finally"+super.render(t)}};Yr.kind="finally";var Xs=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new Be.Scope({parent:t}),this._nodes=[new Ws]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new Us(t,i,n)),i}const(t,r,n){return this._def(Be.varKinds.const,t,r,n)}let(t,r,n){return this._def(Be.varKinds.let,t,r,n)}var(t,r,n){return this._def(Be.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new po(t,r,n))}add(t,r){return this._leafNode(new Fs(t,O.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==q.nil&&this._leafNode(new Gs(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,q.addCodeArg)(r,o));return r.push("}"),new q._Code(r)}if(t,r,n){if(this._blockNode(new Tt(t)),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(t){return this._elseNode(new Tt(t))}else(){return this._elseNode(new Wt)}endIf(){return this._endBlockNode(Tt,Wt)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Js(t),r)}forRange(t,r,n,o,i=this.opts.es5?Be.varKinds.var:Be.varKinds.let){let s=this._scope.toName(t);return this._for(new Qs(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Be.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${s}.length`,a=>{this.var(i,(0,q._)`${s}[${a}]`),n(i)})}return this._for(new fo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Be.varKinds.var:Be.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,q._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new fo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Rt)}label(t){return this._leafNode(new Vs(t))}break(t){return this._leafNode(new Ks(t))}return(t){let r=new Jr;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Jr)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ys;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new Qr(i),r(i)}return n&&(this._currNode=o.finally=new Yr,this.code(n)),this._endBlockNode(Qr,Yr)}throw(t){return this._leafNode(new Hs(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){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||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=q.nil,n,o){return this._blockNode(new Wr(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Wr)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Tt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};O.CodeGen=Xs;function It(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function mo(e,t){return t instanceof q._CodeOrName?It(e,t.names):e}function Jt(e,t,r){if(e instanceof q.Name)return n(e);if(!o(e))return e;return new q._Code(e._items.reduce((i,s)=>(s instanceof q.Name&&(s=n(s)),s instanceof q._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof q._Code&&i._items.some(s=>s instanceof q.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function rb(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Up(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,q._)`!${ea(e)}`}O.not=Up;var nb=Fp(O.operators.AND);function ob(...e){return e.reduce(nb)}O.and=ob;var ib=Fp(O.operators.OR);function sb(...e){return e.reduce(ib)}O.or=sb;function Fp(e){return(t,r)=>t===q.nil?r:r===q.nil?t:(0,q._)`${ea(t)} ${e} ${ea(r)}`}function ea(e){return e instanceof q.Name?e:(0,q._)`(${e})`}});var B=v(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;var K=C(),ab=Hr();function cb(e){let t={};for(let r of e)t[r]=!0;return t}D.toHash=cb;function ub(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Hp(e,t),!Gp(t,e.self.RULES.all))}D.alwaysValidSchema=ub;function Hp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||Qp(e,`unknown keyword: "${i}"`)}D.checkUnknownRules=Hp;function Gp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}D.schemaHasRules=Gp;function lb(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}D.schemaHasRulesButRef=lb;function db({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${e}${t}${(0,K.getProperty)(n)}`}D.schemaRefOrVal=db;function pb(e){return Wp(decodeURIComponent(e))}D.unescapeFragment=pb;function fb(e){return encodeURIComponent(ra(e))}D.escapeFragment=fb;function ra(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=ra;function Wp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=Wp;function mb(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}D.eachItem=mb;function Vp({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof K.Name?(i instanceof K.Name?e(o,i,s):t(o,i,s),s):i instanceof K.Name?(t(o,s,i),i):r(i,s);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}D.mergeEvaluated={props:Vp({mergeNames:(e,t,r)=>e.if((0,K._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,K._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,K._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,K._)`${r} || {}`),na(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Jp}),items:Vp({mergeNames:(e,t,r)=>e.if((0,K._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,K._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,K._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,K._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Jp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,K._)`{}`);return t!==void 0&&na(e,r,t),r}D.evaluatedPropsToName=Jp;function na(e,t,r){Object.keys(r).forEach(n=>e.assign((0,K._)`${t}${(0,K.getProperty)(n)}`,!0))}D.setEvaluated=na;var Kp={};function hb(e,t){return e.scopeValue("func",{ref:t,code:Kp[t.code]||(Kp[t.code]=new ab._Code(t.code))})}D.useFunc=hb;var ta;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ta||(D.Type=ta={}));function gb(e,t,r){if(e instanceof K.Name){let n=t===ta.Num;return r?n?(0,K._)`"[" + ${e} + "]"`:(0,K._)`"['" + ${e} + "']"`:n?(0,K._)`"/" + ${e}`:(0,K._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(e).toString():"/"+ra(e)}D.getErrorPath=gb;function Qp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=Qp});var it=v(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var me=C(),yb={data:new me.Name("data"),valCxt:new me.Name("valCxt"),instancePath:new me.Name("instancePath"),parentData:new me.Name("parentData"),parentDataProperty:new me.Name("parentDataProperty"),rootData:new me.Name("rootData"),dynamicAnchors:new me.Name("dynamicAnchors"),vErrors:new me.Name("vErrors"),errors:new me.Name("errors"),this:new me.Name("this"),self:new me.Name("self"),scope:new me.Name("scope"),json:new me.Name("json"),jsonPos:new me.Name("jsonPos"),jsonLen:new me.Name("jsonLen"),jsonPart:new me.Name("jsonPart")};oa.default=yb});var Xr=v(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.extendErrors=he.resetErrorsCount=he.reportExtraError=he.reportError=he.keyword$DataError=he.keywordError=void 0;var L=C(),go=B(),we=it();he.keywordError={message:({keyword:e})=>(0,L.str)`must pass "${e}" keyword validation`};he.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,L.str)`"${e}" keyword must be ${t} ($data)`:(0,L.str)`"${e}" keyword is invalid ($data)`};function _b(e,t=he.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=ef(e,t,r);n??(s||a)?Yp(i,c):Xp(o,(0,L._)`[${c}]`)}he.reportError=_b;function vb(e,t=he.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=ef(e,t,r);Yp(o,a),i||s||Xp(n,we.default.vErrors)}he.reportExtraError=vb;function wb(e,t){e.assign(we.default.errors,t),e.if((0,L._)`${we.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,L._)`${we.default.vErrors}.length`,t),()=>e.assign(we.default.vErrors,null)))}he.resetErrorsCount=wb;function bb({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,we.default.errors,a=>{e.const(s,(0,L._)`${we.default.vErrors}[${a}]`),e.if((0,L._)`${s}.instancePath === undefined`,()=>e.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(we.default.instancePath,i.errorPath))),e.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,L._)`${s}.schema`,r),e.assign((0,L._)`${s}.data`,n))})}he.extendErrors=bb;function Yp(e,t){let r=e.const("err",t);e.if((0,L._)`${we.default.vErrors} === null`,()=>e.assign(we.default.vErrors,(0,L._)`[${r}]`),(0,L._)`${we.default.vErrors}.push(${r})`),e.code((0,L._)`${we.default.errors}++`)}function Xp(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,L._)`new ${e.ValidationError}(${t})`):(r.assign((0,L._)`${n}.errors`,t),r.return(!1))}var At={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function ef(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,L._)`{}`:$b(e,t,r)}function $b(e,t,r={}){let{gen:n,it:o}=e,i=[xb(o,r),kb(e,r)];return Sb(e,t,i),n.object(...i)}function xb({errorPath:e},{instancePath:t}){let r=t?(0,L.str)`${e}${(0,go.getErrorPath)(t,go.Type.Str)}`:e;return[we.default.instancePath,(0,L.strConcat)(we.default.instancePath,r)]}function kb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,L.str)`${t}/${e}`;return r&&(o=(0,L.str)`${o}${(0,go.getErrorPath)(r,go.Type.Str)}`),[At.schemaPath,o]}function Sb(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([At.keyword,o],[At.params,typeof t=="function"?t(e):t||(0,L._)`{}`]),c.messages&&n.push([At.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([At.schema,s],[At.parentSchema,(0,L._)`${u}${d}`],[we.default.data,i]),l&&n.push([At.propertyName,l])}});var rf=v(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.boolOrEmptySchema=Qt.topBoolOrEmptySchema=void 0;var Eb=Xr(),Pb=C(),zb=it(),Tb={message:"boolean schema is false"};function Rb(e){let{gen:t,schema:r,validateName:n}=e;r===!1?tf(e,!1):typeof r=="object"&&r.$async===!0?t.return(zb.default.data):(t.assign((0,Pb._)`${n}.errors`,null),t.return(!0))}Qt.topBoolOrEmptySchema=Rb;function Ib(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),tf(e)):r.var(t,!0)}Qt.boolOrEmptySchema=Ib;function tf(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Eb.reportError)(o,Tb,void 0,t)}});var ia=v(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getRules=Yt.isJSONType=void 0;var Ab=["string","number","integer","boolean","null","object","array"],Nb=new Set(Ab);function Cb(e){return typeof e=="string"&&Nb.has(e)}Yt.isJSONType=Cb;function Ob(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Yt.getRules=Ob});var sa=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.shouldUseRule=mt.shouldUseGroup=mt.schemaHasRulesForType=void 0;function Db({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&nf(e,n)}mt.schemaHasRulesForType=Db;function nf(e,t){return t.rules.some(r=>of(e,r))}mt.shouldUseGroup=nf;function of(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}mt.shouldUseRule=of});var en=v(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.reportTypeError=ge.checkDataTypes=ge.checkDataType=ge.coerceAndCheckDataType=ge.getJSONTypes=ge.getSchemaTypes=ge.DataType=void 0;var jb=ia(),Mb=sa(),qb=Xr(),N=C(),sf=B(),Xt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Xt||(ge.DataType=Xt={}));function Bb(e){let t=af(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ge.getSchemaTypes=Bb;function af(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(jb.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ge.getJSONTypes=af;function Lb(e,t){let{gen:r,data:n,opts:o}=e,i=Zb(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,Mb.schemaHasRulesForType)(e,t[0]));if(s){let a=ca(t,n,o.strictNumbers,Xt.Wrong);r.if(a,()=>{i.length?Ub(e,t,i):ua(e)})}return s}ge.coerceAndCheckDataType=Lb;var cf=new Set(["string","number","integer","boolean","null"]);function Zb(e,t){return t?e.filter(r=>cf.has(r)||t==="array"&&r==="array"):[]}function Ub(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(ca(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(cf.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),ua(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),Fb(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
3
+ var Ly=Object.create;var _i=Object.defineProperty;var Zy=Object.getOwnPropertyDescriptor;var Uy=Object.getOwnPropertyNames;var Fy=Object.getPrototypeOf,Vy=Object.prototype.hasOwnProperty;var ct=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yu=(e,t)=>{for(var r in t)_i(e,r,{get:t[r],enumerable:!0})},Ky=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Uy(t))!Vy.call(e,o)&&o!==r&&_i(e,o,{get:()=>t[o],enumerable:!(n=Zy(t,o))||n.enumerable});return e};var vi=(e,t,r)=>(r=e!=null?Ly(Fy(e)):{},Ky(t||!e||!e.__esModule?_i(r,"default",{value:e,enumerable:!0}):r,e));var Hr=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.regexpCode=Z.getEsmExportName=Z.getProperty=Z.safeStringify=Z.stringify=Z.strConcat=Z.addCodeArg=Z.str=Z._=Z.nil=Z._Code=Z.Name=Z.IDENTIFIER=Z._CodeOrName=void 0;var Vr=class{};Z._CodeOrName=Vr;Z.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Tt=class extends Vr{constructor(t){if(super(),!Z.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Z.Name=Tt;var Ne=class extends Vr{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Tt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Z._Code=Ne;Z.nil=new Ne("");function Zp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)qs(r,t[n]),r.push(e[++n]);return new Ne(r)}Z._=Zp;var Ms=new Ne("+");function Up(e,...t){let r=[Kr(e[0])],n=0;for(;n<t.length;)r.push(Ms),qs(r,t[n]),r.push(Ms,Kr(e[++n]));return Gw(r),new Ne(r)}Z.str=Up;function qs(e,t){t instanceof Ne?e.push(...t._items):t instanceof Tt?e.push(t):e.push(Qw(t))}Z.addCodeArg=qs;function Gw(e){let t=1;for(;t<e.length-1;){if(e[t]===Ms){let r=Ww(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Ww(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Tt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Tt))return`"${e}${t.slice(1)}`}function Jw(e,t){return t.emptyStr()?e:e.emptyStr()?t:Up`${e}${t}`}Z.strConcat=Jw;function Qw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Kr(Array.isArray(e)?e.join(","):e)}function Yw(e){return new Ne(Kr(e))}Z.stringify=Yw;function Kr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Z.safeStringify=Kr;function Xw(e){return typeof e=="string"&&Z.IDENTIFIER.test(e)?new Ne(`.${e}`):Zp`[${e}]`}Z.getProperty=Xw;function eb(e){if(typeof e=="string"&&Z.IDENTIFIER.test(e))return new Ne(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Z.getEsmExportName=eb;function tb(e){return new Ne(e.toString())}Z.regexpCode=tb});var Zs=v(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.ValueScope=Se.ValueScopeName=Se.Scope=Se.varKinds=Se.UsedValueState=void 0;var ke=Hr(),Bs=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},co;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(co||(Se.UsedValueState=co={}));Se.varKinds={const:new ke.Name("const"),let:new ke.Name("let"),var:new ke.Name("var")};var uo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof ke.Name?t:this.name(t)}name(t){return new ke.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Se.Scope=uo;var lo=class extends ke.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,ke._)`.${new ke.Name(r)}[${n}]`}};Se.ValueScopeName=lo;var rb=(0,ke._)`\n`,Ls=class extends uo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?rb:ke.nil}}get(){return this._scope}name(t){return new lo(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:i,itemIndex:l}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ke._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=ke.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,co.Started);let u=r(l);if(u){let d=this.opts.es5?Se.varKinds.var:Se.varKinds.const;i=(0,ke._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,ke._)`${i}${u}${this.opts._n}`;else throw new Bs(l);c.set(l,co.Completed)})}return i}};Se.ValueScope=Ls});var C=v(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.or=O.and=O.not=O.CodeGen=O.operators=O.varKinds=O.ValueScopeName=O.ValueScope=O.Scope=O.Name=O.regexpCode=O.stringify=O.getProperty=O.nil=O.strConcat=O.str=O._=void 0;var q=Hr(),Be=Zs(),ft=Hr();Object.defineProperty(O,"_",{enumerable:!0,get:function(){return ft._}});Object.defineProperty(O,"str",{enumerable:!0,get:function(){return ft.str}});Object.defineProperty(O,"strConcat",{enumerable:!0,get:function(){return ft.strConcat}});Object.defineProperty(O,"nil",{enumerable:!0,get:function(){return ft.nil}});Object.defineProperty(O,"getProperty",{enumerable:!0,get:function(){return ft.getProperty}});Object.defineProperty(O,"stringify",{enumerable:!0,get:function(){return ft.stringify}});Object.defineProperty(O,"regexpCode",{enumerable:!0,get:function(){return ft.regexpCode}});Object.defineProperty(O,"Name",{enumerable:!0,get:function(){return ft.Name}});var ho=Zs();Object.defineProperty(O,"Scope",{enumerable:!0,get:function(){return ho.Scope}});Object.defineProperty(O,"ValueScope",{enumerable:!0,get:function(){return ho.ValueScope}});Object.defineProperty(O,"ValueScopeName",{enumerable:!0,get:function(){return ho.ValueScopeName}});Object.defineProperty(O,"varKinds",{enumerable:!0,get:function(){return ho.varKinds}});O.operators={GT:new q._Code(">"),GTE:new q._Code(">="),LT:new q._Code("<"),LTE:new q._Code("<="),EQ:new q._Code("==="),NEQ:new q._Code("!=="),NOT:new q._Code("!"),OR:new q._Code("||"),AND:new q._Code("&&"),ADD:new q._Code("+")};var nt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Us=class extends nt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Be.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Jt(this.rhs,t,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},po=class extends nt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof q.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Jt(this.rhs,t,r),this}get names(){let t=this.lhs instanceof q.Name?{}:{...this.lhs.names};return mo(t,this.rhs)}},Fs=class extends po{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Vs=class extends nt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ks=class extends nt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Hs=class extends nt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Gs=class extends nt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Jt(this.code,t,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Gr=class extends nt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(nb(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>It(t,r.names),{})}},ot=class extends Gr{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ws=class extends Gr{},Wt=class extends ot{};Wt.kind="else";var zt=class e extends ot{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Wt(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Fp(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Jt(this.condition,t,r),this}get names(){let t=super.names;return mo(t,this.condition),this.else&&It(t,this.else.names),t}};zt.kind="if";var Rt=class extends ot{};Rt.kind="for";var Js=class extends Rt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Jt(this.iteration,t,r),this}get names(){return It(super.names,this.iteration.names)}},Qs=class extends Rt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Be.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=mo(super.names,this.from);return mo(t,this.to)}},fo=class extends Rt{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Jt(this.iterable,t,r),this}get names(){return It(super.names,this.iterable.names)}},Wr=class extends ot{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Wr.kind="func";var Jr=class extends Gr{render(t){return"return "+super.render(t)}};Jr.kind="return";var Ys=class extends ot{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&It(t,this.catch.names),this.finally&&It(t,this.finally.names),t}},Qr=class extends ot{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Qr.kind="catch";var Yr=class extends ot{render(t){return"finally"+super.render(t)}};Yr.kind="finally";var Xs=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Be.Scope({parent:t}),this._nodes=[new Ws]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new Us(t,i,n)),i}const(t,r,n){return this._def(Be.varKinds.const,t,r,n)}let(t,r,n){return this._def(Be.varKinds.let,t,r,n)}var(t,r,n){return this._def(Be.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new po(t,r,n))}add(t,r){return this._leafNode(new Fs(t,O.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==q.nil&&this._leafNode(new Gs(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,q.addCodeArg)(r,o));return r.push("}"),new q._Code(r)}if(t,r,n){if(this._blockNode(new zt(t)),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(t){return this._elseNode(new zt(t))}else(){return this._elseNode(new Wt)}endIf(){return this._endBlockNode(zt,Wt)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Js(t),r)}forRange(t,r,n,o,i=this.opts.es5?Be.varKinds.var:Be.varKinds.let){let s=this._scope.toName(t);return this._for(new Qs(i,s,r,n),()=>o(s))}forOf(t,r,n,o=Be.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${s}.length`,a=>{this.var(i,(0,q._)`${s}[${a}]`),n(i)})}return this._for(new fo("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?Be.varKinds.var:Be.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,q._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new fo("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Rt)}label(t){return this._leafNode(new Vs(t))}break(t){return this._leafNode(new Ks(t))}return(t){let r=new Jr;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Jr)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ys;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new Qr(i),r(i)}return n&&(this._currNode=o.finally=new Yr,this.code(n)),this._endBlockNode(Qr,Yr)}throw(t){return this._leafNode(new Hs(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){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||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=q.nil,n,o){return this._blockNode(new Wr(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Wr)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof zt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};O.CodeGen=Xs;function It(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function mo(e,t){return t instanceof q._CodeOrName?It(e,t.names):e}function Jt(e,t,r){if(e instanceof q.Name)return n(e);if(!o(e))return e;return new q._Code(e._items.reduce((i,s)=>(s instanceof q.Name&&(s=n(s)),s instanceof q._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof q._Code&&i._items.some(s=>s instanceof q.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function nb(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Fp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,q._)`!${ea(e)}`}O.not=Fp;var ob=Vp(O.operators.AND);function ib(...e){return e.reduce(ob)}O.and=ib;var sb=Vp(O.operators.OR);function ab(...e){return e.reduce(sb)}O.or=ab;function Vp(e){return(t,r)=>t===q.nil?r:r===q.nil?t:(0,q._)`${ea(t)} ${e} ${ea(r)}`}function ea(e){return e instanceof q.Name?e:(0,q._)`(${e})`}});var B=v(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.checkStrictMode=D.getErrorPath=D.Type=D.useFunc=D.setEvaluated=D.evaluatedPropsToName=D.mergeEvaluated=D.eachItem=D.unescapeJsonPointer=D.escapeJsonPointer=D.escapeFragment=D.unescapeFragment=D.schemaRefOrVal=D.schemaHasRulesButRef=D.schemaHasRules=D.checkUnknownRules=D.alwaysValidSchema=D.toHash=void 0;var K=C(),cb=Hr();function ub(e){let t={};for(let r of e)t[r]=!0;return t}D.toHash=ub;function lb(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Gp(e,t),!Wp(t,e.self.RULES.all))}D.alwaysValidSchema=lb;function Gp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||Yp(e,`unknown keyword: "${i}"`)}D.checkUnknownRules=Gp;function Wp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}D.schemaHasRules=Wp;function db(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}D.schemaHasRulesButRef=db;function pb({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,K._)`${r}`}return(0,K._)`${e}${t}${(0,K.getProperty)(n)}`}D.schemaRefOrVal=pb;function fb(e){return Jp(decodeURIComponent(e))}D.unescapeFragment=fb;function mb(e){return encodeURIComponent(ra(e))}D.escapeFragment=mb;function ra(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}D.escapeJsonPointer=ra;function Jp(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}D.unescapeJsonPointer=Jp;function hb(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}D.eachItem=hb;function Kp({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof K.Name?(i instanceof K.Name?e(o,i,s):t(o,i,s),s):i instanceof K.Name?(t(o,s,i),i):r(i,s);return a===K.Name&&!(c instanceof K.Name)?n(o,c):c}}D.mergeEvaluated={props:Kp({mergeNames:(e,t,r)=>e.if((0,K._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,K._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,K._)`${r} || {}`).code((0,K._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,K._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,K._)`${r} || {}`),na(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Qp}),items:Kp({mergeNames:(e,t,r)=>e.if((0,K._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,K._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,K._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,K._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Qp(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,K._)`{}`);return t!==void 0&&na(e,r,t),r}D.evaluatedPropsToName=Qp;function na(e,t,r){Object.keys(r).forEach(n=>e.assign((0,K._)`${t}${(0,K.getProperty)(n)}`,!0))}D.setEvaluated=na;var Hp={};function gb(e,t){return e.scopeValue("func",{ref:t,code:Hp[t.code]||(Hp[t.code]=new cb._Code(t.code))})}D.useFunc=gb;var ta;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ta||(D.Type=ta={}));function yb(e,t,r){if(e instanceof K.Name){let n=t===ta.Num;return r?n?(0,K._)`"[" + ${e} + "]"`:(0,K._)`"['" + ${e} + "']"`:n?(0,K._)`"/" + ${e}`:(0,K._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,K.getProperty)(e).toString():"/"+ra(e)}D.getErrorPath=yb;function Yp(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}D.checkStrictMode=Yp});var it=v(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});var me=C(),_b={data:new me.Name("data"),valCxt:new me.Name("valCxt"),instancePath:new me.Name("instancePath"),parentData:new me.Name("parentData"),parentDataProperty:new me.Name("parentDataProperty"),rootData:new me.Name("rootData"),dynamicAnchors:new me.Name("dynamicAnchors"),vErrors:new me.Name("vErrors"),errors:new me.Name("errors"),this:new me.Name("this"),self:new me.Name("self"),scope:new me.Name("scope"),json:new me.Name("json"),jsonPos:new me.Name("jsonPos"),jsonLen:new me.Name("jsonLen"),jsonPart:new me.Name("jsonPart")};oa.default=_b});var Xr=v(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.extendErrors=he.resetErrorsCount=he.reportExtraError=he.reportError=he.keyword$DataError=he.keywordError=void 0;var L=C(),go=B(),we=it();he.keywordError={message:({keyword:e})=>(0,L.str)`must pass "${e}" keyword validation`};he.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,L.str)`"${e}" keyword must be ${t} ($data)`:(0,L.str)`"${e}" keyword is invalid ($data)`};function vb(e,t=he.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=tf(e,t,r);n??(s||a)?Xp(i,c):ef(o,(0,L._)`[${c}]`)}he.reportError=vb;function wb(e,t=he.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=tf(e,t,r);Xp(o,a),i||s||ef(n,we.default.vErrors)}he.reportExtraError=wb;function bb(e,t){e.assign(we.default.errors,t),e.if((0,L._)`${we.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,L._)`${we.default.vErrors}.length`,t),()=>e.assign(we.default.vErrors,null)))}he.resetErrorsCount=bb;function $b({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,we.default.errors,a=>{e.const(s,(0,L._)`${we.default.vErrors}[${a}]`),e.if((0,L._)`${s}.instancePath === undefined`,()=>e.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(we.default.instancePath,i.errorPath))),e.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,L._)`${s}.schema`,r),e.assign((0,L._)`${s}.data`,n))})}he.extendErrors=$b;function Xp(e,t){let r=e.const("err",t);e.if((0,L._)`${we.default.vErrors} === null`,()=>e.assign(we.default.vErrors,(0,L._)`[${r}]`),(0,L._)`${we.default.vErrors}.push(${r})`),e.code((0,L._)`${we.default.errors}++`)}function ef(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,L._)`new ${e.ValidationError}(${t})`):(r.assign((0,L._)`${n}.errors`,t),r.return(!1))}var At={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function tf(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,L._)`{}`:xb(e,t,r)}function xb(e,t,r={}){let{gen:n,it:o}=e,i=[kb(o,r),Sb(e,r)];return Eb(e,t,i),n.object(...i)}function kb({errorPath:e},{instancePath:t}){let r=t?(0,L.str)`${e}${(0,go.getErrorPath)(t,go.Type.Str)}`:e;return[we.default.instancePath,(0,L.strConcat)(we.default.instancePath,r)]}function Sb({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,L.str)`${t}/${e}`;return r&&(o=(0,L.str)`${o}${(0,go.getErrorPath)(r,go.Type.Str)}`),[At.schemaPath,o]}function Eb(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([At.keyword,o],[At.params,typeof t=="function"?t(e):t||(0,L._)`{}`]),c.messages&&n.push([At.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([At.schema,s],[At.parentSchema,(0,L._)`${u}${d}`],[we.default.data,i]),l&&n.push([At.propertyName,l])}});var nf=v(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.boolOrEmptySchema=Qt.topBoolOrEmptySchema=void 0;var Pb=Xr(),Tb=C(),zb=it(),Rb={message:"boolean schema is false"};function Ib(e){let{gen:t,schema:r,validateName:n}=e;r===!1?rf(e,!1):typeof r=="object"&&r.$async===!0?t.return(zb.default.data):(t.assign((0,Tb._)`${n}.errors`,null),t.return(!0))}Qt.topBoolOrEmptySchema=Ib;function Ab(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),rf(e)):r.var(t,!0)}Qt.boolOrEmptySchema=Ab;function rf(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Pb.reportError)(o,Rb,void 0,t)}});var ia=v(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getRules=Yt.isJSONType=void 0;var Nb=["string","number","integer","boolean","null","object","array"],Cb=new Set(Nb);function Ob(e){return typeof e=="string"&&Cb.has(e)}Yt.isJSONType=Ob;function Db(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Yt.getRules=Db});var sa=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.shouldUseRule=mt.shouldUseGroup=mt.schemaHasRulesForType=void 0;function jb({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&of(e,n)}mt.schemaHasRulesForType=jb;function of(e,t){return t.rules.some(r=>sf(e,r))}mt.shouldUseGroup=of;function sf(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}mt.shouldUseRule=sf});var en=v(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.reportTypeError=ge.checkDataTypes=ge.checkDataType=ge.coerceAndCheckDataType=ge.getJSONTypes=ge.getSchemaTypes=ge.DataType=void 0;var Mb=ia(),qb=sa(),Bb=Xr(),N=C(),af=B(),Xt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Xt||(ge.DataType=Xt={}));function Lb(e){let t=cf(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}ge.getSchemaTypes=Lb;function cf(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Mb.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ge.getJSONTypes=cf;function Zb(e,t){let{gen:r,data:n,opts:o}=e,i=Ub(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,qb.schemaHasRulesForType)(e,t[0]));if(s){let a=ca(t,n,o.strictNumbers,Xt.Wrong);r.if(a,()=>{i.length?Fb(e,t,i):ua(e)})}return s}ge.coerceAndCheckDataType=Zb;var uf=new Set(["string","number","integer","boolean","null"]);function Ub(e,t){return t?e.filter(r=>uf.has(r)||t==="array"&&r==="array"):[]}function Fb(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(ca(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let l of r)(uf.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),ua(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),Vb(e,a)});function c(l){switch(l){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null
5
5
  || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":n.elseIf((0,N._)`${s} === "boolean" || ${o} === null
6
6
  || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":n.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,N._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function Fb({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function aa(e,t,r,n=Xt.Correct){let o=n===Xt.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===Xt.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}ge.checkDataType=aa;function ca(e,t,r,n){if(e.length===1)return aa(e[0],t,r,n);let o,i=(0,sf.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,aa(s,t,r,n));return o}ge.checkDataTypes=ca;var Vb={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function ua(e){let t=Kb(e);(0,qb.reportError)(t,Vb)}ge.reportTypeError=ua;function Kb(e){let{gen:t,data:r,schema:n}=e,o=(0,sf.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var lf=v(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.assignDefaults=void 0;var er=C(),Hb=B();function Gb(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)uf(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>uf(e,i,o.default))}yo.assignDefaults=Gb;function uf(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,er._)`${i}${(0,er.getProperty)(t)}`;if(o){(0,Hb.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,er._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,er._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,er._)`${a} = ${(0,er.stringify)(r)}`)}});var Ce=v(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.validateUnion=V.validateArray=V.usePattern=V.callValidateCode=V.schemaProperties=V.allSchemaProperties=V.noPropertyInData=V.propertyInData=V.isOwnProperty=V.hasPropFunc=V.reportMissingProp=V.checkMissingProp=V.checkReportMissingProp=void 0;var Y=C(),la=B(),ht=it(),Wb=B();function Jb(e,t){let{gen:r,data:n,it:o}=e;r.if(pa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Y._)`${t}`},!0),e.error()})}V.checkReportMissingProp=Jb;function Qb({gen:e,data:t,it:{opts:r}},n,o){return(0,Y.or)(...n.map(i=>(0,Y.and)(pa(e,t,i,r.ownProperties),(0,Y._)`${o} = ${i}`)))}V.checkMissingProp=Qb;function Yb(e,t){e.setParams({missingProperty:t},!0),e.error()}V.reportMissingProp=Yb;function df(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Y._)`Object.prototype.hasOwnProperty`})}V.hasPropFunc=df;function da(e,t,r){return(0,Y._)`${df(e)}.call(${t}, ${r})`}V.isOwnProperty=da;function Xb(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} !== undefined`;return n?(0,Y._)`${o} && ${da(e,t,r)}`:o}V.propertyInData=Xb;function pa(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} === undefined`;return n?(0,Y.or)(o,(0,Y.not)(da(e,t,r))):o}V.noPropertyInData=pa;function pf(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}V.allSchemaProperties=pf;function e$(e,t){return pf(t).filter(r=>!(0,la.alwaysValidSchema)(e,t[r]))}V.schemaProperties=e$;function t$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,Y._)`${e}, ${t}, ${n}${o}`:t,d=[[ht.default.instancePath,(0,Y.strConcat)(ht.default.instancePath,i)],[ht.default.parentData,s.parentData],[ht.default.parentDataProperty,s.parentDataProperty],[ht.default.rootData,ht.default.rootData]];s.opts.dynamicRef&&d.push([ht.default.dynamicAnchors,ht.default.dynamicAnchors]);let p=(0,Y._)`${u}, ${r.object(...d)}`;return c!==Y.nil?(0,Y._)`${a}.call(${c}, ${p})`:(0,Y._)`${a}(${p})`}V.callValidateCode=t$;var r$=(0,Y._)`new RegExp`;function n$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Y._)`${o.code==="new RegExp"?r$:(0,Wb.useFunc)(e,o)}(${r}, ${n})`})}V.usePattern=n$;function o$(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,Y._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:la.Type.Num},i),t.if((0,Y.not)(i),a)})}}V.validateArray=o$;function i$(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,la.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,Y._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,Y.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}V.validateUnion=i$});var hf=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var be=C(),Nt=it(),s$=Ce(),a$=Xr();function c$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=mf(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:be.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Je.macroKeywordCode=c$;function u$(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;d$(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=mf(n,o,l),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)g(),t.modifying&&ff(e),_(()=>e.error());else{let w=t.async?f():h();t.modifying&&ff(e),_(()=>l$(e,w))}}function f(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,be._)`await `),b=>n.assign(d,!1).if((0,be._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,be._)`${b}.errors`),()=>n.throw(b))),w}function h(){let w=(0,be._)`${u}.errors`;return n.assign(w,null),g(be.nil),w}function g(w=t.async?(0,be._)`await `:be.nil){let b=c.opts.passContext?Nt.default.this:Nt.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,be._)`${w}${(0,s$.callValidateCode)(e,u,b,$)}`,t.modifying)}function _(w){var b;n.if((0,be.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}Je.funcKeywordCode=u$;function ff(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,be._)`${n.parentData}[${n.parentDataProperty}]`))}function l$(e,t){let{gen:r}=e;r.if((0,be._)`Array.isArray(${t})`,()=>{r.assign(Nt.default.vErrors,(0,be._)`${Nt.default.vErrors} === null ? ${t} : ${Nt.default.vErrors}.concat(${t})`).assign(Nt.default.errors,(0,be._)`${Nt.default.vErrors}.length`),(0,a$.extendErrors)(e)},()=>e.error())}function d$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function mf(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,be.stringify)(r)})}function p$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Je.validSchemaType=p$;function f$({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=f$});var yf=v(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extendSubschemaMode=gt.extendSubschemaData=gt.getSubschema=void 0;var Qe=C(),gf=B();function m$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Qe._)`${e.schemaPath}${(0,Qe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Qe._)`${e.schemaPath}${(0,Qe.getProperty)(t)}${(0,Qe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,gf.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}gt.getSubschema=m$;function h$(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,p=a.let("data",(0,Qe._)`${t.data}${(0,Qe.getProperty)(r)}`,!0);c(p),e.errorPath=(0,Qe.str)`${l}${(0,gf.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Qe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Qe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}gt.extendSubschemaData=h$;function g$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}gt.extendSubschemaMode=g$});var fa=v((e1,_f)=>{"use strict";_f.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var wf=v((t1,vf)=>{"use strict";var yt=vf.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};_o(t,n,o,e,"",e)};yt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yt.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 _o(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in yt.arrayKeywords)for(var p=0;p<d.length;p++)_o(e,t,r,d[p],o+"/"+u+"/"+p,i,o,u,n,p)}else if(u in yt.propsKeywords){if(d&&typeof d=="object")for(var f in d)_o(e,t,r,d[f],o+"/"+u+"/"+y$(f),i,o,u,n,f)}else(u in yt.keywords||e.allKeys&&!(u in yt.skipKeywords))&&_o(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function y$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var tn=v(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.getSchemaRefs=Ee.resolveUrl=Ee.normalizeId=Ee._getFullPath=Ee.getFullPath=Ee.inlineRef=void 0;var _$=B(),v$=fa(),w$=wf(),b$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ma(e):t?bf(e)<=t:!1}Ee.inlineRef=$$;var x$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ma(e){for(let t in e){if(x$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(ma)||typeof r=="object"&&ma(r))return!0}return!1}function bf(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!b$.has(r)&&(typeof e[r]=="object"&&(0,_$.eachItem)(e[r],n=>t+=bf(n)),t===1/0))return 1/0}return t}function $f(e,t="",r){r!==!1&&(t=tr(t));let n=e.parse(t);return xf(e,n)}Ee.getFullPath=$f;function xf(e,t){return e.serialize(t).split("#")[0]+"#"}Ee._getFullPath=xf;var k$=/#\/?$/;function tr(e){return e?e.replace(k$,""):""}Ee.normalizeId=tr;function S$(e,t,r){return r=tr(r),e.resolve(t,r)}Ee.resolveUrl=S$;var E$=/^[a-z_][-a-z0-9._]*$/i;function P$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=tr(e[r]||t),i={"":o},s=$f(n,o,!1),a={},c=new Set;return w$(e,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let g=s+p,_=i[h];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[p]=_;function w($){let P=this.opts.uriResolver.resolve;if($=tr(_?P(_,$):$),c.has($))throw u($);c.add($);let R=this.refs[$];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?l(d,R.schema,$):$!==tr(g)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=g),$}function b($){if(typeof $=="string"){if(!E$.test($))throw new Error(`invalid anchor "${$}"`);w.call(this,`#${$}`)}}}),a;function l(d,p,f){if(p!==void 0&&!v$(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ee.getSchemaRefs=P$});var on=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.getData=_t.KeywordCxt=_t.validateFunctionCode=void 0;var zf=rf(),kf=en(),ga=sa(),vo=en(),z$=lf(),nn=hf(),ha=yf(),S=C(),A=it(),T$=tn(),st=B(),rn=Xr();function R$(e){if(If(e)&&(Af(e),Rf(e))){N$(e);return}Tf(e,()=>(0,zf.topBoolOrEmptySchema)(e))}_t.validateFunctionCode=R$;function Tf({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Sf(r,o)}`),A$(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${I$(o)}`,n.$async,()=>e.code(Sf(r,o)).code(i))}function I$(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function A$(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function N$(e){let{schema:t,opts:r,gen:n}=e;Tf(e,()=>{r.$comment&&t.$comment&&Cf(e),M$(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&C$(e),Nf(e),L$(e)})}function C$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Sf(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function O$(e,t){if(If(e)&&(Af(e),Rf(e))){D$(e,t);return}(0,zf.boolOrEmptySchema)(e,t)}function Rf({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function If(e){return typeof e.schema!="boolean"}function D$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Cf(e),q$(e),B$(e);let i=n.const("_errs",A.default.errors);Nf(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function Af(e){(0,st.checkUnknownRules)(e),j$(e)}function Nf(e,t){if(e.opts.jtd)return Ef(e,[],!1,t);let r=(0,kf.getSchemaTypes)(e.schema),n=(0,kf.coerceAndCheckDataType)(e,r);Ef(e,r,!n,t)}function j$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,st.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function M$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,st.checkStrictMode)(e,"default is ignored in the schema root")}function q$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,T$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function B$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cf({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function L$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&Z$(e),t.return((0,S._)`${A.default.errors} === 0`))}function Z$({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function Ef(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,st.schemaHasRulesButRef)(i,u))){o.block(()=>Df(e,"$ref",u.all.$ref.definition));return}c.jtd||U$(e,t),o.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,ga.shouldUseGroup)(i,p)&&(p.type?(o.if((0,vo.checkDataType)(p.type,s,c.strictNumbers)),Pf(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,vo.reportTypeError)(e)),o.endIf()):Pf(e,p),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Pf(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,z$.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,ga.shouldUseRule)(n,i)&&Df(e,i.keyword,i.definition,t.type)})}function U$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(F$(e,t),e.opts.allowUnionTypes||V$(e,t),K$(e,e.dataTypes))}function F$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Of(e.dataTypes,r)||ya(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),G$(e,t)}}function V$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&ya(e,"use allowUnionTypes to allow union type keyword")}function K$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ga.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>H$(t,s))&&ya(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function H$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Of(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function G$(e,t){let r=[];for(let n of e.dataTypes)Of(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function ya(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,st.checkStrictMode)(e,t,e.opts.strictTypes)}var wo=class{constructor(t,r,n){if((0,nn.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,st.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",jf(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,nn.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=t.gen.const("_errs",A.default.errors))}result(t,r,n){this.failResult((0,S.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,S.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,S._)`${r} !== undefined && (${(0,S.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?rn.reportExtraError:rn.reportError)(this,this.def.error,r)}$dataError(){(0,rn.reportError)(this,this.def.$dataError||rn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,rn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,vo.checkDataTypes)(c,r,i.opts.strictNumbers,vo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,ha.getSubschema)(this.it,t);(0,ha.extendSubschemaData)(n,this.it,t),(0,ha.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return O$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=st.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=st.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};_t.KeywordCxt=wo;function Df(e,t,r,n){let o=new wo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,nn.funcKeywordCode)(o,r):"macro"in r?(0,nn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,nn.funcKeywordCode)(o,r)}var W$=/^\/(?:[^~]|~0|~1)*$/,J$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function jf(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!W$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=J$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,st.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}_t.getData=jf});var bo=v(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});var _a=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};va.default=_a});var sn=v($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});var wa=tn(),ba=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wa.resolveUrl)(t,r,n),this.missingSchema=(0,wa.normalizeId)((0,wa.getFullPath)(t,this.missingRef))}};$a.default=ba});var xo=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Le=C(),Q$=bo(),Ct=it(),Ze=tn(),Mf=B(),Y$=on(),rr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Ze.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Oe.SchemaEnv=rr;function ka(e){let t=qf.call(this,e);if(t)return t;let r=(0,Ze.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Le.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:Q$.default,code:(0,Le._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Ct.default.data,parentData:Ct.default.parentData,parentDataProperty:Ct.default.parentDataProperty,dataNames:[Ct.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Le._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,Y$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Ct.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let f=new Function(`${Ct.default.self}`,`${Ct.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:g}=l;f.evaluated={props:h instanceof Le.Name?void 0:h,items:g instanceof Le.Name?void 0:g,dynamicProps:h instanceof Le.Name,dynamicItems:g instanceof Le.Name},f.source&&(f.source.evaluated=(0,Le.stringify)(f.evaluated))}return e.validate=f,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}Oe.compileSchema=ka;function X$(e,t,r){var n;r=(0,Ze.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=r0.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new rr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=e0.call(this,i)}Oe.resolveRef=X$;function e0(e){return(0,Ze.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ka.call(this,e)}function qf(e){for(let t of this._compilations)if(t0(t,e))return t}Oe.getCompilingSchema=qf;function t0(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function r0(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||$o.call(this,e,t)}function $o(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ze._getFullPath)(this.opts.uriResolver,r),o=(0,Ze.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return xa.call(this,r,e);let i=(0,Ze.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=$o.call(this,e,s);return typeof a?.schema!="object"?void 0:xa.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||ka.call(this,s),i===(0,Ze.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ze.resolveUrl)(this.opts.uriResolver,o,l)),new rr({schema:a,schemaId:c,root:e,baseId:o})}return xa.call(this,r,s)}}Oe.resolveSchema=$o;var n0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xa(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Mf.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!n0.has(a)&&l&&(t=(0,Ze.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Mf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ze.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=$o.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new rr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var Bf=v((a1,o0)=>{o0.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 Pa=v((c1,Kf)=>{"use strict";var i0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Zf=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),Sa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Uf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s0=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ea(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var a0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Lf(e){return e.length=0,!0}function c0(e,t,r){if(e.length){let n=Ea(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function u0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=c0;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Lf}else{o.push(l);continue}}return o.length&&(a===Lf?r.zone=o.join(""):s?n.push(o.join("")):n.push(Ea(o))),r.address=n.join(""),r}function Ff(e){if(l0(e,":")<2)return{host:e,isIPV6:!1};let t=u0(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function l0(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function d0(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var p0={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},f0=/[@/?#:]/g,m0=/[@/?#]/g;function Vf(e,t){let r=t?m0:f0;return r.lastIndex=0,e.replace(r,n=>p0[n])}function h0(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Sa(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Uf(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function g0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Sa(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Uf(i)?t+=i:t+="%"+o,r+=2;continue}}s0(e[r])?t+=e[r]:t+=escape(e[r])}return t}function y0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Sa(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function _0(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Zf(r)){let n=Ff(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Vf(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}Kf.exports={nonSimpleDomain:a0,recomposeAuthority:_0,reescapeHostDelimiters:Vf,normalizePercentEncoding:h0,normalizePathEncoding:g0,escapePreservingEscapes:y0,removeDotSegments:d0,isIPv4:Zf,isUUID:i0,normalizeIPv6:Ff,stringArrayToHexStripped:Ea}});var Qf=v((u1,Jf)=>{"use strict";var{isUUID:v0}=Pa(),w0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,b0=["http","https","ws","wss","urn","urn:uuid"];function $0(e){return b0.indexOf(e)!==-1}function za(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Hf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Gf(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function x0(e){return e.secure=za(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function k0(e){if((e.port===(za(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function S0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(w0);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=Ta(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function E0(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=Ta(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function P0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!v0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function z0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Wf={scheme:"http",domainHost:!0,parse:Hf,serialize:Gf},T0={scheme:"https",domainHost:Wf.domainHost,parse:Hf,serialize:Gf},ko={scheme:"ws",domainHost:!0,parse:x0,serialize:k0},R0={scheme:"wss",domainHost:ko.domainHost,parse:ko.parse,serialize:ko.serialize},I0={scheme:"urn",parse:S0,serialize:E0,skipNormalize:!0},A0={scheme:"urn:uuid",parse:P0,serialize:z0,skipNormalize:!0},So={http:Wf,https:T0,ws:ko,wss:R0,urn:I0,"urn:uuid":A0};Object.setPrototypeOf(So,null);function Ta(e){return e&&(So[e]||So[e.toLowerCase()])||void 0}Jf.exports={wsIsSecure:za,SCHEMES:So,isValidSchemeName:$0,getSchemeHandler:Ta}});var nm=v((l1,Eo)=>{"use strict";var{normalizeIPv6:N0,removeDotSegments:an,recomposeAuthority:C0,normalizePercentEncoding:O0,normalizePathEncoding:D0,escapePreservingEscapes:j0,reescapeHostDelimiters:M0,isIPv4:q0,nonSimpleDomain:B0}=Pa(),{SCHEMES:L0,getSchemeHandler:Xf}=Qf();function Z0(e,t){return typeof e=="string"?e=H0(e,t):typeof e=="object"&&(e=nr(Ot(e,t),t)),e}function U0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=em(nr(e,n),nr(t,n),n,!0);return n.skipEscape=!0,Ot(o,n)}function em(e,t,r,n){let o={};return n||(e=nr(Ot(e,r),r),t=nr(Ot(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=an(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=an(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=an(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=an(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function F0(e,t,r){let n=Yf(e,r),o=Yf(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ot(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],i=Xf(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=O0(r.path):(r.path=j0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=C0(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=an(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var V0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function K0(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function tm(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(V0);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=K0(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(q0(n.host)===!1){let u=N0(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=Xf(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&B0(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=M0(unescape(n.host),i))),n.path&&(n.path=D0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function nr(e,t){return tm(e,t).parsed}function H0(e,t){return rm(e,t).normalized}function rm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=tm(e,t);return{normalized:n?e:Ot(r,t),malformedAuthorityOrPort:n}}function Yf(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=rm(e,t);return n?void 0:r}if(typeof e=="object")return Ot(e,t)}var Ra={SCHEMES:L0,normalize:Z0,resolve:U0,resolveComponent:em,equal:F0,serialize:Ot,parse:nr};Eo.exports=Ra;Eo.exports.default=Ra;Eo.exports.fastUri=Ra});var im=v(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var om=nm();om.code='require("ajv/dist/runtime/uri").default';Ia.default=om});var fm=v(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=void 0;var G0=on();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return G0.KeywordCxt}});var or=C();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return or._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return or.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return or.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return or.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return or.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return or.CodeGen}});var W0=bo(),lm=sn(),J0=ia(),cn=xo(),Q0=C(),un=tn(),Po=en(),Na=B(),sm=Bf(),Y0=im(),dm=(e,t)=>new RegExp(e,t);dm.code="new RegExp";var X0=["removeAdditional","useDefaults","coerceTypes"],ex=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),tx={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."},rx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},am=200;function nx(e){var t,r,n,o,i,s,a,c,l,u,d,p,f,h,g,_,w,b,$,P,R,_e,Te,Zt,gi;let $r=e.strict,yi=(t=e.code)===null||t===void 0?void 0:t.optimize,mu=yi===!0||yi===void 0?1:yi||0,hu=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:dm,qy=(o=e.uriResolver)!==null&&o!==void 0?o:Y0.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:$r)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:$r)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:$r)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:$r)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=e.strictRequired)!==null&&f!==void 0?f:$r)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:mu,regExp:hu}:{optimize:mu,regExp:hu},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:am,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:am,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(_e=e.validateSchema)!==null&&_e!==void 0?_e:!0,validateFormats:(Te=e.validateFormats)!==null&&Te!==void 0?Te:!0,unicodeRegExp:(Zt=e.unicodeRegExp)!==null&&Zt!==void 0?Zt:!0,int32range:(gi=e.int32range)!==null&&gi!==void 0?gi:!0,uriResolver:qy}}var ln=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...nx(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Q0.ValueScope({scope:{},prefixes:ex,es5:r,lines:n}),this.logger=ux(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,J0.getRules)(),cm.call(this,tx,t,"NOT SUPPORTED"),cm.call(this,rx,t,"DEPRECATED","warn"),this._metaOpts=ax.call(this),t.formats&&ix.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&sx.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),ox.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=sm;n==="id"&&(o={...sm},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(u,d){await i.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof lm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,un.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,t);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=um.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new cn.SchemaEnv({schema:{},schemaId:n});if(r=cn.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=um.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,un.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,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(dx.call(this,n,r),!r)return(0,Na.eachItem)(n,i=>Aa.call(this,i)),this;fx.call(this,r);let o={...r,type:(0,Po.getJSONTypes)(r.type),schemaType:(0,Po.getJSONTypes)(r.schemaType)};return(0,Na.eachItem)(n,o.type.length===0?i=>Aa.call(this,i,o):i=>o.type.forEach(s=>Aa.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=pm(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,un.normalizeId)(s||n);let l=un.getSchemaRefs.call(this,t,n);return c=new cn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):cn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{cn.compileSchema.call(this,t)}finally{this.opts=r}}};ln.ValidationError=W0.default;ln.MissingRefError=lm.default;de.default=ln;function cm(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function um(e){return e=(0,un.normalizeId)(e),this.schemas[e]||this.refs[e]}function ox(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ix(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function sx(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function ax(){let e={...this.opts};for(let t of X0)delete e[t];return e}var cx={log(){},warn(){},error(){}};function ux(e){if(e===!1)return cx;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var lx=/^[a-z_$][a-z0-9_$:-]*$/i;function dx(e,t){let{RULES:r}=this;if((0,Na.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!lx.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Aa(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Po.getJSONTypes)(t.type),schemaType:(0,Po.getJSONTypes)(t.schemaType)}};t.before?px.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function px(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function fx(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=pm(t)),e.validateSchema=this.compile(t,!0))}var mx={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pm(e){return{anyOf:[e,mx]}}});var mm=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var hx={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ca.default=hx});var _m=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.callRef=Dt.getValidate=void 0;var gx=sn(),hm=Ce(),Pe=C(),ir=it(),gm=xo(),zo=B(),yx={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=gm.resolveRef.call(c,l,o,r);if(u===void 0)throw new gx.default(n.opts.uriResolver,o,r);if(u instanceof gm.SchemaEnv)return p(u);return f(u);function d(){if(i===l)return To(e,s,i,i.$async);let h=t.scopeValue("root",{ref:l});return To(e,(0,Pe._)`${h}.validate`,l,l.$async)}function p(h){let g=ym(e,h);To(e,g,h,h.$async)}function f(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pe.stringify)(h)}:{ref:h}),_=t.name("valid"),w=e.subschema({schema:h,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:g,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function ym(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Dt.getValidate=ym;function To(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?ir.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,hm.callValidateCode)(e,t,l)}`),f(t),s||o.assign(h,!0)},g=>{o.if((0,Pe._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),p(g),s||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,hm.callValidateCode)(e,t,l),()=>f(t),()=>p(t))}function p(h){let g=(0,Pe._)`${h}.errors`;o.assign(ir.default.vErrors,(0,Pe._)`${ir.default.vErrors} === null ? ${g} : ${ir.default.vErrors}.concat(${g})`),o.assign(ir.default.errors,(0,Pe._)`${ir.default.vErrors}.length`)}function f(h){var g;if(!i.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=zo.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Pe._)`${h}.evaluated.props`);i.props=zo.mergeEvaluated.props(o,w,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=zo.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Pe._)`${h}.evaluated.items`);i.items=zo.mergeEvaluated.items(o,w,i.items,Pe.Name)}}}Dt.callRef=To;Dt.default=yx});var vm=v(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var _x=mm(),vx=_m(),wx=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_x.default,vx.default];Oa.default=wx});var wm=v(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var Ro=C(),vt=Ro.operators,Io={maximum:{okStr:"<=",ok:vt.LTE,fail:vt.GT},minimum:{okStr:">=",ok:vt.GTE,fail:vt.LT},exclusiveMaximum:{okStr:"<",ok:vt.LT,fail:vt.GTE},exclusiveMinimum:{okStr:">",ok:vt.GT,fail:vt.LTE}},bx={message:({keyword:e,schemaCode:t})=>(0,Ro.str)`must be ${Io[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ro._)`{comparison: ${Io[e].okStr}, limit: ${t}}`},$x={keyword:Object.keys(Io),type:"number",schemaType:"number",$data:!0,error:bx,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Ro._)`${r} ${Io[t].fail} ${n} || isNaN(${r})`)}};Da.default=$x});var bm=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var dn=C(),xx={message:({schemaCode:e})=>(0,dn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,dn._)`{multipleOf: ${e}}`},kx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:xx,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,dn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,dn._)`${s} !== parseInt(${s})`;e.fail$data((0,dn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};ja.default=kx});var xm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});function $m(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Ma.default=$m;$m.code='require("ajv/dist/runtime/ucs2length").default'});var km=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var jt=C(),Sx=B(),Ex=xm(),Px={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,jt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,jt._)`{limit: ${e}}`},zx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Px,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?jt.operators.GT:jt.operators.LT,s=o.opts.unicode===!1?(0,jt._)`${r}.length`:(0,jt._)`${(0,Sx.useFunc)(e.gen,Ex.default)}(${r})`;e.fail$data((0,jt._)`${s} ${i} ${n}`)}};qa.default=zx});var Sm=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var Tx=Ce(),Rx=B(),sr=C(),Ix={message:({schemaCode:e})=>(0,sr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,sr._)`{pattern: ${e}}`},Ax={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ix,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,sr._)`new RegExp`:(0,Rx.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,sr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,sr._)`!${u}`)}else{let c=(0,Tx.usePattern)(e,o);e.fail$data((0,sr._)`!${c}.test(${r})`)}}};Ba.default=Ax});var Em=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var pn=C(),Nx={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,pn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,pn._)`{limit: ${e}}`},Cx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Nx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?pn.operators.GT:pn.operators.LT;e.fail$data((0,pn._)`Object.keys(${r}).length ${o} ${n}`)}};La.default=Cx});var Pm=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var fn=Ce(),mn=C(),Ox=B(),Dx={message:({params:{missingProperty:e}})=>(0,mn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,mn._)`{missingProperty: ${e}}`},jx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Dx,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let f=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(f?.[g]===void 0&&!h.has(g)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,Ox.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(mn.nil,d);else for(let f of r)(0,fn.checkReportMissingProp)(e,f)}function u(){let f=t.let("missing");if(c||i){let h=t.let("valid",!0);e.block$data(h,()=>p(f,h)),e.ok(h)}else t.if((0,fn.checkMissingProp)(e,r,f)),(0,fn.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",n,f=>{e.setParams({missingProperty:f}),t.if((0,fn.noPropertyInData)(t,o,f,a.ownProperties),()=>e.error())})}function p(f,h){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(h,(0,fn.propertyInData)(t,o,f,a.ownProperties)),t.if((0,mn.not)(h),()=>{e.error(),t.break()})},mn.nil)}}};Za.default=jx});var zm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var hn=C(),Mx={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,hn._)`{limit: ${e}}`},qx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Mx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?hn.operators.GT:hn.operators.LT;e.fail$data((0,hn._)`${r}.length ${o} ${n}`)}};Ua.default=qx});var Ao=v(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Tm=fa();Tm.code='require("ajv/dist/runtime/equal").default';Fa.default=Tm});var Rm=v(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Va=en(),pe=C(),Bx=B(),Lx=Ao(),Zx={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},Ux={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Zx,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,Va.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let h=t.let("i",(0,pe._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,pe._)`${h} > 1`,()=>(d()?p:f)(h,g))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function p(h,g){let _=t.name("item"),w=(0,Va.checkDataTypes)(l,_,a.opts.strictNumbers,Va.DataType.Wrong),b=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${h}--;`,()=>{t.let(_,(0,pe._)`${r}[${h}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(g,(0,pe._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${b}[${_}] = ${h}`)})}function f(h,g){let _=(0,Bx.useFunc)(t,Lx.default),w=t.name("outer");t.label(w).for((0,pe._)`;${h}--;`,()=>t.for((0,pe._)`${g} = ${h}; ${g}--;`,()=>t.if((0,pe._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};Ka.default=Ux});var Im=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Ha=C(),Fx=B(),Vx=Ao(),Kx={message:"must be equal to constant",params:({schemaCode:e})=>(0,Ha._)`{allowedValue: ${e}}`},Hx={keyword:"const",$data:!0,error:Kx,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Ha._)`!${(0,Fx.useFunc)(t,Vx.default)}(${r}, ${o})`):e.fail((0,Ha._)`${i} !== ${r}`)}};Ga.default=Hx});var Am=v(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var gn=C(),Gx=B(),Wx=Ao(),Jx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,gn._)`{allowedValues: ${e}}`},Qx={keyword:"enum",schemaType:"array",$data:!0,error:Jx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,Gx.useFunc)(t,Wx.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=t.const("vSchema",i);u=(0,gn.or)(...o.map((h,g)=>p(f,g)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,f=>t.if((0,gn._)`${l()}(${r}, ${f})`,()=>t.assign(u,!0).break()))}function p(f,h){let g=o[h];return typeof g=="object"&&g!==null?(0,gn._)`${l()}(${r}, ${f}[${h}])`:(0,gn._)`${r} === ${g}`}}};Wa.default=Qx});var Nm=v(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Yx=wm(),Xx=bm(),ek=km(),tk=Sm(),rk=Em(),nk=Pm(),ok=zm(),ik=Rm(),sk=Im(),ak=Am(),ck=[Yx.default,Xx.default,ek.default,tk.default,rk.default,nk.default,ok.default,ik.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sk.default,ak.default];Ja.default=ck});var Ya=v(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateAdditionalItems=void 0;var Mt=C(),Qa=B(),uk={message:({params:{len:e}})=>(0,Mt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Mt._)`{limit: ${e}}`},lk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:uk,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Qa.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Cm(e,n)}};function Cm(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Mt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Mt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Qa.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Mt._)`${a} <= ${t.length}`);r.if((0,Mt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Qa.Type.Num},l),s.allErrors||r.if((0,Mt.not)(l),()=>r.break())})}}yn.validateAdditionalItems=Cm;yn.default=lk});var Xa=v(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.validateTuple=void 0;var Om=C(),No=B(),dk=Ce(),pk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Dm(e,"additionalItems",t);r.items=!0,!(0,No.alwaysValidSchema)(r,t)&&e.ok((0,dk.validateArray)(e))}};function Dm(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=No.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Om._)`${i}.length`);r.forEach((d,p)=>{(0,No.alwaysValidSchema)(a,d)||(n.if((0,Om._)`${l} > ${p}`,()=>e.subschema({keyword:s,schemaProp:p,dataProp:p},c)),e.ok(c))});function u(d){let{opts:p,errSchemaPath:f}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(p.strictTuples&&!g){let _=`"${s}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,No.checkStrictMode)(a,_,p.strictTuples)}}}_n.validateTuple=Dm;_n.default=pk});var jm=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var fk=Xa(),mk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,fk.validateTuple)(e,"items")};ec.default=mk});var qm=v(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Mm=C(),hk=B(),gk=Ce(),yk=Ya(),_k={message:({params:{len:e}})=>(0,Mm.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Mm._)`{limit: ${e}}`},vk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_k,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,hk.alwaysValidSchema)(n,t)&&(o?(0,yk.validateAdditionalItems)(e,o):e.ok((0,gk.validateArray)(e)))}};tc.default=vk});var Bm=v(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var De=C(),Co=B(),wk={message:({params:{min:e,max:t}})=>t===void 0?(0,De.str)`must contain at least ${e} valid item(s)`:(0,De.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,De._)`{minContains: ${e}}`:(0,De._)`{minContains: ${e}, maxContains: ${t}}`},bk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,De._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Co.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Co.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Co.alwaysValidSchema)(i,r)){let g=(0,De._)`${u} >= ${s}`;a!==void 0&&(g=(0,De._)`${g} && ${u} <= ${a}`),e.pass(g);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?f(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,De._)`${o}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let g=t.name("_valid"),_=t.let("count",0);f(g,()=>t.if(g,()=>h(_)))}function f(g,_){t.forRange("i",0,u,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Co.Type.Num,compositeRule:!0},g),_()})}function h(g){t.code((0,De._)`${g}++`),a===void 0?t.if((0,De._)`${g} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,De._)`${g} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,De._)`${g} >= ${s}`,()=>t.assign(d,!0)))}}};rc.default=bk});var Um=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateSchemaDeps=Ye.validatePropertyDeps=Ye.error=void 0;var nc=C(),$k=B(),vn=Ce();Ye.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,nc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,nc._)`{property: ${e},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function Vb({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function aa(e,t,r,n=Xt.Correct){let o=n===Xt.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===Xt.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}ge.checkDataType=aa;function ca(e,t,r,n){if(e.length===1)return aa(e[0],t,r,n);let o,i=(0,af.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,aa(s,t,r,n));return o}ge.checkDataTypes=ca;var Kb={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function ua(e){let t=Hb(e);(0,Bb.reportError)(t,Kb)}ge.reportTypeError=ua;function Hb(e){let{gen:t,data:r,schema:n}=e,o=(0,af.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var df=v(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.assignDefaults=void 0;var er=C(),Gb=B();function Wb(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)lf(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>lf(e,i,o.default))}yo.assignDefaults=Wb;function lf(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,er._)`${i}${(0,er.getProperty)(t)}`;if(o){(0,Gb.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,er._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,er._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,er._)`${a} = ${(0,er.stringify)(r)}`)}});var Ce=v(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.validateUnion=V.validateArray=V.usePattern=V.callValidateCode=V.schemaProperties=V.allSchemaProperties=V.noPropertyInData=V.propertyInData=V.isOwnProperty=V.hasPropFunc=V.reportMissingProp=V.checkMissingProp=V.checkReportMissingProp=void 0;var Y=C(),la=B(),ht=it(),Jb=B();function Qb(e,t){let{gen:r,data:n,it:o}=e;r.if(pa(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Y._)`${t}`},!0),e.error()})}V.checkReportMissingProp=Qb;function Yb({gen:e,data:t,it:{opts:r}},n,o){return(0,Y.or)(...n.map(i=>(0,Y.and)(pa(e,t,i,r.ownProperties),(0,Y._)`${o} = ${i}`)))}V.checkMissingProp=Yb;function Xb(e,t){e.setParams({missingProperty:t},!0),e.error()}V.reportMissingProp=Xb;function pf(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Y._)`Object.prototype.hasOwnProperty`})}V.hasPropFunc=pf;function da(e,t,r){return(0,Y._)`${pf(e)}.call(${t}, ${r})`}V.isOwnProperty=da;function e$(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} !== undefined`;return n?(0,Y._)`${o} && ${da(e,t,r)}`:o}V.propertyInData=e$;function pa(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} === undefined`;return n?(0,Y.or)(o,(0,Y.not)(da(e,t,r))):o}V.noPropertyInData=pa;function ff(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}V.allSchemaProperties=ff;function t$(e,t){return ff(t).filter(r=>!(0,la.alwaysValidSchema)(e,t[r]))}V.schemaProperties=t$;function r$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,Y._)`${e}, ${t}, ${n}${o}`:t,d=[[ht.default.instancePath,(0,Y.strConcat)(ht.default.instancePath,i)],[ht.default.parentData,s.parentData],[ht.default.parentDataProperty,s.parentDataProperty],[ht.default.rootData,ht.default.rootData]];s.opts.dynamicRef&&d.push([ht.default.dynamicAnchors,ht.default.dynamicAnchors]);let p=(0,Y._)`${u}, ${r.object(...d)}`;return c!==Y.nil?(0,Y._)`${a}.call(${c}, ${p})`:(0,Y._)`${a}(${p})`}V.callValidateCode=r$;var n$=(0,Y._)`new RegExp`;function o$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Y._)`${o.code==="new RegExp"?n$:(0,Jb.useFunc)(e,o)}(${r}, ${n})`})}V.usePattern=o$;function i$(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,Y._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:la.Type.Num},i),t.if((0,Y.not)(i),a)})}}V.validateArray=i$;function s$(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,la.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);t.assign(s,(0,Y._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,Y.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}V.validateUnion=s$});var gf=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var be=C(),Nt=it(),a$=Ce(),c$=Xr();function u$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=hf(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:be.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}Je.macroKeywordCode=u$;function l$(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;p$(c,t);let l=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=hf(n,o,l),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)g(),t.modifying&&mf(e),_(()=>e.error());else{let w=t.async?f():h();t.modifying&&mf(e),_(()=>d$(e,w))}}function f(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,be._)`await `),b=>n.assign(d,!1).if((0,be._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,be._)`${b}.errors`),()=>n.throw(b))),w}function h(){let w=(0,be._)`${u}.errors`;return n.assign(w,null),g(be.nil),w}function g(w=t.async?(0,be._)`await `:be.nil){let b=c.opts.passContext?Nt.default.this:Nt.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,be._)`${w}${(0,a$.callValidateCode)(e,u,b,$)}`,t.modifying)}function _(w){var b;n.if((0,be.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}Je.funcKeywordCode=l$;function mf(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,be._)`${n.parentData}[${n.parentDataProperty}]`))}function d$(e,t){let{gen:r}=e;r.if((0,be._)`Array.isArray(${t})`,()=>{r.assign(Nt.default.vErrors,(0,be._)`${Nt.default.vErrors} === null ? ${t} : ${Nt.default.vErrors}.concat(${t})`).assign(Nt.default.errors,(0,be._)`${Nt.default.vErrors}.length`),(0,c$.extendErrors)(e)},()=>e.error())}function p$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function hf(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,be.stringify)(r)})}function f$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Je.validSchemaType=f$;function m$({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=m$});var _f=v(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.extendSubschemaMode=gt.extendSubschemaData=gt.getSubschema=void 0;var Qe=C(),yf=B();function h$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Qe._)`${e.schemaPath}${(0,Qe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Qe._)`${e.schemaPath}${(0,Qe.getProperty)(t)}${(0,Qe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,yf.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}gt.getSubschema=h$;function g$(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,p=a.let("data",(0,Qe._)`${t.data}${(0,Qe.getProperty)(r)}`,!0);c(p),e.errorPath=(0,Qe.str)`${l}${(0,yf.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Qe._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Qe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}gt.extendSubschemaData=g$;function y$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}gt.extendSubschemaMode=y$});var fa=v((i1,vf)=>{"use strict";vf.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var bf=v((s1,wf)=>{"use strict";var yt=wf.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};_o(t,n,o,e,"",e)};yt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yt.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 _o(e,t,r,n,o,i,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in yt.arrayKeywords)for(var p=0;p<d.length;p++)_o(e,t,r,d[p],o+"/"+u+"/"+p,i,o,u,n,p)}else if(u in yt.propsKeywords){if(d&&typeof d=="object")for(var f in d)_o(e,t,r,d[f],o+"/"+u+"/"+_$(f),i,o,u,n,f)}else(u in yt.keywords||e.allKeys&&!(u in yt.skipKeywords))&&_o(e,t,r,d,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,l)}}function _$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var tn=v(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.getSchemaRefs=Ee.resolveUrl=Ee.normalizeId=Ee._getFullPath=Ee.getFullPath=Ee.inlineRef=void 0;var v$=B(),w$=fa(),b$=bf(),$$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function x$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ma(e):t?$f(e)<=t:!1}Ee.inlineRef=x$;var k$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ma(e){for(let t in e){if(k$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(ma)||typeof r=="object"&&ma(r))return!0}return!1}function $f(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!$$.has(r)&&(typeof e[r]=="object"&&(0,v$.eachItem)(e[r],n=>t+=$f(n)),t===1/0))return 1/0}return t}function xf(e,t="",r){r!==!1&&(t=tr(t));let n=e.parse(t);return kf(e,n)}Ee.getFullPath=xf;function kf(e,t){return e.serialize(t).split("#")[0]+"#"}Ee._getFullPath=kf;var S$=/#\/?$/;function tr(e){return e?e.replace(S$,""):""}Ee.normalizeId=tr;function E$(e,t,r){return r=tr(r),e.resolve(t,r)}Ee.resolveUrl=E$;var P$=/^[a-z_][-a-z0-9._]*$/i;function T$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=tr(e[r]||t),i={"":o},s=xf(n,o,!1),a={},c=new Set;return b$(e,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let g=s+p,_=i[h];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),i[p]=_;function w($){let P=this.opts.uriResolver.resolve;if($=tr(_?P(_,$):$),c.has($))throw u($);c.add($);let R=this.refs[$];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?l(d,R.schema,$):$!==tr(g)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=g),$}function b($){if(typeof $=="string"){if(!P$.test($))throw new Error(`invalid anchor "${$}"`);w.call(this,`#${$}`)}}}),a;function l(d,p,f){if(p!==void 0&&!w$(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ee.getSchemaRefs=T$});var on=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.getData=_t.KeywordCxt=_t.validateFunctionCode=void 0;var zf=nf(),Sf=en(),ga=sa(),vo=en(),z$=df(),nn=gf(),ha=_f(),S=C(),A=it(),R$=tn(),st=B(),rn=Xr();function I$(e){if(Af(e)&&(Nf(e),If(e))){C$(e);return}Rf(e,()=>(0,zf.topBoolOrEmptySchema)(e))}_t.validateFunctionCode=I$;function Rf({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,S._)`${A.default.data}, ${A.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${Ef(r,o)}`),N$(e,o),e.code(i)}):e.func(t,(0,S._)`${A.default.data}, ${A$(o)}`,n.$async,()=>e.code(Ef(r,o)).code(i))}function A$(e){return(0,S._)`{${A.default.instancePath}="", ${A.default.parentData}, ${A.default.parentDataProperty}, ${A.default.rootData}=${A.default.data}${e.dynamicRef?(0,S._)`, ${A.default.dynamicAnchors}={}`:S.nil}}={}`}function N$(e,t){e.if(A.default.valCxt,()=>{e.var(A.default.instancePath,(0,S._)`${A.default.valCxt}.${A.default.instancePath}`),e.var(A.default.parentData,(0,S._)`${A.default.valCxt}.${A.default.parentData}`),e.var(A.default.parentDataProperty,(0,S._)`${A.default.valCxt}.${A.default.parentDataProperty}`),e.var(A.default.rootData,(0,S._)`${A.default.valCxt}.${A.default.rootData}`),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`${A.default.valCxt}.${A.default.dynamicAnchors}`)},()=>{e.var(A.default.instancePath,(0,S._)`""`),e.var(A.default.parentData,(0,S._)`undefined`),e.var(A.default.parentDataProperty,(0,S._)`undefined`),e.var(A.default.rootData,A.default.data),t.dynamicRef&&e.var(A.default.dynamicAnchors,(0,S._)`{}`)})}function C$(e){let{schema:t,opts:r,gen:n}=e;Rf(e,()=>{r.$comment&&t.$comment&&Of(e),q$(e),n.let(A.default.vErrors,null),n.let(A.default.errors,0),r.unevaluated&&O$(e),Cf(e),Z$(e)})}function O$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,S._)`${r}.evaluated`),t.if((0,S._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,S._)`${e.evaluated}.props`,(0,S._)`undefined`)),t.if((0,S._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,S._)`${e.evaluated}.items`,(0,S._)`undefined`))}function Ef(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,S._)`/*# sourceURL=${r} */`:S.nil}function D$(e,t){if(Af(e)&&(Nf(e),If(e))){j$(e,t);return}(0,zf.boolOrEmptySchema)(e,t)}function If({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Af(e){return typeof e.schema!="boolean"}function j$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Of(e),B$(e),L$(e);let i=n.const("_errs",A.default.errors);Cf(e,i),n.var(t,(0,S._)`${i} === ${A.default.errors}`)}function Nf(e){(0,st.checkUnknownRules)(e),M$(e)}function Cf(e,t){if(e.opts.jtd)return Pf(e,[],!1,t);let r=(0,Sf.getSchemaTypes)(e.schema),n=(0,Sf.coerceAndCheckDataType)(e,r);Pf(e,r,!n,t)}function M$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,st.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function q$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,st.checkStrictMode)(e,"default is ignored in the schema root")}function B$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,R$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function L$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Of({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,S._)`${A.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${A.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Z$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,S._)`${A.default.errors} === 0`,()=>t.return(A.default.data),()=>t.throw((0,S._)`new ${o}(${A.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,A.default.vErrors),i.unevaluated&&U$(e),t.return((0,S._)`${A.default.errors} === 0`))}function U$({gen:e,evaluated:t,props:r,items:n}){r instanceof S.Name&&e.assign((0,S._)`${t}.props`,r),n instanceof S.Name&&e.assign((0,S._)`${t}.items`,n)}function Pf(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,st.schemaHasRulesButRef)(i,u))){o.block(()=>jf(e,"$ref",u.all.$ref.definition));return}c.jtd||F$(e,t),o.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,ga.shouldUseGroup)(i,p)&&(p.type?(o.if((0,vo.checkDataType)(p.type,s,c.strictNumbers)),Tf(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,vo.reportTypeError)(e)),o.endIf()):Tf(e,p),a||o.if((0,S._)`${A.default.errors} === ${n||0}`))}}function Tf(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,z$.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,ga.shouldUseRule)(n,i)&&jf(e,i.keyword,i.definition,t.type)})}function F$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(V$(e,t),e.opts.allowUnionTypes||K$(e,t),H$(e,e.dataTypes))}function V$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Df(e.dataTypes,r)||ya(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),W$(e,t)}}function K$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&ya(e,"use allowUnionTypes to allow union type keyword")}function H$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ga.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>G$(t,s))&&ya(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function G$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Df(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function W$(e,t){let r=[];for(let n of e.dataTypes)Df(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function ya(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,st.checkStrictMode)(e,t,e.opts.strictTypes)}var wo=class{constructor(t,r,n){if((0,nn.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,st.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Mf(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,nn.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=t.gen.const("_errs",A.default.errors))}result(t,r,n){this.failResult((0,S.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,S.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,S._)`${r} !== undefined && (${(0,S.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?rn.reportExtraError:rn.reportError)(this,this.def.error,r)}$dataError(){(0,rn.reportError)(this,this.def.$dataError||rn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,rn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=S.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=S.nil,r=S.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==S.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,S.or)(s(),a());function s(){if(n.length){if(!(r instanceof S.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,S._)`${(0,vo.checkDataTypes)(c,r,i.opts.strictNumbers,vo.DataType.Wrong)}`}return S.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,S._)`!${c}(${r})`}return S.nil}}subschema(t,r){let n=(0,ha.getSubschema)(this.it,t);(0,ha.extendSubschemaData)(n,this.it,t),(0,ha.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return D$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=st.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=st.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,S.Name)),!0}};_t.KeywordCxt=wo;function jf(e,t,r,n){let o=new wo(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,nn.funcKeywordCode)(o,r):"macro"in r?(0,nn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,nn.funcKeywordCode)(o,r)}var J$=/^\/(?:[^~]|~0|~1)*$/,Q$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Mf(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return A.default.rootData;if(e[0]==="/"){if(!J$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=A.default.rootData}else{let l=Q$.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,S._)`${i}${(0,S.getProperty)((0,st.unescapeJsonPointer)(l))}`,s=(0,S._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}_t.getData=Mf});var bo=v(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});var _a=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};va.default=_a});var sn=v($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});var wa=tn(),ba=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wa.resolveUrl)(t,r,n),this.missingSchema=(0,wa.normalizeId)((0,wa.getFullPath)(t,this.missingRef))}};$a.default=ba});var xo=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Le=C(),Y$=bo(),Ct=it(),Ze=tn(),qf=B(),X$=on(),rr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Ze.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Oe.SchemaEnv=rr;function ka(e){let t=Bf.call(this,e);if(t)return t;let r=(0,Ze.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Le.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:Y$.default,code:(0,Le._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Ct.default.data,parentData:Ct.default.parentData,parentDataProperty:Ct.default.parentDataProperty,dataNames:[Ct.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Le._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,X$.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Ct.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let f=new Function(`${Ct.default.self}`,`${Ct.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:g}=l;f.evaluated={props:h instanceof Le.Name?void 0:h,items:g instanceof Le.Name?void 0:g,dynamicProps:h instanceof Le.Name,dynamicItems:g instanceof Le.Name},f.source&&(f.source.evaluated=(0,Le.stringify)(f.evaluated))}return e.validate=f,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}Oe.compileSchema=ka;function e0(e,t,r){var n;r=(0,Ze.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=n0.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new rr({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=t0.call(this,i)}Oe.resolveRef=e0;function t0(e){return(0,Ze.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ka.call(this,e)}function Bf(e){for(let t of this._compilations)if(r0(t,e))return t}Oe.getCompilingSchema=Bf;function r0(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function n0(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||$o.call(this,e,t)}function $o(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ze._getFullPath)(this.opts.uriResolver,r),o=(0,Ze.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return xa.call(this,r,e);let i=(0,Ze.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=$o.call(this,e,s);return typeof a?.schema!="object"?void 0:xa.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||ka.call(this,s),i===(0,Ze.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ze.resolveUrl)(this.opts.uriResolver,o,l)),new rr({schema:a,schemaId:c,root:e,baseId:o})}return xa.call(this,r,s)}}Oe.resolveSchema=$o;var o0=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xa(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,qf.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!o0.has(a)&&l&&(t=(0,Ze.resolveUrl)(this.opts.uriResolver,t,l))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,qf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ze.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=$o.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new rr({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var Lf=v((p1,i0)=>{i0.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 Pa=v((f1,Hf)=>{"use strict";var s0=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Uf=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),Sa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ff=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a0=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ea(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var c0=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Zf(e){return e.length=0,!0}function u0(e,t,r){if(e.length){let n=Ea(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function l0(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=u0;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Zf}else{o.push(l);continue}}return o.length&&(a===Zf?r.zone=o.join(""):s?n.push(o.join("")):n.push(Ea(o))),r.address=n.join(""),r}function Vf(e){if(d0(e,":")<2)return{host:e,isIPV6:!1};let t=l0(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function d0(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function p0(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var f0={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},m0=/[@/?#:]/g,h0=/[@/?#]/g;function Kf(e,t){let r=t?h0:m0;return r.lastIndex=0,e.replace(r,n=>f0[n])}function g0(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Sa(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));t&&Ff(s)?r+=s:r+="%"+i,n+=2;continue}}r+=e[n]}return r}function y0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Sa(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&Ff(i)?t+=i:t+="%"+o,r+=2;continue}}a0(e[r])?t+=e[r]:t+=escape(e[r])}return t}function _0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Sa(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function v0(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Uf(r)){let n=Vf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Kf(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}Hf.exports={nonSimpleDomain:c0,recomposeAuthority:v0,reescapeHostDelimiters:Kf,normalizePercentEncoding:g0,normalizePathEncoding:y0,escapePreservingEscapes:_0,removeDotSegments:p0,isIPv4:Uf,isUUID:s0,normalizeIPv6:Vf,stringArrayToHexStripped:Ea}});var Yf=v((m1,Qf)=>{"use strict";var{isUUID:w0}=Pa(),b0=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,$0=["http","https","ws","wss","urn","urn:uuid"];function x0(e){return $0.indexOf(e)!==-1}function Ta(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Gf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Wf(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function k0(e){return e.secure=Ta(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function S0(e){if((e.port===(Ta(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function E0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(b0);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=za(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function P0(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=za(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function T0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!w0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function z0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Jf={scheme:"http",domainHost:!0,parse:Gf,serialize:Wf},R0={scheme:"https",domainHost:Jf.domainHost,parse:Gf,serialize:Wf},ko={scheme:"ws",domainHost:!0,parse:k0,serialize:S0},I0={scheme:"wss",domainHost:ko.domainHost,parse:ko.parse,serialize:ko.serialize},A0={scheme:"urn",parse:E0,serialize:P0,skipNormalize:!0},N0={scheme:"urn:uuid",parse:T0,serialize:z0,skipNormalize:!0},So={http:Jf,https:R0,ws:ko,wss:I0,urn:A0,"urn:uuid":N0};Object.setPrototypeOf(So,null);function za(e){return e&&(So[e]||So[e.toLowerCase()])||void 0}Qf.exports={wsIsSecure:Ta,SCHEMES:So,isValidSchemeName:x0,getSchemeHandler:za}});var om=v((h1,Eo)=>{"use strict";var{normalizeIPv6:C0,removeDotSegments:an,recomposeAuthority:O0,normalizePercentEncoding:D0,normalizePathEncoding:j0,escapePreservingEscapes:M0,reescapeHostDelimiters:q0,isIPv4:B0,nonSimpleDomain:L0}=Pa(),{SCHEMES:Z0,getSchemeHandler:em}=Yf();function U0(e,t){return typeof e=="string"?e=G0(e,t):typeof e=="object"&&(e=nr(Ot(e,t),t)),e}function F0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=tm(nr(e,n),nr(t,n),n,!0);return n.skipEscape=!0,Ot(o,n)}function tm(e,t,r,n){let o={};return n||(e=nr(Ot(e,r),r),t=nr(Ot(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=an(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=an(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=an(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=an(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function V0(e,t,r){let n=Xf(e,r),o=Xf(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ot(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],i=em(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=D0(r.path):(r.path=M0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=O0(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=an(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var K0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function H0(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function rm(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let s=e.match(K0);if(s){n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]);let a=H0(n,s);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(B0(n.host)===!1){let u=C0(n.host);n.host=u.host.toLowerCase(),i=u.isIPV6}else i=!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 c=em(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&i===!1&&L0(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=q0(unescape(n.host),i))),n.path&&(n.path=j0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}c&&c.parse&&c.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function nr(e,t){return rm(e,t).parsed}function G0(e,t){return nm(e,t).normalized}function nm(e,t){let{parsed:r,malformedAuthorityOrPort:n}=rm(e,t);return{normalized:n?e:Ot(r,t),malformedAuthorityOrPort:n}}function Xf(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=nm(e,t);return n?void 0:r}if(typeof e=="object")return Ot(e,t)}var Ra={SCHEMES:Z0,normalize:U0,resolve:F0,resolveComponent:tm,equal:V0,serialize:Ot,parse:nr};Eo.exports=Ra;Eo.exports.default=Ra;Eo.exports.fastUri=Ra});var sm=v(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var im=om();im.code='require("ajv/dist/runtime/uri").default';Ia.default=im});var mm=v(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=void 0;var W0=on();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return W0.KeywordCxt}});var or=C();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return or._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return or.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return or.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return or.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return or.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return or.CodeGen}});var J0=bo(),dm=sn(),Q0=ia(),cn=xo(),Y0=C(),un=tn(),Po=en(),Na=B(),am=Lf(),X0=sm(),pm=(e,t)=>new RegExp(e,t);pm.code="new RegExp";var ex=["removeAdditional","useDefaults","coerceTypes"],tx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),rx={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."},nx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cm=200;function ox(e){var t,r,n,o,i,s,a,c,l,u,d,p,f,h,g,_,w,b,$,P,R,_e,ze,Zt,gi;let $r=e.strict,yi=(t=e.code)===null||t===void 0?void 0:t.optimize,hu=yi===!0||yi===void 0?1:yi||0,gu=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:pm,By=(o=e.uriResolver)!==null&&o!==void 0?o:X0.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:$r)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:$r)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:$r)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:$r)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=e.strictRequired)!==null&&f!==void 0?f:$r)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:hu,regExp:gu}:{optimize:hu,regExp:gu},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:cm,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:cm,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=e.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(P=e.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(_e=e.validateSchema)!==null&&_e!==void 0?_e:!0,validateFormats:(ze=e.validateFormats)!==null&&ze!==void 0?ze:!0,unicodeRegExp:(Zt=e.unicodeRegExp)!==null&&Zt!==void 0?Zt:!0,int32range:(gi=e.int32range)!==null&&gi!==void 0?gi:!0,uriResolver:By}}var ln=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...ox(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Y0.ValueScope({scope:{},prefixes:tx,es5:r,lines:n}),this.logger=lx(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Q0.getRules)(),um.call(this,rx,t,"NOT SUPPORTED"),um.call(this,nx,t,"DEPRECATED","warn"),this._metaOpts=cx.call(this),t.formats&&sx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&ax.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),ix.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=am;n==="id"&&(o={...am},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(u,d){await i.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof dm.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,un.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,t);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=lm.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new cn.SchemaEnv({schema:{},schemaId:n});if(r=cn.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=lm.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,un.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,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(px.call(this,n,r),!r)return(0,Na.eachItem)(n,i=>Aa.call(this,i)),this;mx.call(this,r);let o={...r,type:(0,Po.getJSONTypes)(r.type),schemaType:(0,Po.getJSONTypes)(r.schemaType)};return(0,Na.eachItem)(n,o.type.length===0?i=>Aa.call(this,i,o):i=>o.type.forEach(s=>Aa.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=fm(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,un.normalizeId)(s||n);let l=un.getSchemaRefs.call(this,t,n);return c=new cn.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):cn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{cn.compileSchema.call(this,t)}finally{this.opts=r}}};ln.ValidationError=J0.default;ln.MissingRefError=dm.default;de.default=ln;function um(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function lm(e){return e=(0,un.normalizeId)(e),this.schemas[e]||this.refs[e]}function ix(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function sx(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ax(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function cx(){let e={...this.opts};for(let t of ex)delete e[t];return e}var ux={log(){},warn(){},error(){}};function lx(e){if(e===!1)return ux;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var dx=/^[a-z_$][a-z0-9_$:-]*$/i;function px(e,t){let{RULES:r}=this;if((0,Na.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!dx.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Aa(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Po.getJSONTypes)(t.type),schemaType:(0,Po.getJSONTypes)(t.schemaType)}};t.before?fx.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function fx(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function mx(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=fm(t)),e.validateSchema=this.compile(t,!0))}var hx={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fm(e){return{anyOf:[e,hx]}}});var hm=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var gx={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ca.default=gx});var vm=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.callRef=Dt.getValidate=void 0;var yx=sn(),gm=Ce(),Pe=C(),ir=it(),ym=xo(),To=B(),_x={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:l}=i;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=ym.resolveRef.call(c,l,o,r);if(u===void 0)throw new yx.default(n.opts.uriResolver,o,r);if(u instanceof ym.SchemaEnv)return p(u);return f(u);function d(){if(i===l)return zo(e,s,i,i.$async);let h=t.scopeValue("root",{ref:l});return zo(e,(0,Pe._)`${h}.validate`,l,l.$async)}function p(h){let g=_m(e,h);zo(e,g,h,h.$async)}function f(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Pe.stringify)(h)}:{ref:h}),_=t.name("valid"),w=e.subschema({schema:h,dataTypes:[],schemaPath:Pe.nil,topSchemaRef:g,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function _m(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Pe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Dt.getValidate=_m;function zo(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?ir.default.this:Pe.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Pe._)`await ${(0,gm.callValidateCode)(e,t,l)}`),f(t),s||o.assign(h,!0)},g=>{o.if((0,Pe._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),p(g),s||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,gm.callValidateCode)(e,t,l),()=>f(t),()=>p(t))}function p(h){let g=(0,Pe._)`${h}.errors`;o.assign(ir.default.vErrors,(0,Pe._)`${ir.default.vErrors} === null ? ${g} : ${ir.default.vErrors}.concat(${g})`),o.assign(ir.default.errors,(0,Pe._)`${ir.default.vErrors}.length`)}function f(h){var g;if(!i.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=To.mergeEvaluated.props(o,_.props,i.props));else{let w=o.var("props",(0,Pe._)`${h}.evaluated.props`);i.props=To.mergeEvaluated.props(o,w,i.props,Pe.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=To.mergeEvaluated.items(o,_.items,i.items));else{let w=o.var("items",(0,Pe._)`${h}.evaluated.items`);i.items=To.mergeEvaluated.items(o,w,i.items,Pe.Name)}}}Dt.callRef=zo;Dt.default=_x});var wm=v(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var vx=hm(),wx=vm(),bx=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vx.default,wx.default];Oa.default=bx});var bm=v(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var Ro=C(),vt=Ro.operators,Io={maximum:{okStr:"<=",ok:vt.LTE,fail:vt.GT},minimum:{okStr:">=",ok:vt.GTE,fail:vt.LT},exclusiveMaximum:{okStr:"<",ok:vt.LT,fail:vt.GTE},exclusiveMinimum:{okStr:">",ok:vt.GT,fail:vt.LTE}},$x={message:({keyword:e,schemaCode:t})=>(0,Ro.str)`must be ${Io[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ro._)`{comparison: ${Io[e].okStr}, limit: ${t}}`},xx={keyword:Object.keys(Io),type:"number",schemaType:"number",$data:!0,error:$x,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Ro._)`${r} ${Io[t].fail} ${n} || isNaN(${r})`)}};Da.default=xx});var $m=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var dn=C(),kx={message:({schemaCode:e})=>(0,dn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,dn._)`{multipleOf: ${e}}`},Sx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:kx,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,dn._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,dn._)`${s} !== parseInt(${s})`;e.fail$data((0,dn._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};ja.default=Sx});var km=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});function xm(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Ma.default=xm;xm.code='require("ajv/dist/runtime/ucs2length").default'});var Sm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var jt=C(),Ex=B(),Px=km(),Tx={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,jt.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,jt._)`{limit: ${e}}`},zx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Tx,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?jt.operators.GT:jt.operators.LT,s=o.opts.unicode===!1?(0,jt._)`${r}.length`:(0,jt._)`${(0,Ex.useFunc)(e.gen,Px.default)}(${r})`;e.fail$data((0,jt._)`${s} ${i} ${n}`)}};qa.default=zx});var Em=v(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var Rx=Ce(),Ix=B(),sr=C(),Ax={message:({schemaCode:e})=>(0,sr.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,sr._)`{pattern: ${e}}`},Nx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ax,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,sr._)`new RegExp`:(0,Ix.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,sr._)`${l}(${i}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,sr._)`!${u}`)}else{let c=(0,Rx.usePattern)(e,o);e.fail$data((0,sr._)`!${c}.test(${r})`)}}};Ba.default=Nx});var Pm=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var pn=C(),Cx={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,pn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,pn._)`{limit: ${e}}`},Ox={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Cx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?pn.operators.GT:pn.operators.LT;e.fail$data((0,pn._)`Object.keys(${r}).length ${o} ${n}`)}};La.default=Ox});var Tm=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var fn=Ce(),mn=C(),Dx=B(),jx={message:({params:{missingProperty:e}})=>(0,mn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,mn._)`{missingProperty: ${e}}`},Mx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:jx,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let f=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(f?.[g]===void 0&&!h.has(g)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,Dx.checkStrictMode)(s,w,s.opts.strictRequired)}}function l(){if(c||i)e.block$data(mn.nil,d);else for(let f of r)(0,fn.checkReportMissingProp)(e,f)}function u(){let f=t.let("missing");if(c||i){let h=t.let("valid",!0);e.block$data(h,()=>p(f,h)),e.ok(h)}else t.if((0,fn.checkMissingProp)(e,r,f)),(0,fn.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",n,f=>{e.setParams({missingProperty:f}),t.if((0,fn.noPropertyInData)(t,o,f,a.ownProperties),()=>e.error())})}function p(f,h){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(h,(0,fn.propertyInData)(t,o,f,a.ownProperties)),t.if((0,mn.not)(h),()=>{e.error(),t.break()})},mn.nil)}}};Za.default=Mx});var zm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var hn=C(),qx={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,hn._)`{limit: ${e}}`},Bx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:qx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?hn.operators.GT:hn.operators.LT;e.fail$data((0,hn._)`${r}.length ${o} ${n}`)}};Ua.default=Bx});var Ao=v(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var Rm=fa();Rm.code='require("ajv/dist/runtime/equal").default';Fa.default=Rm});var Im=v(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Va=en(),pe=C(),Lx=B(),Zx=Ao(),Ux={message:({params:{i:e,j:t}})=>(0,pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,pe._)`{i: ${e}, j: ${t}}`},Fx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ux,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=i.items?(0,Va.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,pe._)`${s} === false`),e.ok(c);function u(){let h=t.let("i",(0,pe._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,pe._)`${h} > 1`,()=>(d()?p:f)(h,g))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function p(h,g){let _=t.name("item"),w=(0,Va.checkDataTypes)(l,_,a.opts.strictNumbers,Va.DataType.Wrong),b=t.const("indices",(0,pe._)`{}`);t.for((0,pe._)`;${h}--;`,()=>{t.let(_,(0,pe._)`${r}[${h}]`),t.if(w,(0,pe._)`continue`),l.length>1&&t.if((0,pe._)`typeof ${_} == "string"`,(0,pe._)`${_} += "_"`),t.if((0,pe._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(g,(0,pe._)`${b}[${_}]`),e.error(),t.assign(c,!1).break()}).code((0,pe._)`${b}[${_}] = ${h}`)})}function f(h,g){let _=(0,Lx.useFunc)(t,Zx.default),w=t.name("outer");t.label(w).for((0,pe._)`;${h}--;`,()=>t.for((0,pe._)`${g} = ${h}; ${g}--;`,()=>t.if((0,pe._)`${_}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};Ka.default=Fx});var Am=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Ha=C(),Vx=B(),Kx=Ao(),Hx={message:"must be equal to constant",params:({schemaCode:e})=>(0,Ha._)`{allowedValue: ${e}}`},Gx={keyword:"const",$data:!0,error:Hx,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Ha._)`!${(0,Vx.useFunc)(t,Kx.default)}(${r}, ${o})`):e.fail((0,Ha._)`${i} !== ${r}`)}};Ga.default=Gx});var Nm=v(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var gn=C(),Wx=B(),Jx=Ao(),Qx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,gn._)`{allowedValues: ${e}}`},Yx={keyword:"enum",schemaType:"array",$data:!0,error:Qx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,Wx.useFunc)(t,Jx.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=t.const("vSchema",i);u=(0,gn.or)(...o.map((h,g)=>p(f,g)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",i,f=>t.if((0,gn._)`${l()}(${r}, ${f})`,()=>t.assign(u,!0).break()))}function p(f,h){let g=o[h];return typeof g=="object"&&g!==null?(0,gn._)`${l()}(${r}, ${f}[${h}])`:(0,gn._)`${r} === ${g}`}}};Wa.default=Yx});var Cm=v(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Xx=bm(),ek=$m(),tk=Sm(),rk=Em(),nk=Pm(),ok=Tm(),ik=zm(),sk=Im(),ak=Am(),ck=Nm(),uk=[Xx.default,ek.default,tk.default,rk.default,nk.default,ok.default,ik.default,sk.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ak.default,ck.default];Ja.default=uk});var Ya=v(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateAdditionalItems=void 0;var Mt=C(),Qa=B(),lk={message:({params:{len:e}})=>(0,Mt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Mt._)`{limit: ${e}}`},dk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:lk,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Qa.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Om(e,n)}};function Om(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Mt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Mt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Qa.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Mt._)`${a} <= ${t.length}`);r.if((0,Mt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Qa.Type.Num},l),s.allErrors||r.if((0,Mt.not)(l),()=>r.break())})}}yn.validateAdditionalItems=Om;yn.default=dk});var Xa=v(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.validateTuple=void 0;var Dm=C(),No=B(),pk=Ce(),fk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return jm(e,"additionalItems",t);r.items=!0,!(0,No.alwaysValidSchema)(r,t)&&e.ok((0,pk.validateArray)(e))}};function jm(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=No.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Dm._)`${i}.length`);r.forEach((d,p)=>{(0,No.alwaysValidSchema)(a,d)||(n.if((0,Dm._)`${l} > ${p}`,()=>e.subschema({keyword:s,schemaProp:p,dataProp:p},c)),e.ok(c))});function u(d){let{opts:p,errSchemaPath:f}=a,h=r.length,g=h===d.minItems&&(h===d.maxItems||d[t]===!1);if(p.strictTuples&&!g){let _=`"${s}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,No.checkStrictMode)(a,_,p.strictTuples)}}}_n.validateTuple=jm;_n.default=fk});var Mm=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var mk=Xa(),hk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,mk.validateTuple)(e,"items")};ec.default=hk});var Bm=v(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var qm=C(),gk=B(),yk=Ce(),_k=Ya(),vk={message:({params:{len:e}})=>(0,qm.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,qm._)`{limit: ${e}}`},wk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:vk,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,gk.alwaysValidSchema)(n,t)&&(o?(0,_k.validateAdditionalItems)(e,o):e.ok((0,yk.validateArray)(e)))}};tc.default=wk});var Lm=v(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var De=C(),Co=B(),bk={message:({params:{min:e,max:t}})=>t===void 0?(0,De.str)`must contain at least ${e} valid item(s)`:(0,De.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,De._)`{minContains: ${e}}`:(0,De._)`{minContains: ${e}, maxContains: ${t}}`},$k={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:bk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:l}=n;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=t.const("len",(0,De._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Co.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Co.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Co.alwaysValidSchema)(i,r)){let g=(0,De._)`${u} >= ${s}`;a!==void 0&&(g=(0,De._)`${g} && ${u} <= ${a}`),e.pass(g);return}i.items=!0;let d=t.name("valid");a===void 0&&s===1?f(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),a!==void 0&&t.if((0,De._)`${o}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let g=t.name("_valid"),_=t.let("count",0);f(g,()=>t.if(g,()=>h(_)))}function f(g,_){t.forRange("i",0,u,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Co.Type.Num,compositeRule:!0},g),_()})}function h(g){t.code((0,De._)`${g}++`),a===void 0?t.if((0,De._)`${g} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,De._)`${g} > ${a}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,De._)`${g} >= ${s}`,()=>t.assign(d,!0)))}}};rc.default=$k});var Fm=v(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateSchemaDeps=Ye.validatePropertyDeps=Ye.error=void 0;var nc=C(),xk=B(),vn=Ce();Ye.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,nc.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,nc._)`{property: ${e},
8
8
  missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var xk={keyword:"dependencies",type:"object",schemaType:"object",error:Ye.error,code(e){let[t,r]=kk(e);Lm(e,t),Zm(e,r)}};function kk({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Lm(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,vn.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,vn.checkReportMissingProp)(e,l)}):(r.if((0,nc._)`${c} && (${(0,vn.checkMissingProp)(e,a,i)})`),(0,vn.reportMissingProp)(e,i),r.else())}}Ye.validatePropertyDeps=Lm;function Zm(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,$k.alwaysValidSchema)(i,t[a])||(r.if((0,vn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}Ye.validateSchemaDeps=Zm;Ye.default=xk});var Vm=v(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Fm=C(),Sk=B(),Ek={message:"property name must be valid",params:({params:e})=>(0,Fm._)`{propertyName: ${e.propertyName}}`},Pk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Ek,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Sk.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,Fm.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};oc.default=Pk});var sc=v(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Oo=Ce(),Ue=C(),zk=it(),Do=B(),Tk={message:"must NOT have additional properties",params:({params:e})=>(0,Ue._)`{additionalProperty: ${e.additionalProperty}}`},Rk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Tk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Do.alwaysValidSchema)(s,r))return;let l=(0,Oo.allSchemaProperties)(n.properties),u=(0,Oo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Ue._)`${i} === ${zk.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?h(_):t.if(p(_),()=>h(_))})}function p(_){let w;if(l.length>8){let b=(0,Do.schemaRefOrVal)(s,n.properties,"properties");w=(0,Oo.isOwnProperty)(t,b,_)}else l.length?w=(0,Ue.or)(...l.map(b=>(0,Ue._)`${_} === ${b}`)):w=Ue.nil;return u.length&&(w=(0,Ue.or)(w,...u.map(b=>(0,Ue._)`${(0,Oo.usePattern)(e,b)}.test(${_})`))),(0,Ue.not)(w)}function f(_){t.code((0,Ue._)`delete ${o}[${_}]`)}function h(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Do.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(_,w,!1),t.if((0,Ue.not)(w),()=>{e.reset(),f(_)})):(g(_,w),a||t.if((0,Ue.not)(w),()=>t.break()))}}function g(_,w,b){let $={keyword:"additionalProperties",dataProp:_,dataPropType:Do.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,w)}}};ic.default=Rk});var Gm=v(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var Ik=on(),Km=Ce(),ac=B(),Hm=sc(),Ak={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Hm.default.code(new Ik.KeywordCxt(i,Hm.default,"additionalProperties"));let s=(0,Km.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=ac.mergeEvaluated.props(t,(0,ac.toHash)(s),i.props));let a=s.filter(d=>!(0,ac.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Km.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};cc.default=Ak});var Ym=v(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Wm=Ce(),jo=C(),Jm=B(),Qm=B(),Nk={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,Wm.allSchemaProperties)(r),c=a.filter(g=>(0,Jm.alwaysValidSchema)(i,r[g]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof jo.Name)&&(i.props=(0,Qm.evaluatedPropsToName)(t,i.props));let{props:d}=i;p();function p(){for(let g of a)l&&f(g),i.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function f(g){for(let _ in l)new RegExp(g).test(_)&&(0,Jm.checkStrictMode)(i,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,_=>{t.if((0,jo._)`${(0,Wm.usePattern)(e,g)}.test(${_})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:Qm.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,jo._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,jo.not)(u),()=>t.break())})})}}};uc.default=Nk});var Xm=v(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Ck=B(),Ok={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Ck.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};lc.default=Ok});var eh=v(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Dk=Ce(),jk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Dk.validateUnion,error:{message:"must match a schema in anyOf"}};dc.default=jk});var th=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Mo=C(),Mk=B(),qk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Mo._)`{passingSchemas: ${e.passing}}`},Bk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qk,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let p;(0,Mk.alwaysValidSchema)(o,u)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),p&&e.mergeEvaluated(p,Mo.Name)})})}}};pc.default=Bk});var rh=v(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Lk=B(),Zk={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((i,s)=>{if((0,Lk.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};fc.default=Zk});var ih=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var qo=C(),oh=B(),Uk={message:({params:e})=>(0,qo.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,qo._)`{failingKeyword: ${e.ifClause}}`},Fk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Uk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,oh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=nh(n,"then"),i=nh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,qo.not)(a),l("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let p=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(p,s),d?t.assign(d,(0,qo._)`${u}`):e.setParams({ifClause:u})}}}};function nh(e,t){let r=e.schema[t];return r!==void 0&&!(0,oh.alwaysValidSchema)(e,r)}mc.default=Fk});var sh=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Vk=B(),Kk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Vk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};hc.default=Kk});var ah=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Hk=Ya(),Gk=jm(),Wk=Xa(),Jk=qm(),Qk=Bm(),Yk=Um(),Xk=Vm(),eS=sc(),tS=Gm(),rS=Ym(),nS=Xm(),oS=eh(),iS=th(),sS=rh(),aS=ih(),cS=sh();function uS(e=!1){let t=[nS.default,oS.default,iS.default,sS.default,aS.default,cS.default,Xk.default,eS.default,Yk.default,tS.default,rS.default];return e?t.push(Gk.default,Jk.default):t.push(Hk.default,Wk.default),t.push(Qk.default),t}gc.default=uS});var ch=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var oe=C(),lS={message:({schemaCode:e})=>(0,oe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,oe._)`{format: ${e}}`},dS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:lS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,oe._)`${h}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,oe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,oe._)`${g}.type || "string"`).assign(w,(0,oe._)`${g}.validate`),()=>r.assign(_,(0,oe._)`"string"`).assign(w,g)),e.fail$data((0,oe.or)(b(),$()));function b(){return c.strictSchema===!1?oe.nil:(0,oe._)`${s} && !${w}`}function $(){let P=u.$async?(0,oe._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,oe._)`${w}(${n})`,R=(0,oe._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,oe._)`${w} && ${w} !== true && ${_} === ${t} && !${R}`}}function f(){let h=d.formats[i];if(!h){b();return}if(h===!0)return;let[g,_,w]=$(h);g===t&&e.pass(P());function b(){if(c.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function $(R){let _e=R instanceof RegExp?(0,oe.regexpCode)(R):c.code.formats?(0,oe._)`${c.code.formats}${(0,oe.getProperty)(i)}`:void 0,Te=r.scopeValue("formats",{key:i,ref:R,code:_e});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,oe._)`${Te}.validate`]:["string",R,Te]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,oe._)`await ${w}(${n})`}return typeof _=="function"?(0,oe._)`${w}(${n})`:(0,oe._)`${w}.test(${n})`}}}};yc.default=dS});var uh=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var pS=ch(),fS=[pS.default];_c.default=fS});var lh=v(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.contentVocabulary=ar.metadataVocabulary=void 0;ar.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ar.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ph=v(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var mS=vm(),hS=Nm(),gS=ah(),yS=uh(),dh=lh(),_S=[mS.default,hS.default,(0,gS.default)(),yS.default,dh.metadataVocabulary,dh.contentVocabulary];vc.default=_S});var mh=v(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.DiscrError=void 0;var fh;(function(e){e.Tag="tag",e.Mapping="mapping"})(fh||(Bo.DiscrError=fh={}))});var gh=v(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var cr=C(),wc=mh(),hh=xo(),vS=sn(),wS=B(),bS={message:({params:{discrError:e,tagName:t}})=>e===wc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,cr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},$S={keyword:"discriminator",type:"object",schemaType:"object",error:bS,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,cr._)`${r}${(0,cr.getProperty)(a)}`);t.if((0,cr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:wc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let f=p();t.if(!1);for(let h in f)t.elseIf((0,cr._)`${l} === ${h}`),t.assign(c,d(f[h]));t.else(),e.error(!1,{discrError:wc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(f){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:f},h);return e.mergeEvaluated(g,cr.Name),h}function p(){var f;let h={},g=w(o),_=!0;for(let P=0;P<s.length;P++){let R=s[P];if(R?.$ref&&!(0,wS.schemaHasRulesButRef)(R,i.self.RULES)){let Te=R.$ref;if(R=hh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Te),R instanceof hh.SchemaEnv&&(R=R.schema),R===void 0)throw new vS.default(i.opts.uriResolver,i.baseId,Te)}let _e=(f=R?.properties)===null||f===void 0?void 0:f[a];if(typeof _e!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(g||w(R)),b(_e,P)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function b(P,R){if(P.const)$(P.const,R);else if(P.enum)for(let _e of P.enum)$(_e,R);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(P,R){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=R}}}};bc.default=$S});var yh=v((Y1,xS)=>{xS.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 xc=v((X,$c)=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.MissingRefError=X.ValidationError=X.CodeGen=X.Name=X.nil=X.stringify=X.str=X._=X.KeywordCxt=X.Ajv=void 0;var kS=fm(),SS=ph(),ES=gh(),_h=yh(),PS=["/properties"],Lo="http://json-schema.org/draft-07/schema",ur=class extends kS.default{_addVocabularies(){super._addVocabularies(),SS.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(ES.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(_h,PS):_h;this.addMetaSchema(t,Lo,!1),this.refs["http://json-schema.org/schema"]=Lo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lo)?Lo:void 0)}};X.Ajv=ur;$c.exports=X=ur;$c.exports.Ajv=ur;Object.defineProperty(X,"__esModule",{value:!0});X.default=ur;var zS=on();Object.defineProperty(X,"KeywordCxt",{enumerable:!0,get:function(){return zS.KeywordCxt}});var lr=C();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return lr._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return lr.str}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return lr.stringify}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return lr.nil}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return lr.Name}});Object.defineProperty(X,"CodeGen",{enumerable:!0,get:function(){return lr.CodeGen}});var TS=bo();Object.defineProperty(X,"ValidationError",{enumerable:!0,get:function(){return TS.default}});var RS=sn();Object.defineProperty(X,"MissingRefError",{enumerable:!0,get:function(){return RS.default}})});var Eh=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Xe(e,t){return{validate:e,compare:t}}et.fullFormats={date:Xe($h,Pc),time:Xe(Sc(!0),zc),"date-time":Xe(vh(!0),kh),"iso-time":Xe(Sc(),xh),"iso-date-time":Xe(vh(),Sh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:DS,"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:US,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:jS,int32:{type:"number",validate:BS},int64:{type:"number",validate:LS},float:{type:"number",validate:bh},double:{type:"number",validate:bh},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pc),time:Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zc),"date-time":Xe(/^\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,kh),"iso-time":Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,xh),"iso-date-time":Xe(/^\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,Sh),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};et.formatNames=Object.keys(et.fullFormats);function IS(e){return e%4===0&&(e%100!==0||e%400===0)}var AS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function $h(e){let t=AS.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&IS(r)?29:NS[n])}function Pc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Sc(e){return function(r){let n=kc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,p=o-l*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function zc(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function xh(e,t){if(!(e&&t))return;let r=kc.exec(e),n=kc.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var Ec=/t|\s/i;function vh(e){let t=Sc(e);return function(n){let o=n.split(Ec);return o.length===2&&$h(o[0])&&t(o[1])}}function kh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Sh(e,t){if(!(e&&t))return;let[r,n]=e.split(Ec),[o,i]=t.split(Ec),s=Pc(r,o);if(s!==void 0)return s||zc(n,i)}var CS=/\/|:/,OS=/^(?:[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 DS(e){return CS.test(e)&&OS.test(e)}var wh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function jS(e){return wh.lastIndex=0,wh.test(e)}var MS=-(2**31),qS=2**31-1;function BS(e){return Number.isInteger(e)&&e<=qS&&e>=MS}function LS(e){return Number.isInteger(e)}function bh(){return!0}var ZS=/[^\\]\\Z/;function US(e){if(ZS.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Ph=v(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.formatLimitDefinition=void 0;var FS=xc(),Fe=C(),wt=Fe.operators,Zo={formatMaximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},formatMinimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},formatExclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},formatExclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},VS={message:({keyword:e,schemaCode:t})=>(0,Fe.str)`should be ${Zo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Fe._)`{comparison: ${Zo[e].okStr}, limit: ${t}}`};dr.formatLimitDefinition={keyword:Object.keys(Zo),type:"string",schemaType:"string",$data:!0,error:VS,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new FS.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let p=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=t.const("fmt",(0,Fe._)`${p}[${c.schemaCode}]`);e.fail$data((0,Fe.or)((0,Fe._)`typeof ${f} != "object"`,(0,Fe._)`${f} instanceof RegExp`,(0,Fe._)`typeof ${f}.compare != "function"`,d(f)))}function u(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=t.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,Fe._)`${s.code.formats}${(0,Fe.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,Fe._)`${p}.compare(${r}, ${n}) ${Zo[o].fail} 0`}},dependencies:["format"]};var KS=e=>(e.addKeyword(dr.formatLimitDefinition),e);dr.default=KS});var Ih=v((wn,Rh)=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});var pr=Eh(),HS=Ph(),Tc=C(),zh=new Tc.Name("fullFormats"),GS=new Tc.Name("fastFormats"),Rc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Th(e,t,pr.fullFormats,zh),e;let[r,n]=t.mode==="fast"?[pr.fastFormats,GS]:[pr.fullFormats,zh],o=t.formats||pr.formatNames;return Th(e,o,r,n),t.keywords&&(0,HS.default)(e),e};Rc.get=(e,t="full")=>{let n=(t==="fast"?pr.fastFormats:pr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Th(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Tc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Rh.exports=wn=Rc;Object.defineProperty(wn,"__esModule",{value:!0});wn.default=Rc});var Bh=v((pD,qh)=>{qh.exports=Mh;Mh.sync=YS;var Dh=ct("fs");function QS(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function jh(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:QS(t,r)}function Mh(e,t,r){Dh.stat(e,function(n,o){r(n,n?!1:jh(o,e,t))})}function YS(e,t){return jh(Dh.statSync(e),e,t)}});var Vh=v((fD,Fh)=>{Fh.exports=Zh;Zh.sync=XS;var Lh=ct("fs");function Zh(e,t,r){Lh.stat(e,function(n,o){r(n,n?!1:Uh(o,t))})}function XS(e,t){return Uh(Lh.statSync(e),t)}function Uh(e,t){return e.isFile()&&eE(e,t)}function eE(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var Hh=v((hD,Kh)=>{var mD=ct("fs"),Ho;process.platform==="win32"||global.TESTING_WINDOWS?Ho=Bh():Ho=Vh();Kh.exports=Ic;Ic.sync=tE;function Ic(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Ic(e,t||{},function(i,s){i?o(i):n(s)})})}Ho(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function tE(e,t){try{return Ho.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var eg=v((gD,Xh)=>{var fr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Gh=ct("path"),rE=fr?";":":",Wh=Hh(),Jh=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Qh=(e,t)=>{let r=t.colon||rE,n=e.match(/\//)||fr&&e.match(/\\/)?[""]:[...fr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=fr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=fr?o.split(r):[""];return fr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},Yh=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Qh(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(Jh(e));let p=n[l],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=Gh.join(f,e),g=!f&&/^\.[\\\/]/.test(e)?e.slice(0,2)+h:h;u(c(g,l,0))}),c=(l,u,d)=>new Promise((p,f)=>{if(d===o.length)return p(a(u+1));let h=o[d];Wh(l+h,{pathExt:i},(g,_)=>{if(!g&&_)if(t.all)s.push(l+h);else return p(l+h);return p(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},nE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Qh(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Gh.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let p=u+n[d];try{if(Wh.sync(p,{pathExt:o}))if(t.all)i.push(p);else return p}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw Jh(e)};Xh.exports=Yh;Yh.sync=nE});var rg=v((yD,Ac)=>{"use strict";var tg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Ac.exports=tg;Ac.exports.default=tg});var sg=v((_D,ig)=>{"use strict";var ng=ct("path"),oE=eg(),iE=rg();function og(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=oE.sync(e.command,{path:r[iE({env:r})],pathExt:t?ng.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=ng.resolve(o?e.options.cwd:"",s)),s}function sE(e){return og(e)||og(e,!0)}ig.exports=sE});var ag=v((vD,Cc)=>{"use strict";var Nc=/([()\][%!^"`<>&|;, *?])/g;function aE(e){return e=e.replace(Nc,"^$1"),e}function cE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Nc,"^$1"),t&&(e=e.replace(Nc,"^$1")),e}Cc.exports.command=aE;Cc.exports.argument=cE});var ug=v((wD,cg)=>{"use strict";cg.exports=/^#!(.*)/});var dg=v((bD,lg)=>{"use strict";var uE=ug();lg.exports=(e="")=>{let t=e.match(uE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var fg=v(($D,pg)=>{"use strict";var Oc=ct("fs"),lE=dg();function dE(e){let r=Buffer.alloc(150),n;try{n=Oc.openSync(e,"r"),Oc.readSync(n,r,0,150,0),Oc.closeSync(n)}catch{}return lE(r.toString())}pg.exports=dE});var yg=v((xD,gg)=>{"use strict";var pE=ct("path"),mg=sg(),hg=ag(),fE=fg(),mE=process.platform==="win32",hE=/\.(?:com|exe)$/i,gE=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function yE(e){e.file=mg(e);let t=e.file&&fE(e.file);return t?(e.args.unshift(e.file),e.command=t,mg(e)):e.file}function _E(e){if(!mE)return e;let t=yE(e),r=!hE.test(t);if(e.options.forceShell||r){let n=gE.test(t);e.command=pE.normalize(e.command),e.command=hg.command(e.command),e.args=e.args.map(i=>hg.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function vE(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:_E(n)}gg.exports=vE});var wg=v((kD,vg)=>{"use strict";var Dc=process.platform==="win32";function jc(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function wE(e,t){if(!Dc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=_g(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function _g(e,t){return Dc&&e===1&&!t.file?jc(t.original,"spawn"):null}function bE(e,t){return Dc&&e===1&&!t.file?jc(t.original,"spawnSync"):null}vg.exports={hookChildProcess:wE,verifyENOENT:_g,verifyENOENTSync:bE,notFoundError:jc}});var xg=v((SD,mr)=>{"use strict";var bg=ct("child_process"),Mc=yg(),qc=wg();function $g(e,t,r){let n=Mc(e,t,r),o=bg.spawn(n.command,n.args,n.options);return qc.hookChildProcess(o,n),o}function $E(e,t,r){let n=Mc(e,t,r),o=bg.spawnSync(n.command,n.args,n.options);return o.error=o.error||qc.verifyENOENTSync(o.status,n),o}mr.exports=$g;mr.exports.spawn=$g;mr.exports.sync=$E;mr.exports._parse=Mc;mr.exports._enoent=qc});import{readFile as UT,mkdir as FT,writeFile as VT}from"node:fs/promises";import{dirname as KT,join as My}from"node:path";var dR=Object.freeze({status:"aborted"});function y(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var pR=Symbol("zod_brand"),tt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},An={};function Re(e){return e&&Object.assign(An,e),An}var U={};gu(U,{BIGINT_FORMAT_RANGES:()=>_u,Class:()=>bi,NUMBER_FORMAT_RANGES:()=>Ti,aborted:()=>kt,allowsEval:()=>Ei,assert:()=>Jy,assertEqual:()=>Ky,assertIs:()=>Gy,assertNever:()=>Wy,assertNotEqual:()=>Hy,assignProp:()=>Si,cached:()=>kr,captureStackTrace:()=>Cn,cleanEnum:()=>u_,cleanRegex:()=>Er,clone:()=>Ge,createTransparentProxy:()=>r_,defineLazy:()=>H,esc:()=>xt,escapeRegex:()=>ut,extend:()=>i_,finalizeIssue:()=>Me,floatSafeRemainder:()=>ki,getElementAtPath:()=>Qy,getEnumValues:()=>$i,getLengthableOrigin:()=>Pr,getParsedType:()=>t_,getSizableOrigin:()=>vu,isObject:()=>Ut,isPlainObject:()=>Ft,issue:()=>Ri,joinValues:()=>Nn,jsonStringifyReplacer:()=>xi,merge:()=>s_,normalizeParams:()=>z,nullish:()=>Sr,numKeys:()=>e_,omit:()=>o_,optionalKeys:()=>zi,partial:()=>a_,pick:()=>n_,prefixIssues:()=>We,primitiveTypes:()=>yu,promiseAllObject:()=>Yy,propertyKeyTypes:()=>Pi,randomString:()=>Xy,required:()=>c_,stringifyPrimitive:()=>On,unwrapMessage:()=>xr});function Ky(e){return e}function Hy(e){return e}function Gy(e){}function Wy(e){throw new Error}function Jy(e){}function $i(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Nn(e,t="|"){return e.map(r=>On(r)).join(t)}function xi(e,t){return typeof t=="bigint"?t.toString():t}function kr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Sr(e){return e==null}function Er(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ki(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function H(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Si(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Qy(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Yy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Xy(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function xt(e){return JSON.stringify(e)}var Cn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ei=kr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ft(e){if(Ut(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Ut(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function e_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var t_=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Pi=new Set(["string","number","symbol"]),yu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function z(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function r_(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function On(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function zi(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ti={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},_u={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function n_(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function o_(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function i_(e,t){if(!Ft(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Si(this,"shape",n),n},checks:[]};return Ge(e,r)}function s_(e,t){return Ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Si(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function a_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Ge(t,{...t._zod.def,shape:o,checks:[]})}function c_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Ge(t,{...t._zod.def,shape:o,checks:[]})}function kt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function We(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function xr(e){return typeof e=="string"?e:e?.message}function Me(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=xr(e.inst?._zod.def?.error?.(e))??xr(t?.error?.(e))??xr(r.customError?.(e))??xr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function vu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Pr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ri(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function u_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var bi=class{constructor(...t){}};var wu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,xi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Dn=y("$ZodError",wu),Ii=y("$ZodError",wu,{Parent:Error});function bu(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function $u(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var xu=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new tt;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Me(c,i,Re())));throw Cn(a,o?.callee),a}return s.value};var ku=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Me(c,i,Re())));throw Cn(a,o?.callee),a}return s.value};var Ai=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new tt;return i.issues.length?{success:!1,error:new(e??Dn)(i.issues.map(s=>Me(s,o,Re())))}:{success:!0,data:i.value}},zr=Ai(Ii),Ni=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Me(s,o,Re())))}:{success:!0,data:i.value}},jn=Ni(Ii);var Su=/^[cC][^\s-]{8,}$/,Eu=/^[0-9a-z]+$/,Pu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zu=/^[0-9a-vA-V]{20}$/,Tu=/^[A-Za-z0-9]{27}$/,Ru=/^[a-zA-Z0-9_-]{21}$/,Iu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Au=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ci=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Nu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var d_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Cu(){return new RegExp(d_,"u")}var Ou=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Du=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,ju=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Mu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oi=/^[A-Za-z0-9_-]*$/,Bu=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Lu=/^\+(?:[0-9]){6,14}[0-9]$/,Zu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Uu=new RegExp(`^${Zu}$`);function Fu(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Vu(e){return new RegExp(`^${Fu(e)}$`)}function Ku(e){let t=Fu({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Zu}T(?:${n})$`)}var Hu=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Gu=/^\d+$/,Wu=/^-?\d+(?:\.\d+)?/i,Ju=/true|false/i,Qu=/null/i;var Yu=/^[^A-Z]*$/,Xu=/^[^a-z]*$/;var fe=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),el={number:"number",bigint:"bigint",object:"date"},ji=y("$ZodCheckLessThan",(e,t)=>{fe.init(e,t);let r=el[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mi=y("$ZodCheckGreaterThan",(e,t)=>{fe.init(e,t);let r=el[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tl=y("$ZodCheckMultipleOf",(e,t)=>{fe.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ki(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),rl=y("$ZodCheckNumberFormat",(e,t)=>{fe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Ti[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=Gu)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var nl=y("$ZodCheckMaxLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Pr(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ol=y("$ZodCheckMinLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Pr(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),il=y("$ZodCheckLengthEquals",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Pr(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Tr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;fe.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),sl=y("$ZodCheckRegex",(e,t)=>{Tr.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),al=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yu),Tr.init(e,t)}),cl=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Xu),Tr.init(e,t)}),ul=y("$ZodCheckIncludes",(e,t)=>{fe.init(e,t);let r=ut(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),ll=y("$ZodCheckStartsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`^${ut(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),dl=y("$ZodCheckEndsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`.*${ut(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var pl=y("$ZodCheckOverwrite",(e,t)=>{fe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Mn=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
10
+ deps: ${r}}`};var kk={keyword:"dependencies",type:"object",schemaType:"object",error:Ye.error,code(e){let[t,r]=Sk(e);Zm(e,t),Um(e,r)}};function Sk({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Zm(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,vn.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,vn.checkReportMissingProp)(e,l)}):(r.if((0,nc._)`${c} && (${(0,vn.checkMissingProp)(e,a,i)})`),(0,vn.reportMissingProp)(e,i),r.else())}}Ye.validatePropertyDeps=Zm;function Um(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,xk.alwaysValidSchema)(i,t[a])||(r.if((0,vn.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}Ye.validateSchemaDeps=Um;Ye.default=kk});var Km=v(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var Vm=C(),Ek=B(),Pk={message:"property name must be valid",params:({params:e})=>(0,Vm._)`{propertyName: ${e.propertyName}}`},Tk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Pk,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Ek.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,Vm.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};oc.default=Tk});var sc=v(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Oo=Ce(),Ue=C(),zk=it(),Do=B(),Rk={message:"must NOT have additional properties",params:({params:e})=>(0,Ue._)`{additionalProperty: ${e.additionalProperty}}`},Ik={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Rk,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Do.alwaysValidSchema)(s,r))return;let l=(0,Oo.allSchemaProperties)(n.properties),u=(0,Oo.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Ue._)`${i} === ${zk.default.errors}`);function d(){t.forIn("key",o,_=>{!l.length&&!u.length?h(_):t.if(p(_),()=>h(_))})}function p(_){let w;if(l.length>8){let b=(0,Do.schemaRefOrVal)(s,n.properties,"properties");w=(0,Oo.isOwnProperty)(t,b,_)}else l.length?w=(0,Ue.or)(...l.map(b=>(0,Ue._)`${_} === ${b}`)):w=Ue.nil;return u.length&&(w=(0,Ue.or)(w,...u.map(b=>(0,Ue._)`${(0,Oo.usePattern)(e,b)}.test(${_})`))),(0,Ue.not)(w)}function f(_){t.code((0,Ue._)`delete ${o}[${_}]`)}function h(_){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Do.alwaysValidSchema)(s,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(_,w,!1),t.if((0,Ue.not)(w),()=>{e.reset(),f(_)})):(g(_,w),a||t.if((0,Ue.not)(w),()=>t.break()))}}function g(_,w,b){let $={keyword:"additionalProperties",dataProp:_,dataPropType:Do.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,w)}}};ic.default=Ik});var Wm=v(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var Ak=on(),Hm=Ce(),ac=B(),Gm=sc(),Nk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Gm.default.code(new Ak.KeywordCxt(i,Gm.default,"additionalProperties"));let s=(0,Hm.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=ac.mergeEvaluated.props(t,(0,ac.toHash)(s),i.props));let a=s.filter(d=>!(0,ac.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Hm.propertyInData)(t,o,d,i.opts.ownProperties)),u(d),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};cc.default=Nk});var Xm=v(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var Jm=Ce(),jo=C(),Qm=B(),Ym=B(),Ck={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,Jm.allSchemaProperties)(r),c=a.filter(g=>(0,Qm.alwaysValidSchema)(i,r[g]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof jo.Name)&&(i.props=(0,Ym.evaluatedPropsToName)(t,i.props));let{props:d}=i;p();function p(){for(let g of a)l&&f(g),i.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function f(g){for(let _ in l)new RegExp(g).test(_)&&(0,Qm.checkStrictMode)(i,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,_=>{t.if((0,jo._)`${(0,Jm.usePattern)(e,g)}.test(${_})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:Ym.Type.Str},u),i.opts.unevaluated&&d!==!0?t.assign((0,jo._)`${d}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,jo.not)(u),()=>t.break())})})}}};uc.default=Ck});var eh=v(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Ok=B(),Dk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Ok.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};lc.default=Dk});var th=v(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var jk=Ce(),Mk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:jk.validateUnion,error:{message:"must match a schema in anyOf"}};dc.default=Mk});var rh=v(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Mo=C(),qk=B(),Bk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Mo._)`{passingSchemas: ${e.passing}}`},Lk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Bk,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){i.forEach((u,d)=>{let p;(0,qk.alwaysValidSchema)(o,u)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),p&&e.mergeEvaluated(p,Mo.Name)})})}}};pc.default=Lk});var nh=v(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Zk=B(),Uk={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((i,s)=>{if((0,Zk.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};fc.default=Uk});var sh=v(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var qo=C(),ih=B(),Fk={message:({params:e})=>(0,qo.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,qo._)`{failingKeyword: ${e.ifClause}}`},Vk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Fk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,ih.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=oh(n,"then"),i=oh(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else o?t.if(a,l("then")):t.if((0,qo.not)(a),l("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let p=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(p,s),d?t.assign(d,(0,qo._)`${u}`):e.setParams({ifClause:u})}}}};function oh(e,t){let r=e.schema[t];return r!==void 0&&!(0,ih.alwaysValidSchema)(e,r)}mc.default=Vk});var ah=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Kk=B(),Hk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Kk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};hc.default=Hk});var ch=v(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Gk=Ya(),Wk=Mm(),Jk=Xa(),Qk=Bm(),Yk=Lm(),Xk=Fm(),eS=Km(),tS=sc(),rS=Wm(),nS=Xm(),oS=eh(),iS=th(),sS=rh(),aS=nh(),cS=sh(),uS=ah();function lS(e=!1){let t=[oS.default,iS.default,sS.default,aS.default,cS.default,uS.default,eS.default,tS.default,Xk.default,rS.default,nS.default];return e?t.push(Wk.default,Qk.default):t.push(Gk.default,Jk.default),t.push(Yk.default),t}gc.default=lS});var uh=v(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var oe=C(),dS={message:({schemaCode:e})=>(0,oe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,oe._)`{format: ${e}}`},pS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:dS,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,oe._)`${h}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,oe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(_,(0,oe._)`${g}.type || "string"`).assign(w,(0,oe._)`${g}.validate`),()=>r.assign(_,(0,oe._)`"string"`).assign(w,g)),e.fail$data((0,oe.or)(b(),$()));function b(){return c.strictSchema===!1?oe.nil:(0,oe._)`${s} && !${w}`}function $(){let P=u.$async?(0,oe._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,oe._)`${w}(${n})`,R=(0,oe._)`(typeof ${w} == "function" ? ${P} : ${w}.test(${n}))`;return(0,oe._)`${w} && ${w} !== true && ${_} === ${t} && !${R}`}}function f(){let h=d.formats[i];if(!h){b();return}if(h===!0)return;let[g,_,w]=$(h);g===t&&e.pass(P());function b(){if(c.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function $(R){let _e=R instanceof RegExp?(0,oe.regexpCode)(R):c.code.formats?(0,oe._)`${c.code.formats}${(0,oe.getProperty)(i)}`:void 0,ze=r.scopeValue("formats",{key:i,ref:R,code:_e});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,oe._)`${ze}.validate`]:["string",R,ze]}function P(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,oe._)`await ${w}(${n})`}return typeof _=="function"?(0,oe._)`${w}(${n})`:(0,oe._)`${w}.test(${n})`}}}};yc.default=pS});var lh=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var fS=uh(),mS=[fS.default];_c.default=mS});var dh=v(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.contentVocabulary=ar.metadataVocabulary=void 0;ar.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ar.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var fh=v(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var hS=wm(),gS=Cm(),yS=ch(),_S=lh(),ph=dh(),vS=[hS.default,gS.default,(0,yS.default)(),_S.default,ph.metadataVocabulary,ph.contentVocabulary];vc.default=vS});var hh=v(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.DiscrError=void 0;var mh;(function(e){e.Tag="tag",e.Mapping="mapping"})(mh||(Bo.DiscrError=mh={}))});var yh=v(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var cr=C(),wc=hh(),gh=xo(),wS=sn(),bS=B(),$S={message:({params:{discrError:e,tagName:t}})=>e===wc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,cr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},xS={keyword:"discriminator",type:"object",schemaType:"object",error:$S,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,cr._)`${r}${(0,cr.getProperty)(a)}`);t.if((0,cr._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:wc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let f=p();t.if(!1);for(let h in f)t.elseIf((0,cr._)`${l} === ${h}`),t.assign(c,d(f[h]));t.else(),e.error(!1,{discrError:wc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(f){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:f},h);return e.mergeEvaluated(g,cr.Name),h}function p(){var f;let h={},g=w(o),_=!0;for(let P=0;P<s.length;P++){let R=s[P];if(R?.$ref&&!(0,bS.schemaHasRulesButRef)(R,i.self.RULES)){let ze=R.$ref;if(R=gh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,ze),R instanceof gh.SchemaEnv&&(R=R.schema),R===void 0)throw new wS.default(i.opts.uriResolver,i.baseId,ze)}let _e=(f=R?.properties)===null||f===void 0?void 0:f[a];if(typeof _e!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(g||w(R)),b(_e,P)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:P}){return Array.isArray(P)&&P.includes(a)}function b(P,R){if(P.const)$(P.const,R);else if(P.enum)for(let _e of P.enum)$(_e,R);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(P,R){if(typeof P!="string"||P in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[P]=R}}}};bc.default=xS});var _h=v((nD,kS)=>{kS.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 xc=v((X,$c)=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.MissingRefError=X.ValidationError=X.CodeGen=X.Name=X.nil=X.stringify=X.str=X._=X.KeywordCxt=X.Ajv=void 0;var SS=mm(),ES=fh(),PS=yh(),vh=_h(),TS=["/properties"],Lo="http://json-schema.org/draft-07/schema",ur=class extends SS.default{_addVocabularies(){super._addVocabularies(),ES.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(PS.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(vh,TS):vh;this.addMetaSchema(t,Lo,!1),this.refs["http://json-schema.org/schema"]=Lo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lo)?Lo:void 0)}};X.Ajv=ur;$c.exports=X=ur;$c.exports.Ajv=ur;Object.defineProperty(X,"__esModule",{value:!0});X.default=ur;var zS=on();Object.defineProperty(X,"KeywordCxt",{enumerable:!0,get:function(){return zS.KeywordCxt}});var lr=C();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return lr._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return lr.str}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return lr.stringify}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return lr.nil}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return lr.Name}});Object.defineProperty(X,"CodeGen",{enumerable:!0,get:function(){return lr.CodeGen}});var RS=bo();Object.defineProperty(X,"ValidationError",{enumerable:!0,get:function(){return RS.default}});var IS=sn();Object.defineProperty(X,"MissingRefError",{enumerable:!0,get:function(){return IS.default}})});var Ph=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Xe(e,t){return{validate:e,compare:t}}et.fullFormats={date:Xe(xh,Pc),time:Xe(Sc(!0),Tc),"date-time":Xe(wh(!0),Sh),"iso-time":Xe(Sc(),kh),"iso-date-time":Xe(wh(),Eh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:jS,"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:FS,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:MS,int32:{type:"number",validate:LS},int64:{type:"number",validate:ZS},float:{type:"number",validate:$h},double:{type:"number",validate:$h},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pc),time:Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Tc),"date-time":Xe(/^\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,Sh),"iso-time":Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,kh),"iso-date-time":Xe(/^\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,Eh),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};et.formatNames=Object.keys(et.fullFormats);function AS(e){return e%4===0&&(e%100!==0||e%400===0)}var NS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function xh(e){let t=NS.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&AS(r)?29:CS[n])}function Pc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Sc(e){return function(r){let n=kc.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,p=o-l*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function Tc(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function kh(e,t){if(!(e&&t))return;let r=kc.exec(e),n=kc.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var Ec=/t|\s/i;function wh(e){let t=Sc(e);return function(n){let o=n.split(Ec);return o.length===2&&xh(o[0])&&t(o[1])}}function Sh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Eh(e,t){if(!(e&&t))return;let[r,n]=e.split(Ec),[o,i]=t.split(Ec),s=Pc(r,o);if(s!==void 0)return s||Tc(n,i)}var OS=/\/|:/,DS=/^(?:[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 jS(e){return OS.test(e)&&DS.test(e)}var bh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function MS(e){return bh.lastIndex=0,bh.test(e)}var qS=-(2**31),BS=2**31-1;function LS(e){return Number.isInteger(e)&&e<=BS&&e>=qS}function ZS(e){return Number.isInteger(e)}function $h(){return!0}var US=/[^\\]\\Z/;function FS(e){if(US.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Th=v(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.formatLimitDefinition=void 0;var VS=xc(),Fe=C(),wt=Fe.operators,Zo={formatMaximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},formatMinimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},formatExclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},formatExclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},KS={message:({keyword:e,schemaCode:t})=>(0,Fe.str)`should be ${Zo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Fe._)`{comparison: ${Zo[e].okStr}, limit: ${t}}`};dr.formatLimitDefinition={keyword:Object.keys(Zo),type:"string",schemaType:"string",$data:!0,error:KS,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new VS.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let p=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=t.const("fmt",(0,Fe._)`${p}[${c.schemaCode}]`);e.fail$data((0,Fe.or)((0,Fe._)`typeof ${f} != "object"`,(0,Fe._)`${f} instanceof RegExp`,(0,Fe._)`typeof ${f}.compare != "function"`,d(f)))}function u(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=t.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,Fe._)`${s.code.formats}${(0,Fe.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,Fe._)`${p}.compare(${r}, ${n}) ${Zo[o].fail} 0`}},dependencies:["format"]};var HS=e=>(e.addKeyword(dr.formatLimitDefinition),e);dr.default=HS});var Ah=v((wn,Ih)=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});var pr=Ph(),GS=Th(),zc=C(),zh=new zc.Name("fullFormats"),WS=new zc.Name("fastFormats"),Rc=(e,t={keywords:!0})=>{if(Array.isArray(t))return Rh(e,t,pr.fullFormats,zh),e;let[r,n]=t.mode==="fast"?[pr.fastFormats,WS]:[pr.fullFormats,zh],o=t.formats||pr.formatNames;return Rh(e,o,r,n),t.keywords&&(0,GS.default)(e),e};Rc.get=(e,t="full")=>{let n=(t==="fast"?pr.fastFormats:pr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Rh(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,zc._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}Ih.exports=wn=Rc;Object.defineProperty(wn,"__esModule",{value:!0});wn.default=Rc});var Lh=v((yD,Bh)=>{Bh.exports=qh;qh.sync=XS;var jh=ct("fs");function YS(e,t){var r=t.pathExt!==void 0?t.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}function Mh(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:YS(t,r)}function qh(e,t,r){jh.stat(e,function(n,o){r(n,n?!1:Mh(o,e,t))})}function XS(e,t){return Mh(jh.statSync(e),e,t)}});var Kh=v((_D,Vh)=>{Vh.exports=Uh;Uh.sync=eE;var Zh=ct("fs");function Uh(e,t,r){Zh.stat(e,function(n,o){r(n,n?!1:Fh(o,t))})}function eE(e,t){return Fh(Zh.statSync(e),t)}function Fh(e,t){return e.isFile()&&tE(e,t)}function tE(e,t){var r=e.mode,n=e.uid,o=e.gid,i=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),s=t.gid!==void 0?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),l=parseInt("001",8),u=a|c,d=r&l||r&c&&o===s||r&a&&n===i||r&u&&i===0;return d}});var Gh=v((wD,Hh)=>{var vD=ct("fs"),Ho;process.platform==="win32"||global.TESTING_WINDOWS?Ho=Lh():Ho=Kh();Hh.exports=Ic;Ic.sync=rE;function Ic(e,t,r){if(typeof t=="function"&&(r=t,t={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Ic(e,t||{},function(i,s){i?o(i):n(s)})})}Ho(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function rE(e,t){try{return Ho.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var tg=v((bD,eg)=>{var fr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Wh=ct("path"),nE=fr?";":":",Jh=Gh(),Qh=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Yh=(e,t)=>{let r=t.colon||nE,n=e.match(/\//)||fr&&e.match(/\\/)?[""]:[...fr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=fr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=fr?o.split(r):[""];return fr&&e.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},Xh=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Yh(e,t),s=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&s.length?u(s):d(Qh(e));let p=n[l],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=Wh.join(f,e),g=!f&&/^\.[\\\/]/.test(e)?e.slice(0,2)+h:h;u(c(g,l,0))}),c=(l,u,d)=>new Promise((p,f)=>{if(d===o.length)return p(a(u+1));let h=o[d];Jh(l+h,{pathExt:i},(g,_)=>{if(!g&&_)if(t.all)s.push(l+h);else return p(l+h);return p(c(l,u,d+1))})});return r?a(0).then(l=>r(null,l),r):a(0)},oE=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Yh(e,t),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Wh.join(c,e),u=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+l:l;for(let d=0;d<n.length;d++){let p=u+n[d];try{if(Jh.sync(p,{pathExt:o}))if(t.all)i.push(p);else return p}catch{}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw Qh(e)};eg.exports=Xh;Xh.sync=oE});var ng=v(($D,Ac)=>{"use strict";var rg=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Ac.exports=rg;Ac.exports.default=rg});var ag=v((xD,sg)=>{"use strict";var og=ct("path"),iE=tg(),sE=ng();function ig(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(e.options.cwd)}catch{}let s;try{s=iE.sync(e.command,{path:r[sE({env:r})],pathExt:t?og.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=og.resolve(o?e.options.cwd:"",s)),s}function aE(e){return ig(e)||ig(e,!0)}sg.exports=aE});var cg=v((kD,Cc)=>{"use strict";var Nc=/([()\][%!^"`<>&|;, *?])/g;function cE(e){return e=e.replace(Nc,"^$1"),e}function uE(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace(Nc,"^$1"),t&&(e=e.replace(Nc,"^$1")),e}Cc.exports.command=cE;Cc.exports.argument=uE});var lg=v((SD,ug)=>{"use strict";ug.exports=/^#!(.*)/});var pg=v((ED,dg)=>{"use strict";var lE=lg();dg.exports=(e="")=>{let t=e.match(lE);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var mg=v((PD,fg)=>{"use strict";var Oc=ct("fs"),dE=pg();function pE(e){let r=Buffer.alloc(150),n;try{n=Oc.openSync(e,"r"),Oc.readSync(n,r,0,150,0),Oc.closeSync(n)}catch{}return dE(r.toString())}fg.exports=pE});var _g=v((TD,yg)=>{"use strict";var fE=ct("path"),hg=ag(),gg=cg(),mE=mg(),hE=process.platform==="win32",gE=/\.(?:com|exe)$/i,yE=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function _E(e){e.file=hg(e);let t=e.file&&mE(e.file);return t?(e.args.unshift(e.file),e.command=t,hg(e)):e.file}function vE(e){if(!hE)return e;let t=_E(e),r=!gE.test(t);if(e.options.forceShell||r){let n=yE.test(t);e.command=fE.normalize(e.command),e.command=gg.command(e.command),e.args=e.args.map(i=>gg.argument(i,n));let o=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${o}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}function wE(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null),t=t?t.slice(0):[],r=Object.assign({},r);let n={command:e,args:t,options:r,file:void 0,original:{command:e,args:t}};return r.shell?n:vE(n)}yg.exports=wE});var bg=v((zD,wg)=>{"use strict";var Dc=process.platform==="win32";function jc(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function bE(e,t){if(!Dc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let i=vg(o,t);if(i)return r.call(e,"error",i)}return r.apply(e,arguments)}}function vg(e,t){return Dc&&e===1&&!t.file?jc(t.original,"spawn"):null}function $E(e,t){return Dc&&e===1&&!t.file?jc(t.original,"spawnSync"):null}wg.exports={hookChildProcess:bE,verifyENOENT:vg,verifyENOENTSync:$E,notFoundError:jc}});var kg=v((RD,mr)=>{"use strict";var $g=ct("child_process"),Mc=_g(),qc=bg();function xg(e,t,r){let n=Mc(e,t,r),o=$g.spawn(n.command,n.args,n.options);return qc.hookChildProcess(o,n),o}function xE(e,t,r){let n=Mc(e,t,r),o=$g.spawnSync(n.command,n.args,n.options);return o.error=o.error||qc.verifyENOENTSync(o.status,n),o}mr.exports=xg;mr.exports.spawn=xg;mr.exports.sync=xE;mr.exports._parse=Mc;mr.exports._enoent=qc});import{readFile as Gz,mkdir as Wz,writeFile as Jz}from"node:fs/promises";import{dirname as Qz,join as qy}from"node:path";var gR=Object.freeze({status:"aborted"});function y(e,t,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var yR=Symbol("zod_brand"),tt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},An={};function Re(e){return e&&Object.assign(An,e),An}var U={};yu(U,{BIGINT_FORMAT_RANGES:()=>vu,Class:()=>bi,NUMBER_FORMAT_RANGES:()=>zi,aborted:()=>kt,allowsEval:()=>Ei,assert:()=>Qy,assertEqual:()=>Hy,assertIs:()=>Wy,assertNever:()=>Jy,assertNotEqual:()=>Gy,assignProp:()=>Si,cached:()=>kr,captureStackTrace:()=>Cn,cleanEnum:()=>l_,cleanRegex:()=>Er,clone:()=>Ge,createTransparentProxy:()=>n_,defineLazy:()=>H,esc:()=>xt,escapeRegex:()=>ut,extend:()=>s_,finalizeIssue:()=>Me,floatSafeRemainder:()=>ki,getElementAtPath:()=>Yy,getEnumValues:()=>$i,getLengthableOrigin:()=>Pr,getParsedType:()=>r_,getSizableOrigin:()=>wu,isObject:()=>Ut,isPlainObject:()=>Ft,issue:()=>Ri,joinValues:()=>Nn,jsonStringifyReplacer:()=>xi,merge:()=>a_,normalizeParams:()=>T,nullish:()=>Sr,numKeys:()=>t_,omit:()=>i_,optionalKeys:()=>Ti,partial:()=>c_,pick:()=>o_,prefixIssues:()=>We,primitiveTypes:()=>_u,promiseAllObject:()=>Xy,propertyKeyTypes:()=>Pi,randomString:()=>e_,required:()=>u_,stringifyPrimitive:()=>On,unwrapMessage:()=>xr});function Hy(e){return e}function Gy(e){return e}function Wy(e){}function Jy(e){throw new Error}function Qy(e){}function $i(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Nn(e,t="|"){return e.map(r=>On(r)).join(t)}function xi(e,t){return typeof t=="bigint"?t.toString():t}function kr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Sr(e){return e==null}function Er(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ki(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function H(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Si(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Yy(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Xy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function e_(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function xt(e){return JSON.stringify(e)}var Cn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ei=kr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ft(e){if(Ut(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Ut(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function t_(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var r_=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Pi=new Set(["string","number","symbol"]),_u=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function T(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function n_(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function On(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Ti(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var zi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},vu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function o_(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function i_(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function s_(e,t){if(!Ft(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Si(this,"shape",n),n},checks:[]};return Ge(e,r)}function a_(e,t){return Ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Si(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function c_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Ge(t,{...t._zod.def,shape:o,checks:[]})}function u_(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Ge(t,{...t._zod.def,shape:o,checks:[]})}function kt(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function We(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function xr(e){return typeof e=="string"?e:e?.message}function Me(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=xr(e.inst?._zod.def?.error?.(e))??xr(t?.error?.(e))??xr(r.customError?.(e))??xr(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function wu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Pr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ri(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function l_(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var bi=class{constructor(...t){}};var bu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,xi,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Dn=y("$ZodError",bu),Ii=y("$ZodError",bu,{Parent:Error});function $u(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function xu(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var ku=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new tt;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Me(c,i,Re())));throw Cn(a,o?.callee),a}return s.value};var Su=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Me(c,i,Re())));throw Cn(a,o?.callee),a}return s.value};var Ai=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new tt;return i.issues.length?{success:!1,error:new(e??Dn)(i.issues.map(s=>Me(s,o,Re())))}:{success:!0,data:i.value}},Tr=Ai(Ii),Ni=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Me(s,o,Re())))}:{success:!0,data:i.value}},jn=Ni(Ii);var Eu=/^[cC][^\s-]{8,}$/,Pu=/^[0-9a-z]+$/,Tu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zu=/^[0-9a-vA-V]{20}$/,Ru=/^[A-Za-z0-9]{27}$/,Iu=/^[a-zA-Z0-9_-]{21}$/,Au=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Nu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ci=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Cu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var p_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ou(){return new RegExp(p_,"u")}var Du=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ju=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Mu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,qu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oi=/^[A-Za-z0-9_-]*$/,Lu=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Zu=/^\+(?:[0-9]){6,14}[0-9]$/,Uu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Fu=new RegExp(`^${Uu}$`);function Vu(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ku(e){return new RegExp(`^${Vu(e)}$`)}function Hu(e){let t=Vu({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Uu}T(?:${n})$`)}var Gu=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Wu=/^\d+$/,Ju=/^-?\d+(?:\.\d+)?/i,Qu=/true|false/i,Yu=/null/i;var Xu=/^[^A-Z]*$/,el=/^[^a-z]*$/;var fe=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tl={number:"number",bigint:"bigint",object:"date"},ji=y("$ZodCheckLessThan",(e,t)=>{fe.init(e,t);let r=tl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Mi=y("$ZodCheckGreaterThan",(e,t)=>{fe.init(e,t);let r=tl[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rl=y("$ZodCheckMultipleOf",(e,t)=>{fe.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ki(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),nl=y("$ZodCheckNumberFormat",(e,t)=>{fe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=zi[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=Wu)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var ol=y("$ZodCheckMaxLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Pr(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),il=y("$ZodCheckMinLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Pr(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),sl=y("$ZodCheckLengthEquals",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Sr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Pr(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),zr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;fe.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),al=y("$ZodCheckRegex",(e,t)=>{zr.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),cl=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xu),zr.init(e,t)}),ul=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=el),zr.init(e,t)}),ll=y("$ZodCheckIncludes",(e,t)=>{fe.init(e,t);let r=ut(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),dl=y("$ZodCheckStartsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`^${ut(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),pl=y("$ZodCheckEndsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`.*${ut(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var fl=y("$ZodCheckOverwrite",(e,t)=>{fe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Mn=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
11
11
  `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
12
- `))}};var ml={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ml;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=kt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,p=u._zod.check(i);if(p instanceof Promise&&a?.async===!1)throw new tt;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,i.issues.length!==d&&(c||(c=kt(i,d)))});else{if(i.issues.length===d)continue;c||(c=kt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new tt;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=zr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return jn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Bn=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Hu(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),J=y("$ZodStringFormat",(e,t)=>{Tr.init(e,t),Bn.init(e,t)}),kl=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Au),J.init(e,t)}),Sl=y("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ci(n))}else t.pattern??(t.pattern=Ci());J.init(e,t)}),El=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Nu),J.init(e,t)}),Pl=y("$ZodURL",(e,t)=>{J.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Bu.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),zl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Cu()),J.init(e,t)}),Tl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ru),J.init(e,t)}),Rl=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Su),J.init(e,t)}),Il=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Eu),J.init(e,t)}),Al=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Pu),J.init(e,t)}),Nl=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=zu),J.init(e,t)}),Cl=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Tu),J.init(e,t)}),Ol=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ku(t)),J.init(e,t)}),Dl=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Uu),J.init(e,t)}),jl=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Vu(t)),J.init(e,t)}),Ml=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Iu),J.init(e,t)}),ql=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ou),J.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Bl=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Du),J.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ll=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ju),J.init(e,t)}),Zl=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Mu),J.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Ul(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Fl=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qu),J.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Ul(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function p_(e){if(!Oi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ul(r)}var Vl=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oi),J.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{p_(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Kl=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lu),J.init(e,t)});function f_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Hl=y("$ZodJWT",(e,t)=>{J.init(e,t),e._zod.check=r=>{f_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Bi=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),Gl=y("$ZodNumber",(e,t)=>{rl.init(e,t),Bi.init(e,t)}),Wl=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=Ju,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Jl=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=Qu,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Ql=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),Yl=y("$ZodNever",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function hl(e,t,r){e.issues.length&&t.issues.push(...We(r,e.issues)),t.value[r]=e.value}var Xl=y("$ZodArray",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>hl(l,r,s))):hl(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function qn(e,t,r){e.issues.length&&t.issues.push(...We(r,e.issues)),t.value[r]=e.value}function gl(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...We(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var ed=y("$ZodObject",(e,t)=>{G.init(e,t);let r=kr(()=>{let d=Object.keys(t.shape);for(let f of d)if(!(t.shape[f]instanceof G))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=zi(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});H(e._zod,"propValues",()=>{let d=t.shape,p={};for(let f in d){let h=d[f]._zod;if(h.values){p[f]??(p[f]=new Set);for(let g of h.values)p[f].add(g)}}return p});let n=d=>{let p=new Mn(["shape","payload","ctx"]),f=r.value,h=b=>{let $=xt(b);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),_=0;for(let b of f.keys)g[b]=`key_${_++}`;p.write("const newResult = {}");for(let b of f.keys)if(f.optionalKeys.has(b)){let $=g[b];p.write(`const ${$} = ${h(b)};`);let P=xt(b);p.write(`
12
+ `))}};var hl={major:4,minor:0,patch:0};var G=y("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=hl;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=kt(i),l;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,p=u._zod.check(i);if(p instanceof Promise&&a?.async===!1)throw new tt;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,i.issues.length!==d&&(c||(c=kt(i,d)))});else{if(i.issues.length===d)continue;c||(c=kt(i,d))}}return l?l.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new tt;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Tr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return jn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Bn=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Gu(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),J=y("$ZodStringFormat",(e,t)=>{zr.init(e,t),Bn.init(e,t)}),Sl=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Nu),J.init(e,t)}),El=y("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ci(n))}else t.pattern??(t.pattern=Ci());J.init(e,t)}),Pl=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Cu),J.init(e,t)}),Tl=y("$ZodURL",(e,t)=>{J.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Lu.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),zl=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ou()),J.init(e,t)}),Rl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Iu),J.init(e,t)}),Il=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Eu),J.init(e,t)}),Al=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pu),J.init(e,t)}),Nl=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Tu),J.init(e,t)}),Cl=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=zu),J.init(e,t)}),Ol=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ru),J.init(e,t)}),Dl=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Hu(t)),J.init(e,t)}),jl=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Fu),J.init(e,t)}),Ml=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ku(t)),J.init(e,t)}),ql=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Au),J.init(e,t)}),Bl=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Du),J.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Ll=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ju),J.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Zl=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Mu),J.init(e,t)}),Ul=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=qu),J.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Fl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Vl=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Bu),J.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{Fl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function f_(e){if(!Oi.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Fl(r)}var Kl=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oi),J.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{f_(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Hl=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Zu),J.init(e,t)});function m_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Gl=y("$ZodJWT",(e,t)=>{J.init(e,t),e._zod.check=r=>{m_(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Bi=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ju,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),Wl=y("$ZodNumber",(e,t)=>{nl.init(e,t),Bi.init(e,t)}),Jl=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=Qu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Ql=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=Yu,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Yl=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),Xl=y("$ZodNever",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function gl(e,t,r){e.issues.length&&t.issues.push(...We(r,e.issues)),t.value[r]=e.value}var ed=y("$ZodArray",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>gl(l,r,s))):gl(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function qn(e,t,r){e.issues.length&&t.issues.push(...We(r,e.issues)),t.value[r]=e.value}function yl(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...We(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var td=y("$ZodObject",(e,t)=>{G.init(e,t);let r=kr(()=>{let d=Object.keys(t.shape);for(let f of d)if(!(t.shape[f]instanceof G))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Ti(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});H(e._zod,"propValues",()=>{let d=t.shape,p={};for(let f in d){let h=d[f]._zod;if(h.values){p[f]??(p[f]=new Set);for(let g of h.values)p[f].add(g)}}return p});let n=d=>{let p=new Mn(["shape","payload","ctx"]),f=r.value,h=b=>{let $=xt(b);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),_=0;for(let b of f.keys)g[b]=`key_${_++}`;p.write("const newResult = {}");for(let b of f.keys)if(f.optionalKeys.has(b)){let $=g[b];p.write(`const ${$} = ${h(b)};`);let P=xt(b);p.write(`
13
13
  if (${$}.issues.length) {
14
14
  if (input[${P}] === undefined) {
15
15
  if (${P} in input) {
@@ -32,27 +32,29 @@ var By=Object.create;var _i=Object.defineProperty;var Ly=Object.getOwnPropertyDe
32
32
  if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
33
33
  ...iss,
34
34
  path: iss.path ? [${xt(b)}, ...iss.path] : [${xt(b)}]
35
- })));`),p.write(`newResult[${xt(b)}] = ${$}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,$)=>w(d,b,$)},o,i=Ut,s=!An.jitless,c=s&&Ei.value,l=t.catchall,u;e._zod.parse=(d,p)=>{u??(u=r.value);let f=d.value;if(!i(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d;let h=[];if(s&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let $=u.shape;for(let P of u.keys){let R=$[P],_e=R._zod.run({value:f[P],issues:[]},p),Te=R._zod.optin==="optional"&&R._zod.optout==="optional";_e instanceof Promise?h.push(_e.then(Zt=>Te?gl(Zt,d,P,f):qn(Zt,d,P))):Te?gl(_e,d,P,f):qn(_e,d,P)}}if(!l)return h.length?Promise.all(h).then(()=>d):d;let g=[],_=u.keySet,w=l._zod,b=w.def.type;for(let $ of Object.keys(f)){if(_.has($))continue;if(b==="never"){g.push($);continue}let P=w.run({value:f[$],issues:[]},p);P instanceof Promise?h.push(P.then(R=>qn(R,d,$))):qn(P,d,$)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function yl(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(i=>Me(i,n,Re())))}),t}var Li=y("$ZodUnion",(e,t)=>{G.init(e,t),H(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),H(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),H(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),H(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Er(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>yl(s,r,e,n)):yl(i,r,e,n)}}),td=y("$ZodDiscriminatedUnion",(e,t)=>{Li.init(e,t);let r=e._zod.parse;H(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=kr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Ut(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),rd=y("$ZodIntersection",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>_l(r,c,l)):_l(r,i,s)}});function qi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ft(e)&&Ft(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=qi(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=qi(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function _l(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),kt(e))return e;let n=qi(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var nd=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Ft(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...We(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...We(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Me(l,n,Re())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...We(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...We(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var od=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=$i(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Pi.has(typeof n)).map(n=>typeof n=="string"?ut(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),id=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ut(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var sd=y("$ZodTransform",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new tt;return r.value=o,r}}),ad=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),H(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Er(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),cd=y("$ZodNullable",(e,t)=>{G.init(e,t),H(e._zod,"optin",()=>t.innerType._zod.optin),H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Er(r.source)}|null)$`):void 0}),H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),ud=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>vl(i,t)):vl(o,t)}});function vl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ld=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),dd=y("$ZodNonOptional",(e,t)=>{G.init(e,t),H(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>wl(i,e)):wl(o,e)}});function wl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var pd=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Me(s,n,Re()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Me(i,n,Re()))},input:r.value}),r.issues=[]),r)}});var fd=y("$ZodPipe",(e,t)=>{G.init(e,t),H(e._zod,"values",()=>t.in._zod.values),H(e._zod,"optin",()=>t.in._zod.optin),H(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>bl(i,t,n)):bl(o,t,n)}});function bl(e,t,r){return kt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var md=y("$ZodReadonly",(e,t)=>{G.init(e,t),H(e._zod,"propValues",()=>t.innerType._zod.propValues),H(e._zod,"values",()=>t.innerType._zod.values),H(e._zod,"optin",()=>t.innerType._zod.optin),H(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then($l):$l(o)}});function $l(e){return e.value=Object.freeze(e.value),e}var hd=y("$ZodCustom",(e,t)=>{fe.init(e,t),G.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>xl(i,r,n,e));xl(o,r,n,e)}});function xl(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Ri(o))}}var m_=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},h_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${m_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${On(n.values[0])}`:`Invalid option: expected one of ${Nn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Nn(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function gd(){return{localeError:h_()}}var ER=Symbol("ZodOutput"),PR=Symbol("ZodInput"),Zi=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function g_(){return new Zi}var Rr=g_();function yd(e,t){return new e({type:"string",...z(t)})}function _d(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...z(t)})}function Ui(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...z(t)})}function vd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...z(t)})}function wd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(t)})}function bd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(t)})}function $d(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(t)})}function xd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...z(t)})}function kd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...z(t)})}function Sd(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(t)})}function Ed(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...z(t)})}function Pd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(t)})}function zd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...z(t)})}function Td(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...z(t)})}function Rd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(t)})}function Id(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(t)})}function Ad(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(t)})}function Nd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(t)})}function Cd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(t)})}function Od(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...z(t)})}function Dd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...z(t)})}function jd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...z(t)})}function Md(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...z(t)})}function qd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(t)})}function Bd(e,t){return new e({type:"string",format:"date",check:"string_format",...z(t)})}function Ld(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...z(t)})}function Zd(e,t){return new e({type:"string",format:"duration",check:"string_format",...z(t)})}function Ud(e,t){return new e({type:"number",checks:[],...z(t)})}function Fd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...z(t)})}function Vd(e,t){return new e({type:"boolean",...z(t)})}function Kd(e,t){return new e({type:"null",...z(t)})}function Hd(e){return new e({type:"unknown"})}function Gd(e,t){return new e({type:"never",...z(t)})}function Ln(e,t){return new ji({check:"less_than",...z(t),value:e,inclusive:!1})}function Ir(e,t){return new ji({check:"less_than",...z(t),value:e,inclusive:!0})}function Zn(e,t){return new Mi({check:"greater_than",...z(t),value:e,inclusive:!1})}function Ar(e,t){return new Mi({check:"greater_than",...z(t),value:e,inclusive:!0})}function Un(e,t){return new tl({check:"multiple_of",...z(t),value:e})}function Fn(e,t){return new nl({check:"max_length",...z(t),maximum:e})}function Vt(e,t){return new ol({check:"min_length",...z(t),minimum:e})}function Vn(e,t){return new il({check:"length_equals",...z(t),length:e})}function Fi(e,t){return new sl({check:"string_format",format:"regex",...z(t),pattern:e})}function Vi(e){return new al({check:"string_format",format:"lowercase",...z(e)})}function Ki(e){return new cl({check:"string_format",format:"uppercase",...z(e)})}function Hi(e,t){return new ul({check:"string_format",format:"includes",...z(t),includes:e})}function Gi(e,t){return new ll({check:"string_format",format:"starts_with",...z(t),prefix:e})}function Wi(e,t){return new dl({check:"string_format",format:"ends_with",...z(t),suffix:e})}function St(e){return new pl({check:"overwrite",tx:e})}function Ji(e){return St(t=>t.normalize(e))}function Qi(){return St(e=>e.trim())}function Yi(){return St(e=>e.toLowerCase())}function Xi(){return St(e=>e.toUpperCase())}function Wd(e,t,r){return new e({type:"array",element:t,...z(r)})}function Jd(e,t,r){let n=z(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Qd(e,t,r){return new e({type:"custom",check:"custom",fn:t,...z(r)})}function Kt(e){return!!e._zod}function qe(e,t){return Kt(e)?zr(e,t):e.safeParse(t)}function Kn(e){if(!e)return;let t;if(Kt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Yd(e){if(Kt(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._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=e.value;if(n!==void 0)return n}var Cr={};gu(Cr,{ZodISODate:()=>ep,ZodISODateTime:()=>Xd,ZodISODuration:()=>rp,ZodISOTime:()=>tp,date:()=>ts,datetime:()=>es,duration:()=>ns,time:()=>rs});var Xd=y("ZodISODateTime",(e,t)=>{Ol.init(e,t),ee.init(e,t)});function es(e){return qd(Xd,e)}var ep=y("ZodISODate",(e,t)=>{Dl.init(e,t),ee.init(e,t)});function ts(e){return Bd(ep,e)}var tp=y("ZodISOTime",(e,t)=>{jl.init(e,t),ee.init(e,t)});function rs(e){return Ld(tp,e)}var rp=y("ZodISODuration",(e,t)=>{Ml.init(e,t),ee.init(e,t)});function ns(e){return Zd(rp,e)}var np=(e,t)=>{Dn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>$u(e,r)},flatten:{value:r=>bu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},aI=y("ZodError",np),Or=y("ZodError",np,{Parent:Error});var op=xu(Or),ip=ku(Or),sp=Ai(Or),ap=Ni(Or);var ne=y("ZodType",(e,t)=>(G.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Ge(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>op(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>sp(e,r,n),e.parseAsync=async(r,n)=>ip(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ap(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(fv(r,n)),e.superRefine=r=>e.check(mv(r)),e.overwrite=r=>e.check(St(r)),e.optional=()=>re(e),e.nullable=()=>lp(e),e.nullish=()=>re(lp(e)),e.nonoptional=r=>sv(e,r),e.array=()=>M(e),e.or=r=>Q([e,r]),e.and=r=>Gn(e,r),e.transform=r=>is(e,gp(r)),e.default=r=>nv(e,r),e.prefault=r=>iv(e,r),e.catch=r=>cv(e,r),e.pipe=r=>is(e,r),e.readonly=()=>dv(e),e.describe=r=>{let n=e.clone();return Rr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Rr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Rr.get(e);let n=e.clone();return Rr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),dp=y("_ZodString",(e,t)=>{Bn.init(e,t),ne.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Fi(...n)),e.includes=(...n)=>e.check(Hi(...n)),e.startsWith=(...n)=>e.check(Gi(...n)),e.endsWith=(...n)=>e.check(Wi(...n)),e.min=(...n)=>e.check(Vt(...n)),e.max=(...n)=>e.check(Fn(...n)),e.length=(...n)=>e.check(Vn(...n)),e.nonempty=(...n)=>e.check(Vt(1,...n)),e.lowercase=n=>e.check(Vi(n)),e.uppercase=n=>e.check(Ki(n)),e.trim=()=>e.check(Qi()),e.normalize=(...n)=>e.check(Ji(...n)),e.toLowerCase=()=>e.check(Yi()),e.toUpperCase=()=>e.check(Xi())}),S_=y("ZodString",(e,t)=>{Bn.init(e,t),dp.init(e,t),e.email=r=>e.check(_d(E_,r)),e.url=r=>e.check(xd(P_,r)),e.jwt=r=>e.check(Md(Z_,r)),e.emoji=r=>e.check(kd(z_,r)),e.guid=r=>e.check(Ui(cp,r)),e.uuid=r=>e.check(vd(Hn,r)),e.uuidv4=r=>e.check(wd(Hn,r)),e.uuidv6=r=>e.check(bd(Hn,r)),e.uuidv7=r=>e.check($d(Hn,r)),e.nanoid=r=>e.check(Sd(T_,r)),e.guid=r=>e.check(Ui(cp,r)),e.cuid=r=>e.check(Ed(R_,r)),e.cuid2=r=>e.check(Pd(I_,r)),e.ulid=r=>e.check(zd(A_,r)),e.base64=r=>e.check(Od(q_,r)),e.base64url=r=>e.check(Dd(B_,r)),e.xid=r=>e.check(Td(N_,r)),e.ksuid=r=>e.check(Rd(C_,r)),e.ipv4=r=>e.check(Id(O_,r)),e.ipv6=r=>e.check(Ad(D_,r)),e.cidrv4=r=>e.check(Nd(j_,r)),e.cidrv6=r=>e.check(Cd(M_,r)),e.e164=r=>e.check(jd(L_,r)),e.datetime=r=>e.check(es(r)),e.date=r=>e.check(ts(r)),e.time=r=>e.check(rs(r)),e.duration=r=>e.check(ns(r))});function m(e){return yd(S_,e)}var ee=y("ZodStringFormat",(e,t)=>{J.init(e,t),dp.init(e,t)}),E_=y("ZodEmail",(e,t)=>{El.init(e,t),ee.init(e,t)});var cp=y("ZodGUID",(e,t)=>{kl.init(e,t),ee.init(e,t)});var Hn=y("ZodUUID",(e,t)=>{Sl.init(e,t),ee.init(e,t)});var P_=y("ZodURL",(e,t)=>{Pl.init(e,t),ee.init(e,t)});var z_=y("ZodEmoji",(e,t)=>{zl.init(e,t),ee.init(e,t)});var T_=y("ZodNanoID",(e,t)=>{Tl.init(e,t),ee.init(e,t)});var R_=y("ZodCUID",(e,t)=>{Rl.init(e,t),ee.init(e,t)});var I_=y("ZodCUID2",(e,t)=>{Il.init(e,t),ee.init(e,t)});var A_=y("ZodULID",(e,t)=>{Al.init(e,t),ee.init(e,t)});var N_=y("ZodXID",(e,t)=>{Nl.init(e,t),ee.init(e,t)});var C_=y("ZodKSUID",(e,t)=>{Cl.init(e,t),ee.init(e,t)});var O_=y("ZodIPv4",(e,t)=>{ql.init(e,t),ee.init(e,t)});var D_=y("ZodIPv6",(e,t)=>{Bl.init(e,t),ee.init(e,t)});var j_=y("ZodCIDRv4",(e,t)=>{Ll.init(e,t),ee.init(e,t)});var M_=y("ZodCIDRv6",(e,t)=>{Zl.init(e,t),ee.init(e,t)});var q_=y("ZodBase64",(e,t)=>{Fl.init(e,t),ee.init(e,t)});var B_=y("ZodBase64URL",(e,t)=>{Vl.init(e,t),ee.init(e,t)});var L_=y("ZodE164",(e,t)=>{Kl.init(e,t),ee.init(e,t)});var Z_=y("ZodJWT",(e,t)=>{Hl.init(e,t),ee.init(e,t)});var pp=y("ZodNumber",(e,t)=>{Bi.init(e,t),ne.init(e,t),e.gt=(n,o)=>e.check(Zn(n,o)),e.gte=(n,o)=>e.check(Ar(n,o)),e.min=(n,o)=>e.check(Ar(n,o)),e.lt=(n,o)=>e.check(Ln(n,o)),e.lte=(n,o)=>e.check(Ir(n,o)),e.max=(n,o)=>e.check(Ir(n,o)),e.int=n=>e.check(up(n)),e.safe=n=>e.check(up(n)),e.positive=n=>e.check(Zn(0,n)),e.nonnegative=n=>e.check(Ar(0,n)),e.negative=n=>e.check(Ln(0,n)),e.nonpositive=n=>e.check(Ir(0,n)),e.multipleOf=(n,o)=>e.check(Un(n,o)),e.step=(n,o)=>e.check(Un(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function F(e){return Ud(pp,e)}var U_=y("ZodNumberFormat",(e,t)=>{Gl.init(e,t),pp.init(e,t)});function up(e){return Fd(U_,e)}var F_=y("ZodBoolean",(e,t)=>{Wl.init(e,t),ne.init(e,t)});function ae(e){return Vd(F_,e)}var V_=y("ZodNull",(e,t)=>{Jl.init(e,t),ne.init(e,t)});function fp(e){return Kd(V_,e)}var K_=y("ZodUnknown",(e,t)=>{Ql.init(e,t),ne.init(e,t)});function te(){return Hd(K_)}var H_=y("ZodNever",(e,t)=>{Yl.init(e,t),ne.init(e,t)});function G_(e){return Gd(H_,e)}var W_=y("ZodArray",(e,t)=>{Xl.init(e,t),ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Vt(r,n)),e.nonempty=r=>e.check(Vt(1,r)),e.max=(r,n)=>e.check(Fn(r,n)),e.length=(r,n)=>e.check(Vn(r,n)),e.unwrap=()=>e.element});function M(e,t){return Wd(W_,e,t)}var mp=y("ZodObject",(e,t)=>{ed.init(e,t),ne.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>xe(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:te()}),e.loose=()=>e.clone({...e._zod.def,catchall:te()}),e.strict=()=>e.clone({...e._zod.def,catchall:G_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>U.extend(e,r),e.merge=r=>U.merge(e,r),e.pick=r=>U.pick(e,r),e.omit=r=>U.omit(e,r),e.partial=(...r)=>U.partial(yp,e,r[0]),e.required=(...r)=>U.required(_p,e,r[0])});function x(e,t){let r={type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},...U.normalizeParams(t)};return new mp(r)}function ve(e,t){return new mp({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:te(),...U.normalizeParams(t)})}var hp=y("ZodUnion",(e,t)=>{Li.init(e,t),ne.init(e,t),e.options=t.options});function Q(e,t){return new hp({type:"union",options:e,...U.normalizeParams(t)})}var J_=y("ZodDiscriminatedUnion",(e,t)=>{hp.init(e,t),td.init(e,t)});function ss(e,t,r){return new J_({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Q_=y("ZodIntersection",(e,t)=>{rd.init(e,t),ne.init(e,t)});function Gn(e,t){return new Q_({type:"intersection",left:e,right:t})}var Y_=y("ZodRecord",(e,t)=>{nd.init(e,t),ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function W(e,t,r){return new Y_({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var os=y("ZodEnum",(e,t)=>{od.init(e,t),ne.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new os({...t,checks:[],...U.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new os({...t,checks:[],...U.normalizeParams(o),entries:i})}});function xe(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new os({type:"enum",entries:r,...U.normalizeParams(t)})}var X_=y("ZodLiteral",(e,t)=>{id.init(e,t),ne.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function k(e,t){return new X_({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var ev=y("ZodTransform",(e,t)=>{sd.init(e,t),ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(U.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(U.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function gp(e){return new ev({type:"transform",transform:e})}var yp=y("ZodOptional",(e,t)=>{ad.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function re(e){return new yp({type:"optional",innerType:e})}var tv=y("ZodNullable",(e,t)=>{cd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function lp(e){return new tv({type:"nullable",innerType:e})}var rv=y("ZodDefault",(e,t)=>{ud.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function nv(e,t){return new rv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var ov=y("ZodPrefault",(e,t)=>{ld.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function iv(e,t){return new ov({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var _p=y("ZodNonOptional",(e,t)=>{dd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function sv(e,t){return new _p({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var av=y("ZodCatch",(e,t)=>{pd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cv(e,t){return new av({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var uv=y("ZodPipe",(e,t)=>{fd.init(e,t),ne.init(e,t),e.in=t.in,e.out=t.out});function is(e,t){return new uv({type:"pipe",in:e,out:t})}var lv=y("ZodReadonly",(e,t)=>{md.init(e,t),ne.init(e,t)});function dv(e){return new lv({type:"readonly",innerType:e})}var vp=y("ZodCustom",(e,t)=>{hd.init(e,t),ne.init(e,t)});function pv(e){let t=new fe({check:"custom"});return t._zod.check=e,t}function wp(e,t){return Jd(vp,e??(()=>!0),t)}function fv(e,t={}){return Qd(vp,e,t)}function mv(e){let t=pv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(U.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(U.issue(o))}},e(r.value,r)));return t}function as(e,t){return is(gp(e),t)}Re(gd());var us="2025-11-25";var bp=[us,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lt="io.modelcontextprotocol/related-task",Jn="2.0",se=wp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),$p=Q([m(),F().int()]),xp=m(),eA=ve({ttl:F().optional(),pollInterval:F().optional()}),hv=x({ttl:F().optional()}),gv=x({taskId:m()}),ls=ve({progressToken:$p.optional(),[lt]:gv.optional()}),ze=x({_meta:ls.optional()}),Dr=ze.extend({task:hv.optional()}),kp=e=>Dr.safeParse(e).success,ce=x({method:m(),params:ze.loose().optional()}),Ie=x({_meta:ls.optional()}),Ae=x({method:m(),params:Ie.loose().optional()}),ue=ve({_meta:ls.optional()}),Qn=Q([m(),F().int()]),Sp=x({jsonrpc:k(Jn),id:Qn,...ce.shape}).strict(),ds=e=>Sp.safeParse(e).success,Ep=x({jsonrpc:k(Jn),...Ae.shape}).strict(),Pp=e=>Ep.safeParse(e).success,ps=x({jsonrpc:k(Jn),id:Qn,result:ue}).strict(),jr=e=>ps.safeParse(e).success;var I;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(I||(I={}));var fs=x({jsonrpc:k(Jn),id:Qn.optional(),error:x({code:F().int(),message:m(),data:te().optional()})}).strict();var zp=e=>fs.safeParse(e).success;var Tp=Q([Sp,Ep,ps,fs]),tA=Q([ps,fs]),Et=ue.strict(),yv=Ie.extend({requestId:Qn.optional(),reason:m().optional()}),Yn=Ae.extend({method:k("notifications/cancelled"),params:yv}),_v=x({src:m(),mimeType:m().optional(),sizes:M(m()).optional(),theme:xe(["light","dark"]).optional()}),Mr=x({icons:M(_v).optional()}),Ht=x({name:m(),title:m().optional()}),Rp=Ht.extend({...Ht.shape,...Mr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),vv=Gn(x({applyDefaults:ae().optional()}),W(m(),te())),wv=as(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Gn(x({form:vv.optional(),url:se.optional()}),W(m(),te()).optional())),bv=ve({list:se.optional(),cancel:se.optional(),requests:ve({sampling:ve({createMessage:se.optional()}).optional(),elicitation:ve({create:se.optional()}).optional()}).optional()}),$v=ve({list:se.optional(),cancel:se.optional(),requests:ve({tools:ve({call:se.optional()}).optional()}).optional()}),xv=x({experimental:W(m(),se).optional(),sampling:x({context:se.optional(),tools:se.optional()}).optional(),elicitation:wv.optional(),roots:x({listChanged:ae().optional()}).optional(),tasks:bv.optional(),extensions:W(m(),se).optional()}),kv=ze.extend({protocolVersion:m(),capabilities:xv,clientInfo:Rp}),Sv=ce.extend({method:k("initialize"),params:kv});var Ev=x({experimental:W(m(),se).optional(),logging:se.optional(),completions:se.optional(),prompts:x({listChanged:ae().optional()}).optional(),resources:x({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:x({listChanged:ae().optional()}).optional(),tasks:$v.optional(),extensions:W(m(),se).optional()}),ms=ue.extend({protocolVersion:m(),capabilities:Ev,serverInfo:Rp,instructions:m().optional()}),Pv=Ae.extend({method:k("notifications/initialized"),params:Ie.optional()});var Xn=ce.extend({method:k("ping"),params:ze.optional()}),zv=x({progress:F(),total:re(F()),message:re(m())}),Tv=x({...Ie.shape,...zv.shape,progressToken:$p}),eo=Ae.extend({method:k("notifications/progress"),params:Tv}),Rv=ze.extend({cursor:xp.optional()}),qr=ce.extend({params:Rv.optional()}),Br=ue.extend({nextCursor:xp.optional()}),Iv=xe(["working","input_required","completed","failed","cancelled"]),Lr=x({taskId:m(),status:Iv,ttl:Q([F(),fp()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:re(F()),statusMessage:re(m())}),Pt=ue.extend({task:Lr}),Av=Ie.merge(Lr),Zr=Ae.extend({method:k("notifications/tasks/status"),params:Av}),to=ce.extend({method:k("tasks/get"),params:ze.extend({taskId:m()})}),ro=ue.merge(Lr),no=ce.extend({method:k("tasks/result"),params:ze.extend({taskId:m()})}),rA=ue.loose(),oo=qr.extend({method:k("tasks/list")}),io=Br.extend({tasks:M(Lr)}),so=ce.extend({method:k("tasks/cancel"),params:ze.extend({taskId:m()})}),Ip=ue.merge(Lr),Ap=x({uri:m(),mimeType:re(m()),_meta:W(m(),te()).optional()}),Np=Ap.extend({text:m()}),hs=m().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Cp=Ap.extend({blob:hs}),Ur=xe(["user","assistant"]),Gt=x({audience:M(Ur).optional(),priority:F().min(0).max(1).optional(),lastModified:Cr.datetime({offset:!0}).optional()}),Op=x({...Ht.shape,...Mr.shape,uri:m(),description:re(m()),mimeType:re(m()),size:re(F()),annotations:Gt.optional(),_meta:re(ve({}))}),Nv=x({...Ht.shape,...Mr.shape,uriTemplate:m(),description:re(m()),mimeType:re(m()),annotations:Gt.optional(),_meta:re(ve({}))}),Cv=qr.extend({method:k("resources/list")}),gs=Br.extend({resources:M(Op)}),Ov=qr.extend({method:k("resources/templates/list")}),ys=Br.extend({resourceTemplates:M(Nv)}),_s=ze.extend({uri:m()}),Dv=_s,jv=ce.extend({method:k("resources/read"),params:Dv}),vs=ue.extend({contents:M(Q([Np,Cp]))}),ws=Ae.extend({method:k("notifications/resources/list_changed"),params:Ie.optional()}),Mv=_s,qv=ce.extend({method:k("resources/subscribe"),params:Mv}),Bv=_s,Lv=ce.extend({method:k("resources/unsubscribe"),params:Bv}),Zv=Ie.extend({uri:m()}),Uv=Ae.extend({method:k("notifications/resources/updated"),params:Zv}),Fv=x({name:m(),description:re(m()),required:re(ae())}),Vv=x({...Ht.shape,...Mr.shape,description:re(m()),arguments:re(M(Fv)),_meta:re(ve({}))}),Kv=qr.extend({method:k("prompts/list")}),bs=Br.extend({prompts:M(Vv)}),Hv=ze.extend({name:m(),arguments:W(m(),m()).optional()}),Gv=ce.extend({method:k("prompts/get"),params:Hv}),$s=x({type:k("text"),text:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),xs=x({type:k("image"),data:hs,mimeType:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),ks=x({type:k("audio"),data:hs,mimeType:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),Wv=x({type:k("tool_use"),name:m(),id:m(),input:W(m(),te()),_meta:W(m(),te()).optional()}),Jv=x({type:k("resource"),resource:Q([Np,Cp]),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),Qv=Op.extend({type:k("resource_link")}),Ss=Q([$s,xs,ks,Qv,Jv]),Yv=x({role:Ur,content:Ss}),Es=ue.extend({description:m().optional(),messages:M(Yv)}),Ps=Ae.extend({method:k("notifications/prompts/list_changed"),params:Ie.optional()}),Xv=x({title:m().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),ew=x({taskSupport:xe(["required","optional","forbidden"]).optional()}),Dp=x({...Ht.shape,...Mr.shape,description:m().optional(),inputSchema:x({type:k("object"),properties:W(m(),se).optional(),required:M(m()).optional()}).catchall(te()),outputSchema:x({type:k("object"),properties:W(m(),se).optional(),required:M(m()).optional()}).catchall(te()).optional(),annotations:Xv.optional(),execution:ew.optional(),_meta:W(m(),te()).optional()}),tw=qr.extend({method:k("tools/list")}),zs=Br.extend({tools:M(Dp)}),dt=ue.extend({content:M(Ss).default([]),structuredContent:W(m(),te()).optional(),isError:ae().optional()}),nA=dt.or(ue.extend({toolResult:te()})),rw=Dr.extend({name:m(),arguments:W(m(),te()).optional()}),nw=ce.extend({method:k("tools/call"),params:rw}),Ts=Ae.extend({method:k("notifications/tools/list_changed"),params:Ie.optional()}),jp=x({autoRefresh:ae().default(!0),debounceMs:F().int().nonnegative().default(300)}),Mp=xe(["debug","info","notice","warning","error","critical","alert","emergency"]),ow=ze.extend({level:Mp}),iw=ce.extend({method:k("logging/setLevel"),params:ow}),sw=Ie.extend({level:Mp,logger:m().optional(),data:te()}),aw=Ae.extend({method:k("notifications/message"),params:sw}),cw=x({name:m().optional()}),uw=x({hints:M(cw).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),lw=x({mode:xe(["auto","required","none"]).optional()}),dw=x({type:k("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:M(Ss).default([]),structuredContent:x({}).loose().optional(),isError:ae().optional(),_meta:W(m(),te()).optional()}),pw=ss("type",[$s,xs,ks]),Wn=ss("type",[$s,xs,ks,Wv,dw]),fw=x({role:Ur,content:Q([Wn,M(Wn)]),_meta:W(m(),te()).optional()}),mw=Dr.extend({messages:M(fw),modelPreferences:uw.optional(),systemPrompt:m().optional(),includeContext:xe(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:M(m()).optional(),metadata:se.optional(),tools:M(Dp).optional(),toolChoice:lw.optional()}),Rs=ce.extend({method:k("sampling/createMessage"),params:mw}),Is=ue.extend({model:m(),stopReason:re(xe(["endTurn","stopSequence","maxTokens"]).or(m())),role:Ur,content:pw}),As=ue.extend({model:m(),stopReason:re(xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:Ur,content:Q([Wn,M(Wn)])}),hw=x({type:k("boolean"),title:m().optional(),description:m().optional(),default:ae().optional()}),gw=x({type:k("string"),title:m().optional(),description:m().optional(),minLength:F().optional(),maxLength:F().optional(),format:xe(["email","uri","date","date-time"]).optional(),default:m().optional()}),yw=x({type:xe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),_w=x({type:k("string"),title:m().optional(),description:m().optional(),enum:M(m()),default:m().optional()}),vw=x({type:k("string"),title:m().optional(),description:m().optional(),oneOf:M(x({const:m(),title:m()})),default:m().optional()}),ww=x({type:k("string"),title:m().optional(),description:m().optional(),enum:M(m()),enumNames:M(m()).optional(),default:m().optional()}),bw=Q([_w,vw]),$w=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:k("string"),enum:M(m())}),default:M(m()).optional()}),xw=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:M(x({const:m(),title:m()}))}),default:M(m()).optional()}),kw=Q([$w,xw]),Sw=Q([ww,bw,kw]),Ew=Q([Sw,hw,gw,yw]),Pw=Dr.extend({mode:k("form").optional(),message:m(),requestedSchema:x({type:k("object"),properties:W(m(),Ew),required:M(m()).optional()})}),zw=Dr.extend({mode:k("url"),message:m(),elicitationId:m(),url:m().url()}),Tw=Q([Pw,zw]),Ns=ce.extend({method:k("elicitation/create"),params:Tw}),Rw=Ie.extend({elicitationId:m()}),Iw=Ae.extend({method:k("notifications/elicitation/complete"),params:Rw}),Cs=ue.extend({action:xe(["accept","decline","cancel"]),content:as(e=>e===null?void 0:e,W(m(),Q([m(),F(),ae(),M(m())])).optional())}),Aw=x({type:k("ref/resource"),uri:m()});var Nw=x({type:k("ref/prompt"),name:m()}),Cw=ze.extend({ref:Q([Nw,Aw]),argument:x({name:m(),value:m()}),context:x({arguments:W(m(),m()).optional()}).optional()}),Ow=ce.extend({method:k("completion/complete"),params:Cw});var Os=ue.extend({completion:ve({values:M(m()).max(100),total:re(F().int()),hasMore:re(ae())})}),Dw=x({uri:m().startsWith("file://"),name:m().optional(),_meta:W(m(),te()).optional()}),jw=ce.extend({method:k("roots/list"),params:ze.optional()}),Mw=ue.extend({roots:M(Dw)}),qw=Ae.extend({method:k("notifications/roots/list_changed"),params:Ie.optional()}),oA=Q([Xn,Sv,Ow,iw,Gv,Kv,Cv,Ov,jv,qv,Lv,nw,tw,to,no,oo,so]),iA=Q([Yn,eo,Pv,qw,Zr]),sA=Q([Et,Is,As,Cs,Mw,ro,io,Pt]),aA=Q([Xn,Rs,Ns,jw,to,no,oo,so]),cA=Q([Yn,eo,aw,Uv,ws,Ts,Ps,Zr,Iw]),uA=Q([Et,ms,Os,Es,bs,gs,ys,vs,dt,zs,ro,io,Pt]),E=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cs(o.elicitations,r)}return new e(t,r,n)}},cs=class extends E{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function pt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Bw=Symbol("Let zodToJsonSchema decide on which parser to use");var ZA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ds(e){let r=Kn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Yd(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function js(e,t){let r=qe(e,t);if(!r.success)throw r.error;return r.data}var Kw=6e4,ao=class{constructor(t){this._options=t,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(Yn,r=>{this._oncancel(r)}),this.setNotificationHandler(eo,r=>{this._onprogress(r)}),this.setRequestHandler(Xn,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(to,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(no,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,p=new E(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new E(I.InvalidParams,`Task not found: ${i}`);if(!pt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(pt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[lt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(oo,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new E(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(so,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(pt(o.status))throw new E(I.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new E(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof E?o:new E(I.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),E.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){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=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),jr(i)||zp(i)?this._onresponse(i):ds(i)?this._onrequest(i,s):Pp(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=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=E.fromError(I.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[lt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=kp(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new E(I.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:t.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let h=f.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),jr(t))n(t);else{let s=new E(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(jr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),jr(t))o(t);else{let s=E.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Pt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new E(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},pt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new E(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[lt]:c}});let h=b=>{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(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let $=b instanceof E?b:new E(I.RequestTimeout,String(b));u($)};this._responseHandlers.set(p,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let $=qe(r,b.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??Kw,_=()=>h(E.fromError(I.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=$=>{let P=this._responseHandlers.get(p);P?P($):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(p),u($)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(p),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ro,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},io,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Ip,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[lt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[lt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[lt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Ds(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=js(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Ds(t);this._notificationHandlers.set(n,o=>{let i=js(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&ds(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new E(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new E(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new E(I.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Zr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new E(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(pt(a.status))throw new E(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=Zr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),pt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function qp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Bp(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];qp(s)&&qp(i)?r[o]={...s,...i}:r[o]=i}return r}var Ah=vi(xc(),1),Nh=vi(Ih(),1);function WS(){let e=new Ah.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Nh.default)(e),e}var Uo=class{constructor(t){this._ajv=t??WS()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Fo=class{constructor(t){this._client=t}async*callToolStream(t,r=dt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof E){yield{type:"error",error:u};return}yield{type:"error",error:new E(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Ch(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Oh(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Vo(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Vo(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Vo(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Vo(r,t)}}function JS(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var Ko=class extends ao{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Uo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ts,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ps,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ws,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Fo(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Bp(this._capabilities,t)}setRequestHandler(t,r){let o=Kn(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=qe(Ns,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=JS(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new E(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new E(I.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let b=qe(Pt,h);if(!b.success){let $=b.error instanceof Error?b.error.message:String(b.error);throw new E(I.InvalidParams,`Invalid task creation result: ${$}`)}return b.data}let g=qe(Cs,h);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new E(I.InvalidParams,`Invalid elicitation result: ${b}`)}let _=g.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Vo(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=qe(Rs,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,p=await Promise.resolve(r(c,l));if(d.task){let _=qe(Pt,p);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new E(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let h=d.tools||d.toolChoice?As:Is,g=qe(h,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new E(I.InvalidParams,`Invalid sampling result: ${_}`)}return g.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:us,capabilities:this._capabilities,clientInfo:this._clientInfo}},ms,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!bp.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Ch(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Oh(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Et,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Os,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Et,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Es,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},bs,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},gs,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ys,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},vs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Et,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Et,r)}async callTool(t,r=dt,n){if(this.isToolTaskRequired(t.name))throw new E(I.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof E?s:new E(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},zs,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=jp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(l,a);this._listChangedDebounceTimers.set(t,p)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Sg=vi(xg(),1);import Bc from"node:process";import{PassThrough as kE}from"node:stream";var Go=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),xE(r)}clear(){this._buffer=void 0}};function xE(e){return Tp.parse(JSON.parse(e))}function kg(e){return JSON.stringify(e)+`
37
- `}var SE=Bc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function EE(){let e={};for(let t of SE){let r=Bc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Wo=class{constructor(t){this._readBuffer=new Go,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new kE)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,Sg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...EE(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Bc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=kg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var PE=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var qt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new Wo({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??zE(),stderr:t.stderr??"pipe"}),n=new Ko({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:RE(r).map(IE),nextCursor:Eg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!Jo(n,["error"])&&CE(n,["ok","success"],!0),target:t,messageId:Ve(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:AE(r).map(NE).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=PE.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:TE(r)},dt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
- `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function zE(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function TE(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function RE(e){if(Array.isArray(e))return e;if(!hr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&hr(r)?[r]:[]}function IE(e){return hr(e)?{id:Ve(e,["id","message_id","messageId"]),cursor:Eg(e,["cursor"]),type:Ve(e,["type","event_type","eventType"]),platform:Ve(e,["platform"]),target:Ve(e,["target"]),sessionKey:Ve(e,["session_key","sessionKey"]),timestamp:Ve(e,["timestamp","created_at","createdAt"]),message:Ve(e,["message","text","content"]),raw:e}:{raw:e}}function AE(e){if(Array.isArray(e))return e;if(!hr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function NE(e){if(!hr(e))return null;let t=Ve(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Ve(e,["platform"]),name:Ve(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Ve(e,t){let r=Jo(e,t);return typeof r=="string"?r:void 0}function CE(e,t,r){let n=Jo(e,t);return typeof n=="boolean"?n:r}function Eg(e,t){let r=Jo(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function Jo(e,t){if(hr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function hr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as $T,writeFile as xT}from"node:fs/promises";import{join as Sy}from"node:path";import{basename as ky}from"node:path";import{createHash as DE,randomUUID as Uc}from"node:crypto";import{spawn as jE}from"node:child_process";import{constants as Lc}from"node:fs";import{readFileSync as ME}from"node:fs";import{mkdir as Ig,open as qE,readFile as BE,rename as UD,rm as bn,stat as FD,writeFile as VD}from"node:fs/promises";import{tmpdir as LE}from"node:os";import{dirname as gr,join as je,resolve as Xo}from"node:path";import{fileURLToPath as ZE}from"node:url";import{createConnection as OE}from"node:net";async function Qo(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=OE(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
35
+ })));`),p.write(`newResult[${xt(b)}] = ${$}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,$)=>w(d,b,$)},o,i=Ut,s=!An.jitless,c=s&&Ei.value,l=t.catchall,u;e._zod.parse=(d,p)=>{u??(u=r.value);let f=d.value;if(!i(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d;let h=[];if(s&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let $=u.shape;for(let P of u.keys){let R=$[P],_e=R._zod.run({value:f[P],issues:[]},p),ze=R._zod.optin==="optional"&&R._zod.optout==="optional";_e instanceof Promise?h.push(_e.then(Zt=>ze?yl(Zt,d,P,f):qn(Zt,d,P))):ze?yl(_e,d,P,f):qn(_e,d,P)}}if(!l)return h.length?Promise.all(h).then(()=>d):d;let g=[],_=u.keySet,w=l._zod,b=w.def.type;for(let $ of Object.keys(f)){if(_.has($))continue;if(b==="never"){g.push($);continue}let P=w.run({value:f[$],issues:[]},p);P instanceof Promise?h.push(P.then(R=>qn(R,d,$))):qn(P,d,$)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:e}),h.length?Promise.all(h).then(()=>d):d}});function _l(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(i=>Me(i,n,Re())))}),t}var Li=y("$ZodUnion",(e,t)=>{G.init(e,t),H(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),H(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),H(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),H(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Er(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>_l(s,r,e,n)):_l(i,r,e,n)}}),rd=y("$ZodDiscriminatedUnion",(e,t)=>{Li.init(e,t);let r=e._zod.parse;H(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=kr(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Ut(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),nd=y("$ZodIntersection",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,l])=>vl(r,c,l)):vl(r,i,s)}});function qi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ft(e)&&Ft(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=qi(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=qi(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function vl(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),kt(e))return e;let n=qi(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var od=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Ft(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?i.push(l.then(u=>{u.issues.length&&r.issues.push(...We(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...We(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Me(l,n,Re())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(l=>{l.issues.length&&r.issues.push(...We(s,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...We(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var id=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=$i(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>Pi.has(typeof n)).map(n=>typeof n=="string"?ut(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),sd=y("$ZodLiteral",(e,t)=>{G.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?ut(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var ad=y("$ZodTransform",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new tt;return r.value=o,r}}),cd=y("$ZodOptional",(e,t)=>{G.init(e,t),e._zod.optin="optional",e._zod.optout="optional",H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),H(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Er(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),ud=y("$ZodNullable",(e,t)=>{G.init(e,t),H(e._zod,"optin",()=>t.innerType._zod.optin),H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Er(r.source)}|null)$`):void 0}),H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),ld=y("$ZodDefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>wl(i,t)):wl(o,t)}});function wl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var dd=y("$ZodPrefault",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),pd=y("$ZodNonOptional",(e,t)=>{G.init(e,t),H(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>bl(i,e)):bl(o,e)}});function bl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var fd=y("$ZodCatch",(e,t)=>{G.init(e,t),e._zod.optin="optional",H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Me(s,n,Re()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Me(i,n,Re()))},input:r.value}),r.issues=[]),r)}});var md=y("$ZodPipe",(e,t)=>{G.init(e,t),H(e._zod,"values",()=>t.in._zod.values),H(e._zod,"optin",()=>t.in._zod.optin),H(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>$l(i,t,n)):$l(o,t,n)}});function $l(e,t,r){return kt(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var hd=y("$ZodReadonly",(e,t)=>{G.init(e,t),H(e._zod,"propValues",()=>t.innerType._zod.propValues),H(e._zod,"values",()=>t.innerType._zod.values),H(e._zod,"optin",()=>t.innerType._zod.optin),H(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(xl):xl(o)}});function xl(e){return e.value=Object.freeze(e.value),e}var gd=y("$ZodCustom",(e,t)=>{fe.init(e,t),G.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>kl(i,r,n,e));kl(o,r,n,e)}});function kl(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Ri(o))}}var h_=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},g_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${h_(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${On(n.values[0])}`:`Invalid option: expected one of ${Nn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Nn(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function yd(){return{localeError:g_()}}var IR=Symbol("ZodOutput"),AR=Symbol("ZodInput"),Zi=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function y_(){return new Zi}var Rr=y_();function _d(e,t){return new e({type:"string",...T(t)})}function vd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...T(t)})}function Ui(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...T(t)})}function wd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...T(t)})}function bd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(t)})}function $d(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(t)})}function xd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(t)})}function kd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...T(t)})}function Sd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...T(t)})}function Ed(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(t)})}function Pd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...T(t)})}function Td(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(t)})}function zd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...T(t)})}function Rd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...T(t)})}function Id(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(t)})}function Ad(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(t)})}function Nd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(t)})}function Cd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(t)})}function Od(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(t)})}function Dd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...T(t)})}function jd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...T(t)})}function Md(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...T(t)})}function qd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...T(t)})}function Bd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(t)})}function Ld(e,t){return new e({type:"string",format:"date",check:"string_format",...T(t)})}function Zd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...T(t)})}function Ud(e,t){return new e({type:"string",format:"duration",check:"string_format",...T(t)})}function Fd(e,t){return new e({type:"number",checks:[],...T(t)})}function Vd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...T(t)})}function Kd(e,t){return new e({type:"boolean",...T(t)})}function Hd(e,t){return new e({type:"null",...T(t)})}function Gd(e){return new e({type:"unknown"})}function Wd(e,t){return new e({type:"never",...T(t)})}function Ln(e,t){return new ji({check:"less_than",...T(t),value:e,inclusive:!1})}function Ir(e,t){return new ji({check:"less_than",...T(t),value:e,inclusive:!0})}function Zn(e,t){return new Mi({check:"greater_than",...T(t),value:e,inclusive:!1})}function Ar(e,t){return new Mi({check:"greater_than",...T(t),value:e,inclusive:!0})}function Un(e,t){return new rl({check:"multiple_of",...T(t),value:e})}function Fn(e,t){return new ol({check:"max_length",...T(t),maximum:e})}function Vt(e,t){return new il({check:"min_length",...T(t),minimum:e})}function Vn(e,t){return new sl({check:"length_equals",...T(t),length:e})}function Fi(e,t){return new al({check:"string_format",format:"regex",...T(t),pattern:e})}function Vi(e){return new cl({check:"string_format",format:"lowercase",...T(e)})}function Ki(e){return new ul({check:"string_format",format:"uppercase",...T(e)})}function Hi(e,t){return new ll({check:"string_format",format:"includes",...T(t),includes:e})}function Gi(e,t){return new dl({check:"string_format",format:"starts_with",...T(t),prefix:e})}function Wi(e,t){return new pl({check:"string_format",format:"ends_with",...T(t),suffix:e})}function St(e){return new fl({check:"overwrite",tx:e})}function Ji(e){return St(t=>t.normalize(e))}function Qi(){return St(e=>e.trim())}function Yi(){return St(e=>e.toLowerCase())}function Xi(){return St(e=>e.toUpperCase())}function Jd(e,t,r){return new e({type:"array",element:t,...T(r)})}function Qd(e,t,r){let n=T(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Yd(e,t,r){return new e({type:"custom",check:"custom",fn:t,...T(r)})}function Kt(e){return!!e._zod}function qe(e,t){return Kt(e)?Tr(e,t):e.safeParse(t)}function Kn(e){if(!e)return;let t;if(Kt(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Xd(e){if(Kt(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._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=e.value;if(n!==void 0)return n}var Cr={};yu(Cr,{ZodISODate:()=>tp,ZodISODateTime:()=>ep,ZodISODuration:()=>np,ZodISOTime:()=>rp,date:()=>ts,datetime:()=>es,duration:()=>ns,time:()=>rs});var ep=y("ZodISODateTime",(e,t)=>{Dl.init(e,t),ee.init(e,t)});function es(e){return Bd(ep,e)}var tp=y("ZodISODate",(e,t)=>{jl.init(e,t),ee.init(e,t)});function ts(e){return Ld(tp,e)}var rp=y("ZodISOTime",(e,t)=>{Ml.init(e,t),ee.init(e,t)});function rs(e){return Zd(rp,e)}var np=y("ZodISODuration",(e,t)=>{ql.init(e,t),ee.init(e,t)});function ns(e){return Ud(np,e)}var op=(e,t)=>{Dn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>xu(e,r)},flatten:{value:r=>$u(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},pI=y("ZodError",op),Or=y("ZodError",op,{Parent:Error});var ip=ku(Or),sp=Su(Or),ap=Ai(Or),cp=Ni(Or);var ne=y("ZodType",(e,t)=>(G.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Ge(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>ip(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>ap(e,r,n),e.parseAsync=async(r,n)=>sp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>cp(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(mv(r,n)),e.superRefine=r=>e.check(hv(r)),e.overwrite=r=>e.check(St(r)),e.optional=()=>re(e),e.nullable=()=>dp(e),e.nullish=()=>re(dp(e)),e.nonoptional=r=>av(e,r),e.array=()=>M(e),e.or=r=>Q([e,r]),e.and=r=>Gn(e,r),e.transform=r=>is(e,yp(r)),e.default=r=>ov(e,r),e.prefault=r=>sv(e,r),e.catch=r=>uv(e,r),e.pipe=r=>is(e,r),e.readonly=()=>pv(e),e.describe=r=>{let n=e.clone();return Rr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Rr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Rr.get(e);let n=e.clone();return Rr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),pp=y("_ZodString",(e,t)=>{Bn.init(e,t),ne.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Fi(...n)),e.includes=(...n)=>e.check(Hi(...n)),e.startsWith=(...n)=>e.check(Gi(...n)),e.endsWith=(...n)=>e.check(Wi(...n)),e.min=(...n)=>e.check(Vt(...n)),e.max=(...n)=>e.check(Fn(...n)),e.length=(...n)=>e.check(Vn(...n)),e.nonempty=(...n)=>e.check(Vt(1,...n)),e.lowercase=n=>e.check(Vi(n)),e.uppercase=n=>e.check(Ki(n)),e.trim=()=>e.check(Qi()),e.normalize=(...n)=>e.check(Ji(...n)),e.toLowerCase=()=>e.check(Yi()),e.toUpperCase=()=>e.check(Xi())}),E_=y("ZodString",(e,t)=>{Bn.init(e,t),pp.init(e,t),e.email=r=>e.check(vd(P_,r)),e.url=r=>e.check(kd(T_,r)),e.jwt=r=>e.check(qd(U_,r)),e.emoji=r=>e.check(Sd(z_,r)),e.guid=r=>e.check(Ui(up,r)),e.uuid=r=>e.check(wd(Hn,r)),e.uuidv4=r=>e.check(bd(Hn,r)),e.uuidv6=r=>e.check($d(Hn,r)),e.uuidv7=r=>e.check(xd(Hn,r)),e.nanoid=r=>e.check(Ed(R_,r)),e.guid=r=>e.check(Ui(up,r)),e.cuid=r=>e.check(Pd(I_,r)),e.cuid2=r=>e.check(Td(A_,r)),e.ulid=r=>e.check(zd(N_,r)),e.base64=r=>e.check(Dd(B_,r)),e.base64url=r=>e.check(jd(L_,r)),e.xid=r=>e.check(Rd(C_,r)),e.ksuid=r=>e.check(Id(O_,r)),e.ipv4=r=>e.check(Ad(D_,r)),e.ipv6=r=>e.check(Nd(j_,r)),e.cidrv4=r=>e.check(Cd(M_,r)),e.cidrv6=r=>e.check(Od(q_,r)),e.e164=r=>e.check(Md(Z_,r)),e.datetime=r=>e.check(es(r)),e.date=r=>e.check(ts(r)),e.time=r=>e.check(rs(r)),e.duration=r=>e.check(ns(r))});function m(e){return _d(E_,e)}var ee=y("ZodStringFormat",(e,t)=>{J.init(e,t),pp.init(e,t)}),P_=y("ZodEmail",(e,t)=>{Pl.init(e,t),ee.init(e,t)});var up=y("ZodGUID",(e,t)=>{Sl.init(e,t),ee.init(e,t)});var Hn=y("ZodUUID",(e,t)=>{El.init(e,t),ee.init(e,t)});var T_=y("ZodURL",(e,t)=>{Tl.init(e,t),ee.init(e,t)});var z_=y("ZodEmoji",(e,t)=>{zl.init(e,t),ee.init(e,t)});var R_=y("ZodNanoID",(e,t)=>{Rl.init(e,t),ee.init(e,t)});var I_=y("ZodCUID",(e,t)=>{Il.init(e,t),ee.init(e,t)});var A_=y("ZodCUID2",(e,t)=>{Al.init(e,t),ee.init(e,t)});var N_=y("ZodULID",(e,t)=>{Nl.init(e,t),ee.init(e,t)});var C_=y("ZodXID",(e,t)=>{Cl.init(e,t),ee.init(e,t)});var O_=y("ZodKSUID",(e,t)=>{Ol.init(e,t),ee.init(e,t)});var D_=y("ZodIPv4",(e,t)=>{Bl.init(e,t),ee.init(e,t)});var j_=y("ZodIPv6",(e,t)=>{Ll.init(e,t),ee.init(e,t)});var M_=y("ZodCIDRv4",(e,t)=>{Zl.init(e,t),ee.init(e,t)});var q_=y("ZodCIDRv6",(e,t)=>{Ul.init(e,t),ee.init(e,t)});var B_=y("ZodBase64",(e,t)=>{Vl.init(e,t),ee.init(e,t)});var L_=y("ZodBase64URL",(e,t)=>{Kl.init(e,t),ee.init(e,t)});var Z_=y("ZodE164",(e,t)=>{Hl.init(e,t),ee.init(e,t)});var U_=y("ZodJWT",(e,t)=>{Gl.init(e,t),ee.init(e,t)});var fp=y("ZodNumber",(e,t)=>{Bi.init(e,t),ne.init(e,t),e.gt=(n,o)=>e.check(Zn(n,o)),e.gte=(n,o)=>e.check(Ar(n,o)),e.min=(n,o)=>e.check(Ar(n,o)),e.lt=(n,o)=>e.check(Ln(n,o)),e.lte=(n,o)=>e.check(Ir(n,o)),e.max=(n,o)=>e.check(Ir(n,o)),e.int=n=>e.check(lp(n)),e.safe=n=>e.check(lp(n)),e.positive=n=>e.check(Zn(0,n)),e.nonnegative=n=>e.check(Ar(0,n)),e.negative=n=>e.check(Ln(0,n)),e.nonpositive=n=>e.check(Ir(0,n)),e.multipleOf=(n,o)=>e.check(Un(n,o)),e.step=(n,o)=>e.check(Un(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function F(e){return Fd(fp,e)}var F_=y("ZodNumberFormat",(e,t)=>{Wl.init(e,t),fp.init(e,t)});function lp(e){return Vd(F_,e)}var V_=y("ZodBoolean",(e,t)=>{Jl.init(e,t),ne.init(e,t)});function ae(e){return Kd(V_,e)}var K_=y("ZodNull",(e,t)=>{Ql.init(e,t),ne.init(e,t)});function mp(e){return Hd(K_,e)}var H_=y("ZodUnknown",(e,t)=>{Yl.init(e,t),ne.init(e,t)});function te(){return Gd(H_)}var G_=y("ZodNever",(e,t)=>{Xl.init(e,t),ne.init(e,t)});function W_(e){return Wd(G_,e)}var J_=y("ZodArray",(e,t)=>{ed.init(e,t),ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Vt(r,n)),e.nonempty=r=>e.check(Vt(1,r)),e.max=(r,n)=>e.check(Fn(r,n)),e.length=(r,n)=>e.check(Vn(r,n)),e.unwrap=()=>e.element});function M(e,t){return Jd(J_,e,t)}var hp=y("ZodObject",(e,t)=>{td.init(e,t),ne.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>xe(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:te()}),e.loose=()=>e.clone({...e._zod.def,catchall:te()}),e.strict=()=>e.clone({...e._zod.def,catchall:W_()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>U.extend(e,r),e.merge=r=>U.merge(e,r),e.pick=r=>U.pick(e,r),e.omit=r=>U.omit(e,r),e.partial=(...r)=>U.partial(_p,e,r[0]),e.required=(...r)=>U.required(vp,e,r[0])});function x(e,t){let r={type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},...U.normalizeParams(t)};return new hp(r)}function ve(e,t){return new hp({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:te(),...U.normalizeParams(t)})}var gp=y("ZodUnion",(e,t)=>{Li.init(e,t),ne.init(e,t),e.options=t.options});function Q(e,t){return new gp({type:"union",options:e,...U.normalizeParams(t)})}var Q_=y("ZodDiscriminatedUnion",(e,t)=>{gp.init(e,t),rd.init(e,t)});function ss(e,t,r){return new Q_({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var Y_=y("ZodIntersection",(e,t)=>{nd.init(e,t),ne.init(e,t)});function Gn(e,t){return new Y_({type:"intersection",left:e,right:t})}var X_=y("ZodRecord",(e,t)=>{od.init(e,t),ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function W(e,t,r){return new X_({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var os=y("ZodEnum",(e,t)=>{id.init(e,t),ne.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new os({...t,checks:[],...U.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new os({...t,checks:[],...U.normalizeParams(o),entries:i})}});function xe(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new os({type:"enum",entries:r,...U.normalizeParams(t)})}var ev=y("ZodLiteral",(e,t)=>{sd.init(e,t),ne.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function k(e,t){return new ev({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var tv=y("ZodTransform",(e,t)=>{ad.init(e,t),ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(U.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(U.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function yp(e){return new tv({type:"transform",transform:e})}var _p=y("ZodOptional",(e,t)=>{cd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function re(e){return new _p({type:"optional",innerType:e})}var rv=y("ZodNullable",(e,t)=>{ud.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dp(e){return new rv({type:"nullable",innerType:e})}var nv=y("ZodDefault",(e,t)=>{ld.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ov(e,t){return new nv({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var iv=y("ZodPrefault",(e,t)=>{dd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function sv(e,t){return new iv({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var vp=y("ZodNonOptional",(e,t)=>{pd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function av(e,t){return new vp({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var cv=y("ZodCatch",(e,t)=>{fd.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function uv(e,t){return new cv({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var lv=y("ZodPipe",(e,t)=>{md.init(e,t),ne.init(e,t),e.in=t.in,e.out=t.out});function is(e,t){return new lv({type:"pipe",in:e,out:t})}var dv=y("ZodReadonly",(e,t)=>{hd.init(e,t),ne.init(e,t)});function pv(e){return new dv({type:"readonly",innerType:e})}var wp=y("ZodCustom",(e,t)=>{gd.init(e,t),ne.init(e,t)});function fv(e){let t=new fe({check:"custom"});return t._zod.check=e,t}function bp(e,t){return Qd(wp,e??(()=>!0),t)}function mv(e,t={}){return Yd(wp,e,t)}function hv(e){let t=fv(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(U.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(U.issue(o))}},e(r.value,r)));return t}function as(e,t){return is(yp(e),t)}Re(yd());var us="2025-11-25";var $p=[us,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lt="io.modelcontextprotocol/related-task",Jn="2.0",se=bp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),xp=Q([m(),F().int()]),kp=m(),iA=ve({ttl:F().optional(),pollInterval:F().optional()}),gv=x({ttl:F().optional()}),yv=x({taskId:m()}),ls=ve({progressToken:xp.optional(),[lt]:yv.optional()}),Te=x({_meta:ls.optional()}),Dr=Te.extend({task:gv.optional()}),Sp=e=>Dr.safeParse(e).success,ce=x({method:m(),params:Te.loose().optional()}),Ie=x({_meta:ls.optional()}),Ae=x({method:m(),params:Ie.loose().optional()}),ue=ve({_meta:ls.optional()}),Qn=Q([m(),F().int()]),Ep=x({jsonrpc:k(Jn),id:Qn,...ce.shape}).strict(),ds=e=>Ep.safeParse(e).success,Pp=x({jsonrpc:k(Jn),...Ae.shape}).strict(),Tp=e=>Pp.safeParse(e).success,ps=x({jsonrpc:k(Jn),id:Qn,result:ue}).strict(),jr=e=>ps.safeParse(e).success;var I;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(I||(I={}));var fs=x({jsonrpc:k(Jn),id:Qn.optional(),error:x({code:F().int(),message:m(),data:te().optional()})}).strict();var zp=e=>fs.safeParse(e).success;var Rp=Q([Ep,Pp,ps,fs]),sA=Q([ps,fs]),Et=ue.strict(),_v=Ie.extend({requestId:Qn.optional(),reason:m().optional()}),Yn=Ae.extend({method:k("notifications/cancelled"),params:_v}),vv=x({src:m(),mimeType:m().optional(),sizes:M(m()).optional(),theme:xe(["light","dark"]).optional()}),Mr=x({icons:M(vv).optional()}),Ht=x({name:m(),title:m().optional()}),Ip=Ht.extend({...Ht.shape,...Mr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),wv=Gn(x({applyDefaults:ae().optional()}),W(m(),te())),bv=as(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Gn(x({form:wv.optional(),url:se.optional()}),W(m(),te()).optional())),$v=ve({list:se.optional(),cancel:se.optional(),requests:ve({sampling:ve({createMessage:se.optional()}).optional(),elicitation:ve({create:se.optional()}).optional()}).optional()}),xv=ve({list:se.optional(),cancel:se.optional(),requests:ve({tools:ve({call:se.optional()}).optional()}).optional()}),kv=x({experimental:W(m(),se).optional(),sampling:x({context:se.optional(),tools:se.optional()}).optional(),elicitation:bv.optional(),roots:x({listChanged:ae().optional()}).optional(),tasks:$v.optional(),extensions:W(m(),se).optional()}),Sv=Te.extend({protocolVersion:m(),capabilities:kv,clientInfo:Ip}),Ev=ce.extend({method:k("initialize"),params:Sv});var Pv=x({experimental:W(m(),se).optional(),logging:se.optional(),completions:se.optional(),prompts:x({listChanged:ae().optional()}).optional(),resources:x({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:x({listChanged:ae().optional()}).optional(),tasks:xv.optional(),extensions:W(m(),se).optional()}),ms=ue.extend({protocolVersion:m(),capabilities:Pv,serverInfo:Ip,instructions:m().optional()}),Tv=Ae.extend({method:k("notifications/initialized"),params:Ie.optional()});var Xn=ce.extend({method:k("ping"),params:Te.optional()}),zv=x({progress:F(),total:re(F()),message:re(m())}),Rv=x({...Ie.shape,...zv.shape,progressToken:xp}),eo=Ae.extend({method:k("notifications/progress"),params:Rv}),Iv=Te.extend({cursor:kp.optional()}),qr=ce.extend({params:Iv.optional()}),Br=ue.extend({nextCursor:kp.optional()}),Av=xe(["working","input_required","completed","failed","cancelled"]),Lr=x({taskId:m(),status:Av,ttl:Q([F(),mp()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:re(F()),statusMessage:re(m())}),Pt=ue.extend({task:Lr}),Nv=Ie.merge(Lr),Zr=Ae.extend({method:k("notifications/tasks/status"),params:Nv}),to=ce.extend({method:k("tasks/get"),params:Te.extend({taskId:m()})}),ro=ue.merge(Lr),no=ce.extend({method:k("tasks/result"),params:Te.extend({taskId:m()})}),aA=ue.loose(),oo=qr.extend({method:k("tasks/list")}),io=Br.extend({tasks:M(Lr)}),so=ce.extend({method:k("tasks/cancel"),params:Te.extend({taskId:m()})}),Ap=ue.merge(Lr),Np=x({uri:m(),mimeType:re(m()),_meta:W(m(),te()).optional()}),Cp=Np.extend({text:m()}),hs=m().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Op=Np.extend({blob:hs}),Ur=xe(["user","assistant"]),Gt=x({audience:M(Ur).optional(),priority:F().min(0).max(1).optional(),lastModified:Cr.datetime({offset:!0}).optional()}),Dp=x({...Ht.shape,...Mr.shape,uri:m(),description:re(m()),mimeType:re(m()),size:re(F()),annotations:Gt.optional(),_meta:re(ve({}))}),Cv=x({...Ht.shape,...Mr.shape,uriTemplate:m(),description:re(m()),mimeType:re(m()),annotations:Gt.optional(),_meta:re(ve({}))}),Ov=qr.extend({method:k("resources/list")}),gs=Br.extend({resources:M(Dp)}),Dv=qr.extend({method:k("resources/templates/list")}),ys=Br.extend({resourceTemplates:M(Cv)}),_s=Te.extend({uri:m()}),jv=_s,Mv=ce.extend({method:k("resources/read"),params:jv}),vs=ue.extend({contents:M(Q([Cp,Op]))}),ws=Ae.extend({method:k("notifications/resources/list_changed"),params:Ie.optional()}),qv=_s,Bv=ce.extend({method:k("resources/subscribe"),params:qv}),Lv=_s,Zv=ce.extend({method:k("resources/unsubscribe"),params:Lv}),Uv=Ie.extend({uri:m()}),Fv=Ae.extend({method:k("notifications/resources/updated"),params:Uv}),Vv=x({name:m(),description:re(m()),required:re(ae())}),Kv=x({...Ht.shape,...Mr.shape,description:re(m()),arguments:re(M(Vv)),_meta:re(ve({}))}),Hv=qr.extend({method:k("prompts/list")}),bs=Br.extend({prompts:M(Kv)}),Gv=Te.extend({name:m(),arguments:W(m(),m()).optional()}),Wv=ce.extend({method:k("prompts/get"),params:Gv}),$s=x({type:k("text"),text:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),xs=x({type:k("image"),data:hs,mimeType:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),ks=x({type:k("audio"),data:hs,mimeType:m(),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),Jv=x({type:k("tool_use"),name:m(),id:m(),input:W(m(),te()),_meta:W(m(),te()).optional()}),Qv=x({type:k("resource"),resource:Q([Cp,Op]),annotations:Gt.optional(),_meta:W(m(),te()).optional()}),Yv=Dp.extend({type:k("resource_link")}),Ss=Q([$s,xs,ks,Yv,Qv]),Xv=x({role:Ur,content:Ss}),Es=ue.extend({description:m().optional(),messages:M(Xv)}),Ps=Ae.extend({method:k("notifications/prompts/list_changed"),params:Ie.optional()}),ew=x({title:m().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),tw=x({taskSupport:xe(["required","optional","forbidden"]).optional()}),jp=x({...Ht.shape,...Mr.shape,description:m().optional(),inputSchema:x({type:k("object"),properties:W(m(),se).optional(),required:M(m()).optional()}).catchall(te()),outputSchema:x({type:k("object"),properties:W(m(),se).optional(),required:M(m()).optional()}).catchall(te()).optional(),annotations:ew.optional(),execution:tw.optional(),_meta:W(m(),te()).optional()}),rw=qr.extend({method:k("tools/list")}),Ts=Br.extend({tools:M(jp)}),dt=ue.extend({content:M(Ss).default([]),structuredContent:W(m(),te()).optional(),isError:ae().optional()}),cA=dt.or(ue.extend({toolResult:te()})),nw=Dr.extend({name:m(),arguments:W(m(),te()).optional()}),ow=ce.extend({method:k("tools/call"),params:nw}),zs=Ae.extend({method:k("notifications/tools/list_changed"),params:Ie.optional()}),Mp=x({autoRefresh:ae().default(!0),debounceMs:F().int().nonnegative().default(300)}),qp=xe(["debug","info","notice","warning","error","critical","alert","emergency"]),iw=Te.extend({level:qp}),sw=ce.extend({method:k("logging/setLevel"),params:iw}),aw=Ie.extend({level:qp,logger:m().optional(),data:te()}),cw=Ae.extend({method:k("notifications/message"),params:aw}),uw=x({name:m().optional()}),lw=x({hints:M(uw).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),dw=x({mode:xe(["auto","required","none"]).optional()}),pw=x({type:k("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:M(Ss).default([]),structuredContent:x({}).loose().optional(),isError:ae().optional(),_meta:W(m(),te()).optional()}),fw=ss("type",[$s,xs,ks]),Wn=ss("type",[$s,xs,ks,Jv,pw]),mw=x({role:Ur,content:Q([Wn,M(Wn)]),_meta:W(m(),te()).optional()}),hw=Dr.extend({messages:M(mw),modelPreferences:lw.optional(),systemPrompt:m().optional(),includeContext:xe(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:M(m()).optional(),metadata:se.optional(),tools:M(jp).optional(),toolChoice:dw.optional()}),Rs=ce.extend({method:k("sampling/createMessage"),params:hw}),Is=ue.extend({model:m(),stopReason:re(xe(["endTurn","stopSequence","maxTokens"]).or(m())),role:Ur,content:fw}),As=ue.extend({model:m(),stopReason:re(xe(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:Ur,content:Q([Wn,M(Wn)])}),gw=x({type:k("boolean"),title:m().optional(),description:m().optional(),default:ae().optional()}),yw=x({type:k("string"),title:m().optional(),description:m().optional(),minLength:F().optional(),maxLength:F().optional(),format:xe(["email","uri","date","date-time"]).optional(),default:m().optional()}),_w=x({type:xe(["number","integer"]),title:m().optional(),description:m().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),vw=x({type:k("string"),title:m().optional(),description:m().optional(),enum:M(m()),default:m().optional()}),ww=x({type:k("string"),title:m().optional(),description:m().optional(),oneOf:M(x({const:m(),title:m()})),default:m().optional()}),bw=x({type:k("string"),title:m().optional(),description:m().optional(),enum:M(m()),enumNames:M(m()).optional(),default:m().optional()}),$w=Q([vw,ww]),xw=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:k("string"),enum:M(m())}),default:M(m()).optional()}),kw=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:M(x({const:m(),title:m()}))}),default:M(m()).optional()}),Sw=Q([xw,kw]),Ew=Q([bw,$w,Sw]),Pw=Q([Ew,gw,yw,_w]),Tw=Dr.extend({mode:k("form").optional(),message:m(),requestedSchema:x({type:k("object"),properties:W(m(),Pw),required:M(m()).optional()})}),zw=Dr.extend({mode:k("url"),message:m(),elicitationId:m(),url:m().url()}),Rw=Q([Tw,zw]),Ns=ce.extend({method:k("elicitation/create"),params:Rw}),Iw=Ie.extend({elicitationId:m()}),Aw=Ae.extend({method:k("notifications/elicitation/complete"),params:Iw}),Cs=ue.extend({action:xe(["accept","decline","cancel"]),content:as(e=>e===null?void 0:e,W(m(),Q([m(),F(),ae(),M(m())])).optional())}),Nw=x({type:k("ref/resource"),uri:m()});var Cw=x({type:k("ref/prompt"),name:m()}),Ow=Te.extend({ref:Q([Cw,Nw]),argument:x({name:m(),value:m()}),context:x({arguments:W(m(),m()).optional()}).optional()}),Dw=ce.extend({method:k("completion/complete"),params:Ow});var Os=ue.extend({completion:ve({values:M(m()).max(100),total:re(F().int()),hasMore:re(ae())})}),jw=x({uri:m().startsWith("file://"),name:m().optional(),_meta:W(m(),te()).optional()}),Mw=ce.extend({method:k("roots/list"),params:Te.optional()}),qw=ue.extend({roots:M(jw)}),Bw=Ae.extend({method:k("notifications/roots/list_changed"),params:Ie.optional()}),uA=Q([Xn,Ev,Dw,sw,Wv,Hv,Ov,Dv,Mv,Bv,Zv,ow,rw,to,no,oo,so]),lA=Q([Yn,eo,Tv,Bw,Zr]),dA=Q([Et,Is,As,Cs,qw,ro,io,Pt]),pA=Q([Xn,Rs,Ns,Mw,to,no,oo,so]),fA=Q([Yn,eo,cw,Fv,ws,zs,Ps,Zr,Aw]),mA=Q([Et,ms,Os,Es,bs,gs,ys,vs,dt,Ts,ro,io,Pt]),E=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cs(o.elicitations,r)}return new e(t,r,n)}},cs=class extends E{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function pt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Lw=Symbol("Let zodToJsonSchema decide on which parser to use");var HA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ds(e){let r=Kn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Xd(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function js(e,t){let r=qe(e,t);if(!r.success)throw r.error;return r.data}var Hw=6e4,ao=class{constructor(t){this._options=t,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(Yn,r=>{this._oncancel(r)}),this.setNotificationHandler(eo,r=>{this._onprogress(r)}),this.setRequestHandler(Xn,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(to,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(no,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,p=new E(d.error.code,d.error.message,d.error.data);u(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new E(I.InvalidParams,`Task not found: ${i}`);if(!pt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(pt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[lt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(oo,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new E(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(so,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new E(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(pt(o.status))throw new E(I.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new E(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof E?o:new E(I.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),E.fromError(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){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=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),jr(i)||zp(i)?this._onresponse(i):ds(i)?this._onrequest(i,s):Tp(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=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=E.fromError(I.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[lt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:I.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Sp(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(s.signal.aborted)throw new E(I.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:t.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let h=f.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:I.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),jr(t))n(t);else{let s=new E(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(jr(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),jr(t))o(t);else{let s=E.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Pt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new E(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},pt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new E(I.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(I.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof E?s:new E(I.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[lt]:c}});let h=b=>{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(b)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let $=b instanceof E?b:new E(I.RequestTimeout,String(b));u($)};this._responseHandlers.set(p,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let $=qe(r,b.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??Hw,_=()=>h(E.fromError(I.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=$=>{let P=this._responseHandlers.get(p);P?P($):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(p),u($)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(p),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ro,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},io,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Ap,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[lt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[lt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[lt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Ds(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=js(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Ds(t);this._notificationHandlers.set(n,o=>{let i=js(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&ds(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new E(I.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new E(I.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new E(I.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new E(I.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Zr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new E(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(pt(a.status))throw new E(I.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=Zr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),pt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Bp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lp(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];Bp(s)&&Bp(i)?r[o]={...s,...i}:r[o]=i}return r}var Nh=vi(xc(),1),Ch=vi(Ah(),1);function JS(){let e=new Nh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ch.default)(e),e}var Uo=class{constructor(t){this._ajv=t??JS()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Fo=class{constructor(t){this._client=t}async*callToolStream(t,r=dt,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:t},r,i),a=o.getToolOutputValidator(t.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof E){yield{type:"error",error:u};return}yield{type:"error",error:new E(I.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Oh(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Dh(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Vo(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Vo(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Vo(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Vo(r,t)}}function QS(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var Ko=class extends ao{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Uo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",zs,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ps,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ws,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Fo(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Lp(this._capabilities,t)}setRequestHandler(t,r){let o=Kn(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,l)=>{let u=qe(Ns,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=QS(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new E(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new E(I.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let b=qe(Pt,h);if(!b.success){let $=b.error instanceof Error?b.error.message:String(b.error);throw new E(I.InvalidParams,`Invalid task creation result: ${$}`)}return b.data}let g=qe(Cs,h);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new E(I.InvalidParams,`Invalid elicitation result: ${b}`)}let _=g.data,w=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Vo(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=qe(Rs,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new E(I.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,p=await Promise.resolve(r(c,l));if(d.task){let _=qe(Pt,p);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new E(I.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let h=d.tools||d.toolChoice?As:Is,g=qe(h,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new E(I.InvalidParams,`Invalid sampling result: ${_}`)}return g.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:us,capabilities:this._capabilities,clientInfo:this._clientInfo}},ms,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!$p.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Oh(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Dh(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Et,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Os,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Et,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Es,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},bs,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},gs,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ys,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},vs,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Et,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Et,r)}async callTool(t,r=dt,n){if(this.isToolTaskRequired(t.name))throw new E(I.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!o.structuredContent&&!o.isError)throw new E(I.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new E(I.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof E?s:new E(I.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},Ts,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let i=Mp.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,l=async()=>{if(!s){c(null,null);return}try{let d=await o();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(l,a);this._listChangedDebounceTimers.set(t,p)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Eg=vi(kg(),1);import Bc from"node:process";import{PassThrough as SE}from"node:stream";var Go=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
36
+ `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),kE(r)}clear(){this._buffer=void 0}};function kE(e){return Rp.parse(JSON.parse(e))}function Sg(e){return JSON.stringify(e)+`
37
+ `}var EE=Bc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function PE(){let e={};for(let t of EE){let r=Bc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Wo=class{constructor(t){this._readBuffer=new Go,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new SE)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,Eg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...PE(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Bc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=Sg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var TE=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var qt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new Wo({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??zE(),stderr:t.stderr??"pipe"}),n=new Ko({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:IE(r).map(AE),nextCursor:Pg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!Jo(n,["error"])&&OE(n,["ok","success"],!0),target:t,messageId:Ve(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:NE(r).map(CE).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=TE.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:RE(r)},dt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
38
+ `).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function zE(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function RE(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function IE(e){if(Array.isArray(e))return e;if(!hr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&hr(r)?[r]:[]}function AE(e){return hr(e)?{id:Ve(e,["id","message_id","messageId"]),cursor:Pg(e,["cursor"]),type:Ve(e,["type","event_type","eventType"]),platform:Ve(e,["platform"]),target:Ve(e,["target"]),sessionKey:Ve(e,["session_key","sessionKey"]),timestamp:Ve(e,["timestamp","created_at","createdAt"]),message:Ve(e,["message","text","content"]),raw:e}:{raw:e}}function NE(e){if(Array.isArray(e))return e;if(!hr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function CE(e){if(!hr(e))return null;let t=Ve(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Ve(e,["platform"]),name:Ve(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Ve(e,t){let r=Jo(e,t);return typeof r=="string"?r:void 0}function OE(e,t,r){let n=Jo(e,t);return typeof n=="boolean"?n:r}function Pg(e,t){let r=Jo(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function Jo(e,t){if(hr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function hr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as Pz,writeFile as Tz}from"node:fs/promises";import{join as Ey}from"node:path";import{basename as Sy}from"node:path";import{createHash as jE,randomUUID as Fc}from"node:crypto";import{spawn as ME}from"node:child_process";import{constants as Lc}from"node:fs";import{readFileSync as qE}from"node:fs";import{mkdir as Ag,open as BE,readFile as LE,rename as GD,rm as bn,stat as WD,writeFile as JD}from"node:fs/promises";import{tmpdir as ZE}from"node:os";import{dirname as gr,join as je,resolve as Xo}from"node:path";import{fileURLToPath as UE}from"node:url";import{createConnection as DE}from"node:net";async function Qo(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=DE(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
39
39
  `)}),i.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
40
- `);if(d<0)return;let p=a.slice(0,d);l(()=>{try{n(JSON.parse(p))}catch(f){o(f)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var UE=108,FE=1;function ei(e){let t=eP(e)??Xo(e),r=XE(t);return{rootDir:t,socketPath:je(r,"rsp.sock"),pidPath:je(r,"rsp.pid"),lockPath:je(r,"rsp.lock"),wakeLockPath:je(t,".red","tmp","rsp.wake.lock"),summaryPath:je(t,".red","tmp","rsp-status-summary.json"),registryPath:je(t,".red","tmp","rsp-resident.pid.json")}}var Yo=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await VE(this.paths,this.config);let r=await Qo(this.paths,{...t,id:Uc()});if(!r.ok)throw new Error(r.error);return r.value}};async function VE(e,t){if(await Ig(gr(e.socketPath),{recursive:!0,mode:448}),await Tg(e.socketPath,t))return;await zg(e,t);let r=await GE(e.lockPath);if(r)try{if(await Tg(e.socketPath,t))return;await zg(e,t),await HE(e.socketPath);let n=WE(e,t);await Pg(e.socketPath,n);return}finally{await r.close(),await bn(e.lockPath,{force:!0})}await Pg(e.socketPath)}async function xn(e,t=200){try{return await Ag(e,t)!=null}catch{return!1}}async function Ag(e,t=200){let r=await Qo({socketPath:e,timeoutMs:t},{id:Uc(),op:"ping"});return r.ok?Cg(r.value)?{version:oP(r.value.version)}:{}:null}async function KE(e){try{let t=JSON.parse(await BE(e,"utf8"));return iP(t)?t:null}catch{return null}}async function Pg(e,t){let r=Date.now()+5e3,n;for(;Date.now()<r;){if(await xn(e))return;if(t&&t.exitCode!=null)throw new Error(`resident rsp server exited before ready (${t.exitCode})`);await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error("resident rsp server did not start")}async function HE(e){await bn(e,{force:!0})}async function GE(e){await Ig(gr(e),{recursive:!0,mode:448});try{return await qE(e,Lc.O_CREAT|Lc.O_EXCL|Lc.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function WE(e,t){let[r,n]=YE(t),o=jE(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return o.unref(),o}async function zg(e,t){try{let r=await KE(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!$n(r.pid)){await bn(e.registryPath,{force:!0});return}if(await xn(r.socket_path,100))return;if(Ng(t.clientVersion,r.resident_version)&&(await QE(r.pid,1500),!$n(r.pid))){await bn(e.registryPath,{force:!0});return}await JE(r.pid),await bn(e.registryPath,{force:!0})}catch{}}function $n(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function JE(e){if(!$n(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!$n(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function QE(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!$n(e))return;await new Promise(n=>setTimeout(n,50))}}function YE(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?Xo(process.argv[1]):ZE(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function XE(e){let t=DE("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=je(r,"red-skills",t);if(je(o,"rsp.sock").length<UE)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return je(LE(),`red-skills-${n}`,t)}function eP(e){let t=Xo(e);for(let r=0;r<32;r++){try{let o=Zc(je(t,".git"));if(o!=null)return tP(t,o)??t;if(Zc(je(t,".git","HEAD"))!=null||Zc(je(t,".red","config.yaml"))!=null)return t}catch{}let n=gr(t);if(n===t)return null;t=n}return null}function tP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Xo(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?gr(gr(gr(n))):null}function Zc(e){try{return ME(e,"utf8")}catch{return null}}async function Tg(e,t){let r=await Ag(e).catch(()=>null);return r?Ng(t.clientVersion,r.version)?(await rP(e,t.clientVersion),await sP(e),!1):!0:!1}async function rP(e,t){try{await Qo({socketPath:e,timeoutMs:200},{id:Uc(),op:"handover",clientVersion:t})}catch{}}function Ng(e,t){return!e||!t?!1:nP(e,t)>0}function nP(e,t){let r=Rg(e),n=Rg(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function Rg(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function Cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oP(e){return typeof e=="string"&&e.length>0?e:void 0}function iP(e){return Cg(e)&&e.version===FE&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function sP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await xn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as aP}from"node:child_process";var Vc=["supports","contradicts","related_to"];function Kc(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function Hc(e){return typeof e=="string"&&Vc.includes(e)}function yr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Og(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
41
- `)}function cP(e){return{deriveConnections(t){return lP(e,t)}}}function Dg(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return cP({command:t,args:dP(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:pP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function uP(e){let t=JSON.parse(fP(e));return(Array.isArray(t)?t:Fc(t)&&Array.isArray(t.connections)?t.connections:[]).filter(mP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Fc(n.metadata)?n.metadata:void 0}))}async function lP(e,t){let r=aP(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return uP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function dP(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function pP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function fP(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function mP(e){return Fc(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Hc(e.kind)}function Fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as ti}from"node:fs";import{mkdir as hP,readFile as Gc,writeFile as gP}from"node:fs/promises";import{dirname as Wc,isAbsolute as yP,join as _r,resolve as bt}from"node:path";var ri="file://./.red/brain/brain.rdb",_P="RED_BRAIN_ROOT",vP="brain.root";async function wP(e=process.cwd(),t={}){let n=(t.env??process.env)[_P];if(n)return bt(e,n);let o=await bP(e);if(o)return o;let i=bt(e),s=null;for(;;){let a=_r(i,".red");if(ti(a)&&(s??=i,ti(_r(a,"brain"))||ti(_r(a,vP))))return i;let c=Wc(i);if(c===i)return s??bt(e);i=c}}async function bP(e){let t=bt(e);for(;;){let r=_r(t,".red","config.yaml");try{let o=await Gc(r,"utf8"),i=$P(o);if(i)return bt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Wc(t);if(n===t)return null;t=n}}function $P(e){let t=xP(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function xP(e){let t={},r=[],n=[];for(let o of e.split(`
42
- `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let p=i.indexOf("#");p>=0&&(i=i.slice(0,p))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function jg(e){return _r(bt(e),".red","brain","config.yaml")}function kP(e){return _r(bt(e),".env")}async function SP(e){let t=jg(e);return ti(t)||(await hP(Wc(t),{recursive:!0}),await gP(t,`connection_string: ${ri}
43
- `,"utf8")),t}async function EP(e){let t=jg(e);try{let r=await Gc(t,"utf8");return PP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function PP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:ri};let r=t.slice(18).trim();return{connection_string:Mg(r)||ri}}function Mg(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function qg(e=process.cwd()){let t=await wP(e),r=await SP(t),n=await EP(t)??{connection_string:ri},o=await zP(t),i=n.connection_string,s=TP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:RP(t,s)}}async function zP(e){let t={...process.env};try{let r=await Gc(kP(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=Mg(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function TP(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function RP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return yP(r)?t:`file://${bt(e,r)}`}import{resolve as IP}from"node:path";var AP=".red/tmp/red-skills.rdb",NP=7,CP=64*1024*1024;function Lg(e){return e.connectionString.startsWith("file://")?e.connectionString.slice(7)===Ug(e.rootDir):!1}async function Zg(e){let t=ei(e.rootDir),r=new Yo(t,DP(e.rootDir));return await r.request({op:"ping"}),new Jc(r)}function OP(e){return`file://${Ug(e)}`}function Ug(e){return IP(e,AP)}function DP(e){return{storeUri:OP(e),ttlDays:NP,byteBudget:CP,serverCommand:process.env.RSP_BIN??"rsp"}}var Jc=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return jP(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:Bg(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:Bg(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function Bg(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function jP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var MP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",qP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function Fg(e,t){return MP?LP(e,t):qP?UP(e,t):BP(e,t)}async function BP(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function LP(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:ZP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*ZP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function UP(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:FP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*FP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as HP}from"node:url";import{dirname as GP,resolve as WP,join as pj}from"node:path";import{existsSync as VP}from"node:fs";import{join as KP}from"node:path";function Vg(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=KP(r,"bin",t);if(VP(i))return i;throw new Error(`reddb: binary "${t}" not found.
40
+ `);if(d<0)return;let p=a.slice(0,d);l(()=>{try{n(JSON.parse(p))}catch(f){o(f)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var FE=108,VE=1,KE=5e3;function ei(e){let t=iP(e)??Xo(e),r=oP(t);return{rootDir:t,socketPath:je(r,"rsp.sock"),pidPath:je(r,"rsp.pid"),lockPath:je(r,"rsp.lock"),wakeLockPath:je(t,".red","tmp","rsp.wake.lock"),summaryPath:je(t,".red","tmp","rsp-status-summary.json"),registryPath:je(t,".red","tmp","rsp-resident.pid.json")}}var Yo=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await HE(this.paths,this.config);let r=await Qo(this.paths,{...t,id:Fc()});if(!r.ok)throw new Error(r.error);return r.value}};async function HE(e,t){if(await Ag(gr(e.socketPath),{recursive:!0,mode:448}),await Rg(e.socketPath,t))return;await zg(e,t);let r=await QE(e.lockPath);if(r)try{if(await Rg(e.socketPath,t))return;await zg(e,t),await JE(e.socketPath);let n=YE(e,t);await Tg(e.socketPath,n);return}finally{await r.close(),await bn(e.lockPath,{force:!0})}await Tg(e.socketPath)}async function xn(e,t=200){try{return await Ng(e,t)!=null}catch{return!1}}async function Ng(e,t=200){let r=await Qo({socketPath:e,timeoutMs:t},{id:Fc(),op:"ping"});return r.ok?Og(r.value)?{version:uP(r.value.version)}:{}:null}async function GE(e){try{let t=JSON.parse(await LE(e,"utf8"));return lP(t)?t:null}catch{return null}}async function Tg(e,t){let r=Date.now()+WE(),n;for(;Date.now()<r;){if(await xn(e))return;if(t){let o=t.spawnError();if(o)throw new Error(Zc("resident rsp server spawn failed",t,o));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(Zc("resident rsp server exited before ready",t))}await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error(t?Zc("resident rsp server did not start",t):"resident rsp server did not start")}function WE(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:KE}async function JE(e){await bn(e,{force:!0})}async function QE(e){await Ag(gr(e),{recursive:!0,mode:448});try{return await BE(e,Lc.O_CREAT|Lc.O_EXCL|Lc.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function YE(e,t){let[r,n]=nP(t),o=process.env.RSP_DEBUG==="1",i,s="",a=ME(r,[...n,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:o?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),o&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{s=eP(`${s}${c}`,XE)})),a.unref(),{child:a,stderrTail:()=>s,spawnError:()=>i}}var XE=8*1024;function Zc(e,t,r){let n=[e];r&&n.push(`error: ${r.message}`),t.child.exitCode!=null&&n.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&n.push(`signal: ${t.child.signalCode}`);let o=t.stderrTail().trimEnd();return o&&n.push(`stderr tail:
41
+ ${o}`),n.join(`
42
+ `)}function eP(e,t){let r=Buffer.byteLength(e,"utf8");return r<=t?e:Buffer.from(e,"utf8").subarray(r-t).toString("utf8").replace(/^\uFFFD+/,"")}async function zg(e,t){try{let r=await GE(e.registryPath);if(!r||r.socket_path!==e.socketPath||r.store_uri!==t.storeUri)return;if(!$n(r.pid)){await bn(e.registryPath,{force:!0});return}if(await xn(r.socket_path,100))return;if(Cg(t.clientVersion,r.resident_version)&&(await rP(r.pid,1500),!$n(r.pid))){await bn(e.registryPath,{force:!0});return}await tP(r.pid),await bn(e.registryPath,{force:!0})}catch{}}function $n(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function tP(e){if(!$n(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!$n(e))return;await new Promise(r=>setTimeout(r,50))}try{process.kill(e,"SIGKILL")}catch{}}async function rP(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(!$n(e))return;await new Promise(n=>setTimeout(n,50))}}function nP(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?Xo(process.argv[1]):UE(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function oP(e){let t=jE("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=je(r,"red-skills",t);if(je(o,"rsp.sock").length<FE)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return je(ZE(),`red-skills-${n}`,t)}function iP(e){let t=Xo(e);for(let r=0;r<32;r++){try{let o=Uc(je(t,".git"));if(o!=null)return sP(t,o)??t;if(Uc(je(t,".git","HEAD"))!=null||Uc(je(t,".red","config.yaml"))!=null)return t}catch{}let n=gr(t);if(n===t)return null;t=n}return null}function sP(e,t){let r=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!r)return null;let n=Xo(e,r[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(n)?gr(gr(gr(n))):null}function Uc(e){try{return qE(e,"utf8")}catch{return null}}async function Rg(e,t){let r=await Ng(e).catch(()=>null);return r?Cg(t.clientVersion,r.version)?(await aP(e,t.clientVersion),await dP(e),!1):!0:!1}async function aP(e,t){try{await Qo({socketPath:e,timeoutMs:200},{id:Fc(),op:"handover",clientVersion:t})}catch{}}function Cg(e,t){return!e||!t?!1:cP(e,t)>0}function cP(e,t){let r=Ig(e),n=Ig(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function Ig(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function Og(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uP(e){return typeof e=="string"&&e.length>0?e:void 0}function lP(e){return Og(e)&&e.version===VE&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function dP(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await xn(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as pP}from"node:child_process";var Kc=["supports","contradicts","related_to"];function Hc(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function Gc(e){return typeof e=="string"&&Kc.includes(e)}function yr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Dg(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
43
+ `)}function fP(e){return{deriveConnections(t){return hP(e,t)}}}function jg(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return fP({command:t,args:gP(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:yP(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function mP(e){let t=JSON.parse(_P(e));return(Array.isArray(t)?t:Vc(t)&&Array.isArray(t.connections)?t.connections:[]).filter(vP).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Vc(n.metadata)?n.metadata:void 0}))}async function hP(e,t){let r=pP(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return mP(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function gP(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function yP(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function _P(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function vP(e){return Vc(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Gc(e.kind)}function Vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as ti}from"node:fs";import{mkdir as wP,readFile as Wc,writeFile as bP}from"node:fs/promises";import{dirname as Jc,isAbsolute as $P,join as _r,resolve as bt}from"node:path";var ri="file://./.red/brain/brain.rdb",xP="RED_BRAIN_ROOT",kP="brain.root";async function SP(e=process.cwd(),t={}){let n=(t.env??process.env)[xP];if(n)return bt(e,n);let o=await EP(e);if(o)return o;let i=bt(e),s=null;for(;;){let a=_r(i,".red");if(ti(a)&&(s??=i,ti(_r(a,"brain"))||ti(_r(a,kP))))return i;let c=Jc(i);if(c===i)return s??bt(e);i=c}}async function EP(e){let t=bt(e);for(;;){let r=_r(t,".red","config.yaml");try{let o=await Wc(r,"utf8"),i=PP(o);if(i)return bt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Jc(t);if(n===t)return null;t=n}}function PP(e){let t=TP(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function TP(e){let t={},r=[],n=[];for(let o of e.split(`
44
+ `)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let p=i.indexOf("#");p>=0&&(i=i.slice(0,p))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function Mg(e){return _r(bt(e),".red","brain","config.yaml")}function zP(e){return _r(bt(e),".env")}async function RP(e){let t=Mg(e);return ti(t)||(await wP(Jc(t),{recursive:!0}),await bP(t,`connection_string: ${ri}
45
+ `,"utf8")),t}async function IP(e){let t=Mg(e);try{let r=await Wc(t,"utf8");return AP(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function AP(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:ri};let r=t.slice(18).trim();return{connection_string:qg(r)||ri}}function qg(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function Bg(e=process.cwd()){let t=await SP(e),r=await RP(t),n=await IP(t)??{connection_string:ri},o=await NP(t),i=n.connection_string,s=CP(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:OP(t,s)}}async function NP(e){let t={...process.env};try{let r=await Wc(zP(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=qg(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function CP(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function OP(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return $P(r)?t:`file://${bt(e,r)}`}import{resolve as DP}from"node:path";var jP=".red/tmp/red-skills.rdb",MP=7,qP=64*1024*1024;function Zg(e){return e.connectionString.startsWith("file://")?e.connectionString.slice(7)===Fg(e.rootDir):!1}async function Ug(e){let t=ei(e.rootDir),r=new Yo(t,LP(e.rootDir));return await r.request({op:"ping"}),new Qc(r)}function BP(e){return`file://${Fg(e)}`}function Fg(e){return DP(e,jP)}function LP(e){return{storeUri:BP(e),ttlDays:MP,byteBudget:qP,serverCommand:process.env.RSP_BIN??"rsp"}}var Qc=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return ZP(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:Lg(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:Lg(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function Lg(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function ZP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var UP=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",FP=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function Vg(e,t){return UP?KP(e,t):FP?GP(e,t):VP(e,t)}async function VP(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function KP(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:HP(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*HP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function GP(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:WP(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*WP(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as YP}from"node:url";import{dirname as XP,resolve as eT,join as yj}from"node:path";import{existsSync as JP}from"node:fs";import{join as QP}from"node:path";function Kg(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=QP(r,"bin",t);if(JP(i))return i;throw new Error(`reddb: binary "${t}" not found.
44
46
  expected at: ${i}
45
47
  override: set ${n}=/path/to/${t}
46
48
  fix: re-run \`pnpm install\` (the postinstall script downloads it),
47
- or check the postinstall log for a download error.`)}var JP=GP(HP(import.meta.url)),QP=WP(JP,"..");function YP(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function Kg(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:Vg({name:YP(),packageRoot:QP,envVar:"REDDB_BIN"})}var XP=new TextEncoder,ez=new TextDecoder("utf-8"),T=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},ni=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new T("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(XP.encode(o+`
48
- `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(ez.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new T(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new T("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function Yc(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?tz(e):rz(e)}function tz(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new T("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=nz(o),a=r.port?Number(r.port):Qc(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function rz(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new T("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):Qc(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new T("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Qc(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new T("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function nz(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new T("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Qc(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var oz=new Set(["embedded"]),kn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&oz.has(this._transport))throw new T("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:sz(n.value)}async put(t,r,n,o={}){this._guard("put");let i=iz(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function iz(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Hg(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Hg(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Hg(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function sz(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var vr=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Gg).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Xc(o,t)} = ${cz(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${Xc(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${Xc(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new T("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${eu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(Gg).join(", ")}] FROM ${eu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new T("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new T("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
49
+ or check the postinstall log for a download error.`)}var tT=XP(YP(import.meta.url)),rT=eT(tT,"..");function nT(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function Hg(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:Kg({name:nT(),packageRoot:rT,envVar:"REDDB_BIN"})}var oT=new TextEncoder,iT=new TextDecoder("utf-8"),z=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},ni=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,r={}){if(this.closed)return Promise.reject(new z("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let n=this.nextId++,o=JSON.stringify({jsonrpc:"2.0",id:n,method:t,params:r});return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.child.stdin.write(oT.encode(o+`
50
+ `)).catch(a=>{this.pending.delete(n),s(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let r of this.child.stdout){let n=new Uint8Array(t.length+r.length);n.set(t,0),n.set(r,t.length),t=n;let o=0;for(let i=0;i<t.length;i++)if(t[i]===10){let s=t.subarray(o,i);this.#r(iT.decode(s)),o=i+1}o>0&&(t=t.subarray(o))}}catch(r){this.#e(`stdout reader error: ${r.message}`);return}this.#e("server stdout closed")}#r(t){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let n=r.id;if(n==null)return;let o=this.pending.get(n);o&&(this.pending.delete(n),r.error?o.reject(new z(r.error.code??"UNKNOWN",r.error.message??"unknown error",r.error.data)):o.resolve(r.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let r=new z("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function Xc(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?sT(e):aT(e)}function sT(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let r;try{r=new URL(t)}catch(u){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),i=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let s=cT(o),a=r.port?Number(r.port):Yc(s),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:s,host:r.hostname,port:a,path:i||void 0,username:c,password:l,token:n.get("token")??void 0,apiKey:n.get("apiKey")??n.get("api_key")??void 0,loginUrl:n.get("loginUrl")??n.get("login_url")??void 0,params:n,originalUri:e}}function aT(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],r;try{r=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!r.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let n=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",o=r.searchParams;return{kind:n,host:r.hostname,port:r.port?Number(r.port):Yc(n),username:r.username?decodeURIComponent(r.username):void 0,password:r.password?decodeURIComponent(r.password):void 0,token:o.get("token")??void 0,apiKey:o.get("apiKey")??o.get("api_key")??void 0,loginUrl:o.get("loginUrl")??o.get("login_url")??void 0,params:o,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new z("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Yc(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new z("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function cT(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new z("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Yc(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var uT=new Set(["embedded"]),kn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&uT.has(this._transport))throw new z("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,r){this._guard("get");let n=await this._client.call("cache.get",{namespace:t,key:r});return n==null||n.value==null?null:dT(n.value)}async put(t,r,n,o={}){this._guard("put");let i=lT(n);await this._client.call("cache.put",{namespace:t,key:r,value:i,...o})}async exists(t,r){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:r}))?.status??"maybe"}async invalidate(t,r){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:r})}async invalidatePrefix(t,r){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:r}))?.removed??0}async invalidateTags(t,r){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:r}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}};function lT(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Gg(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Gg(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Gg(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t)}function dT(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}var vr=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Wg).join(", ")}]`:"",s=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${eu(o,t)} = ${fT(r)}${s}${i}`})}set(t,r,n={}){return this.put(t,r,n)}async get(t,r={}){let n=r.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${eu(n,t)}`}))?.rows?.[0]?.value??null}async getMany(t,r={}){let n=[];for(let o of t)n.push(await this.get(o,r));return n}async exists(t,r={}){return{exists:await this.get(t,r)!==null}}async delete(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`KV DELETE ${eu(n,t)}`}),i=o.affected??o.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let r=t.collection??this.collection,n=t.limit==null?100:Number(t.limit);if(!Number.isInteger(n)||n<=0)throw new z("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),s=(await this.client.call("query",{sql:`SELECT key, value FROM ${tu(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?s.filter(c=>String(c.key).startsWith(o)):s}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(Wg).join(", ")}] FROM ${tu(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new z("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let n=r.collection??this.collection,o=new URLSearchParams;r.sinceLsn!=null&&o.set("since_lsn",String(r.sinceLsn)),r.limit!=null&&o.set("limit",String(r.limit));let i=o.toString()?`?${o}`:"",s=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(s,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new z("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
49
51
 
50
52
  `)){let u=l.split(`
51
- `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function Xc(e,t){return`${eu(e)}.${az(t)}`}function eu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new T("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function az(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function cz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function Gg(e){return`'${String(e).replace(/'/g,"''")}'`}var Sn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${at(t)}`})}push(t,r,n={}){let o=dz(n);return this.client.call("query",{sql:`QUEUE PUSH ${at(t)} ${pz(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${at(t)}${ru(r)}`});return tu(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${at(t)}${ru(r)}`});return tu(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${at(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${at(t)}`})}async readWait(t,r,n={}){let o=uz(t,r,n),i=await this.client.call("query",{sql:o});return tu(i)}};function uz(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new T("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=at(e),a=at(t),c=o!=null?` GROUP ${at(o)}`:"",l=i!=null?ru(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function at(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new T("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function ru(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new T("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function lz(e){if(!Number.isInteger(e))throw new T("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function dz(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new T("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${lz(e.priority)}`),e.key!=null&&(t+=` KEY ${nu(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${nu(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function pz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?nu(e):JSON.stringify(e)}function nu(e){return`'${String(e).replace(/'/g,"''")}'`}function tu(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var En=class{constructor(t){this.db=t}async insert(t,r){Wg(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${oi(t)} DOCUMENT VALUES (${hz(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new T("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new T("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=fz(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${oi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){Wg(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new T("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new T("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${Jg(c)} = ${gz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${oi(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new T("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${oi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function Wg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new T("INVALID_ARGUMENT",`${t} must be an object`)}function fz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new T("INVALID_ARGUMENT","limit must be a positive integer");return e}function oi(e){return String(e).split(".").map(Jg).join(".")}function Jg(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new T("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function mz(e){return Qg(JSON.stringify(e))}function hz(e){return JSON.stringify(e)}function gz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?mz(e):Qg(e)}function Qg(e){return`'${String(e).replace(/'/g,"''")}'`}var Pn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){_z(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Yg).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${$t(o)} ${$t(t)} = ${yz(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${$t(n)} ${$t(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${$t(n)} ${$t(t)}`})}};function yz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${$t(r)}.${$t(n)})`}return vz(e)}function _z(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function $t(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function vz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Yg(e)}function Yg(e){return`'${String(e).replace(/'/g,"''")}'`}var zn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){wz(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Xg).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${wr(o)}.${wr(t)} = ${bz(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${wr(n)}.${wr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${wr(n)}.${wr(t)}`})}};function wz(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function wr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function bz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Xg(e)}function Xg(e){return`'${String(e).replace(/'/g,"''")}'`}async function ty(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map($z)}async function ry(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${kz(t)}`)).rows??[]).some(n=>n.name===String(t))}var Tn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new T("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map(ey).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${ey(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function $z(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function ey(e){return String(e).split(".").map(xz).join(".")}function xz(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new T("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function kz(e){return`'${String(e).replace(/'/g,"''")}'`}var Sz="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",Ez="1.0",iy="1.0.9",ny="NESTED_TX_NOT_SUPPORTED";async function sy(e,t={}){let r=Yc(e);if(Cz(r),r.kind==="embedded"){let n=Nz(r,t.auth);if(n.token||n.username)throw new T("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=Az(r),i=t.binary??Kg(),s=await Fg(i,o),a=new ni(s);return await a.call("version",{}),new iu(a,{transport:"embedded"})}}function oy(e){return Pz(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:Tz(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&Iz(e)?{$uuid:e}:e}function Pz(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new T("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new T("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new T("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function zz(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(oy):e.map(oy)}function Tz(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function Rz(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Iz(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function ii(e){if(Array.isArray(e))return e.map(ii);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return Rz(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=ii(o);return r}return e}function Az(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function Nz(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function Cz(e){if(e.kind!=="embedded")throw new T("EMBEDDED_ONLY",Sz)}var si=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw su()}},ou=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw su();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new T("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new T("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new T("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new si(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){ay(r,n)}throw r}}},iu=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=Ez,this.cache=new kn(t,this.transport),this.queue=new Sn(t),this.queues=this.queue,this.documents=new En(this);let n=new vr(t);this.kv=Object.assign((o="kv_default")=>new vr(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Pn(t,o),this.vault=(o="red.vault")=>new zn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new T("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=zz(r);return n==null?this.client.call("query",{sql:t}).then(ii):this.client.call("query",{sql:t,params:n}).then(ii)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return Oz(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return Dz(n,r.length)}tx(){return new ou(this)}async transaction(t){if(this.inTransaction)throw su();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new si(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){ay(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return ry(this,t)}list(){return ty(this)}from(t){return new Tn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function su(){return new T(ny,`${ny}: nested transactions are not supported on one connection`)}function ay(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function Oz(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new T("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${iy} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function Dz(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new T("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${iy} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new T("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Rn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&jz(t.chosenOption)&&Mz(t.outcome)&&qz(t.cost)}function jz(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function Mz(e){return e==="success"||e==="failure"||e==="escalated"}function qz(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as Bz}from"node:crypto";function au(e){return Bz("sha256").update(e).digest("hex")}function cy(e){return au(JSON.stringify(e))}function uy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var cu="unknown",ai=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=du(t.from),i=du(t.to),s=this.artifacts.filter(f=>f.kind==="event").map(f=>Lz(f,n)).filter(f=>f!=null).filter(f=>Uz(f,t)).filter(f=>Fz(f.ts,o,i)).sort((f,h)=>f.ts-h.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=Hz(c,l,r),p=[ly(null,s,u,r)];if(t.groupBy){let h=[...Vz(s,t.groupBy).entries()].map(([g,_])=>ly(g,_,u,r)).sort((g,_)=>_.total-g.total||Wz(g.group,_.group));p.push(...h)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:p}}};function Lz(e,t){let r=e.properties.metadata??{},n=Zz(e,r,t);return n==null?null:{ts:n,platform:uu(r,"platform")??cu,eventType:uu(r,"event_type")??cu,target:uu(r,"target")??cu}}function Zz(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:du(t.timestamp)??n}function uu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function Uz(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function Fz(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function Vz(e,t){let r=new Map;for(let n of e){let o=Kz(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function Kz(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function ly(e,t,r,n){let o=new Map;for(let s of t){let a=lu(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function Hz(e,t,r){if(e==null||t==null)return[];let n=[],o=lu(e,r),i=lu(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=Gz(o,r),s++;return n}function lu(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function Gz(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function du(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function Wz(e,t){return String(e??"").localeCompare(String(t??""))}var Jz=["validate","simple","complex","think"];var Qz={validate:1,simple:.85,complex:.65,think:.45};function Yz(){return{schemaVersion:1,buckets:{}}}function py(e,t={}){let r=oT(t.initial??Yz());for(let n of e)Xz(r,n,t);return r}function Xz(e,t,r={}){let n=(r.tierForEvent??eT)(t);if(!n)return e;let i=rT(e,t.taskClass).arms[n],s=tT(t,n);return i.posterior.alpha=dy(i.posterior.alpha+s),i.posterior.beta=dy(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function eT(e){let t=e.chosenOption.kind;if(iT(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function tT(e,t){return e.outcome!=="success"?0:Qz[t]}function rT(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=nT(),e.buckets[r]}function nT(){return{arms:{validate:ci(),simple:ci(),complex:ci(),think:ci()}}}function ci(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function oT(e){return JSON.parse(JSON.stringify(e))}function iT(e){return Jz.includes(e)}function dy(e){return Math.round(e*1e3)/1e3}var ui=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],fy={contact:"person"},li=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ke={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var pi=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await sy(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.outcomeEvents}`)}kv(){return this.db.kv(Ke.kv)}async capture(t){let r=wy(t.kind??"note"),n=Date.now(),o=uT(t.tags??[]),i=cy([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let g=await this.getArtifact(s);if(g)return g}let a=await this.listArtifacts(),c=`${uy(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},p=(await this.db.query(`INSERT INTO ${Ke.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!p)throw new Error("INSERT artifact returned no row");let f=Number(p.red_entity_id??p.rid);await this.kv().put(hy(i),f),this.artifactCache=null;let h={...u,rid:f};return await this.autoLinkArtifact(h,a),await this.materializeTagConnections(h),h}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.artifacts}`);this.artifactCache=t.rows.map(sT).filter(di)}return this.artifactCache}async search(t,r=10,n={}){let o=lT(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=$y(u,o),p=xy({...d,connections:dT(u,o,a,c),vector:0});return{artifact:u,score:p.total,score_breakdown:p,excerpt:fT(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=by(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Ke.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(gy(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.connections}`);this.connectionCache=t.rows.map(aT).filter(di)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:wT(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new ai(r).events(t)}async appendOutcomeEvent(t){if(!Rn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ke.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.outcomeEvents}`);this.outcomeEventCache=t.rows.map(cT).filter(di).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(yy());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return _y(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!_y(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(yy(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=py(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!yr(i.artifact)).slice(0,r);return mT(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(hy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(gy(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||yr(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=Og(t),i=new Set([t.rid]);for(let d of r)yr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!yr(d.artifact)).map(d=>({artifact:Kc(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Kc(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Vc},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!Hc(d.kind))continue;let p=await this.getArtifact(d.from),f=await this.getArtifact(d.to);if(!p||!f)continue;let h=p.rid===t.rid||f.rid===t.rid,g=n.has(p.rid)||n.has(f.rid);if(!h||!g||p.rid===f.rid)continue;let _=await this.link({from:p.rid,to:f.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function wy(e){let r=fy[e]??e;if(ui.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function by(e){if(li.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function sT(e){let t=Number(e.red_entity_id??e.rid),r=pu(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:wy(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function aT(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:by(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:pu(e.properties??e.PROPERTIES)}}function cT(e){let t=Number(e.red_entity_id??e.rid),r=pu(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Rn(r)?null:{rid:t,event:r}}function pu(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function di(e){return e!=null}function uT(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function lT(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function my(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function $y(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+my(r,a)*3+my(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function dT(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||yr(a))continue;let c=xy({...$y(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*pT(i.kind))}return Bt(o*.35)}function pT(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function xy(e){return{...e,lexical:Bt(e.lexical),tags:Bt(e.tags),kind:Bt(e.kind),connections:Bt(e.connections),vector:Bt(e.vector),total:Bt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Bt(e){return Math.round(e*1e3)/1e3}function fT(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function mT(e,t){let r=t.map(hT),n=gT(t),o=yT(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:_T(e,r,n,o)}}function hT(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function gT(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function yT(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function _T(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
52
- `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${vT(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
53
- `)}function vT(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(di);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function hy(e){return`artifact.hash.${e}`}function gy(e,t,r){return`connection.${e}.${r}.${t}`}function yy(){return`model-tier-bandit.v${1}`}function _y(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function wT(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function bT(e=process.cwd()){let t=await qg(e);if(Lg(t))try{return{config:t,store:await Zg(t),project:ky(t.rootDir)}}catch(n){let o=ei(t.rootDir);if(await xn(o.socketPath,50))throw n}let r=await pi.open({uri:t.connectionString,autoLinker:Dg()});return{config:t,store:r,project:ky(t.rootDir)}}async function ye(e,t=process.cwd()){let r=await bT(t);try{return await e(r)}finally{await r.store.close()}}async function Ey(e,t){if(e!=="SessionStart")return{};let r=await ye(async({config:o,store:i})=>(await i.status(),o)),n=Sy(r.rootDir,".red","brain","sessions");return await $T(n,{recursive:!0}),await xT(Sy(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var fi=class{map({event:t,sourceAgent:r}){return{title:kT(t),content:ST(t),kind:"event",tags:ET(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Py(t),metadata:PT(t)}}};function Py(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${au(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function kT(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function ST(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
54
- `)||JSON.stringify(e.raw)}function ET(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function PT(e){let t={event_key:Py(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function mi(e){let t=new fi,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Lt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Ty(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Lt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Lt("brain_act requires a non-empty message");let o=t.connect??(a=>qt.connect(a)),i=t.process??zT(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Lt(`brain_act could not reach the channel bridge: ${zy(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Lt(`brain_act could not send to "${r}": ${zy(c)}`,{cause:c})}if(!a.ok)throw new Lt(`brain_act could not send to "${r}": ${TT(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function zT(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function TT(e){return RT(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function RT(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function zy(e){return e instanceof Error?e.message:String(e)}import{createServer as IT}from"node:http";async function Ay(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:fu(n,"supports"),contradicts:fu(n,"contradicts"),depends_on:fu(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>AT(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>NT(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function Ny(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:CT(e)}}async function Cy(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=IT((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
55
- `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function AT(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:jT(e.properties.content)}}function NT(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function CT(e){return`<!doctype html>
53
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function eu(e,t){return`${tu(e)}.${pT(t)}`}function tu(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new z("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function pT(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function fT(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function Wg(e){return`'${String(e).replace(/'/g,"''")}'`}var Sn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${at(t)}`})}push(t,r,n={}){let o=gT(n);return this.client.call("query",{sql:`QUEUE PUSH ${at(t)} ${yT(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${at(t)}${nu(r)}`});return ru(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${at(t)}${nu(r)}`});return ru(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${at(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${at(t)}`})}async readWait(t,r,n={}){let o=mT(t,r,n),i=await this.client.call("query",{sql:o});return ru(i)}};function mT(e,t,r){let{waitMs:n,group:o=null,count:i=null}=r??{};if(!Number.isInteger(n)||n<0)throw new z("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let s=at(e),a=at(t),c=o!=null?` GROUP ${at(o)}`:"",l=i!=null?nu(i):"";return`QUEUE READ ${s}${c} CONSUMER ${a}${l} WAIT ${n}ms`}function at(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function nu(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new z("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function hT(e){if(!Number.isInteger(e))throw new z("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function gT(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new z("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${hT(e.priority)}`),e.key!=null&&(t+=` KEY ${ou(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${ou(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function yT(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?ou(e):JSON.stringify(e)}function ou(e){return`'${String(e).replace(/'/g,"''")}'`}function ru(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var En=class{constructor(t){this.db=t}async insert(t,r){Jg(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${oi(t)} DOCUMENT VALUES (${wT(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new z("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:n.affected??1,rid:o.rid,item:o}}async get(t,r){let n=await this.db.get(t,r);if(!n.entity)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=_T(r.limit),o=r.orderBy??r.order_by??"rid ASC",i=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${oi(t)}${i} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){Jg(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new z("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new z("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=o.map(([c,l])=>`${Qg(c)} = ${bT(l)}`).join(", "),a=(await this.db.query(`UPDATE ${oi(t)} SET ${i} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new z("NOT_FOUND",`document ${String(r)} was not found`);return a}async delete(t,r){let o=(await this.db.delete(t,r)).affected??0;return{affected:o,deleted:o>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${oi(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function Jg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z("INVALID_ARGUMENT",`${t} must be an object`)}function _T(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new z("INVALID_ARGUMENT","limit must be a positive integer");return e}function oi(e){return String(e).split(".").map(Qg).join(".")}function Qg(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function vT(e){return Yg(JSON.stringify(e))}function wT(e){return JSON.stringify(e)}function bT(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?vT(e):Yg(e)}function Yg(e){return`'${String(e).replace(/'/g,"''")}'`}var Pn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){xT(n,"config");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(Xg).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${$t(o)} ${$t(t)} = ${$T(r,n)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${$t(n)} ${$t(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${$t(n)} ${$t(t)}`})}};function $T(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${$t(r)}.${$t(n)})`}return kT(e)}function xT(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function $t(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function kT(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Xg(e)}function Xg(e){return`'${String(e).replace(/'/g,"''")}'`}var Tn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){ST(n,"vault");let o=n.collection??this.collection,i=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(ey).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${wr(o)}.${wr(t)} = ${ET(r)}${i}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${wr(n)}.${wr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${wr(n)}.${wr(t)}`})}};function ST(e,t){for(let r of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[r]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function wr(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function ET(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):ey(e)}function ey(e){return`'${String(e).replace(/'/g,"''")}'`}async function ry(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(PT)}async function ny(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${zT(t)}`)).rows??[]).some(n=>n.name===String(t))}var zn=class e{constructor(t,r,n=null,o=[],i=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=i}select(...t){let r=t.length===1&&Array.isArray(t[0])?t[0]:t,n=r.length===1&&r[0]==="*"?null:r;return new e(this.db,this.collection,n!=null&&n.length>0?n:null,this.whereClauses,this.params)}where(t,...r){if(typeof t!="string"||t.trim().length===0)throw new z("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let n=r.length===1&&Array.isArray(r[0])?r[0]:r;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...n])}async run(){let t=this.columns==null?"*":this.columns.map(ty).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(s=>`(${s})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${ty(this.collection)}${r}`,i=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?i:i.map(s=>{let a={};for(let c of this.columns)a[c]=s[c];return a})}};function PT(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function ty(e){return String(e).split(".").map(TT).join(".")}function TT(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new z("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function zT(e){return`'${String(e).replace(/'/g,"''")}'`}var RT="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",IT="1.0",sy="1.0.9",oy="NESTED_TX_NOT_SUPPORTED";async function ay(e,t={}){let r=Xc(e);if(qT(r),r.kind==="embedded"){let n=MT(r,t.auth);if(n.token||n.username)throw new z("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=jT(r),i=t.binary??Hg(),s=await Vg(i,o),a=new ni(s);return await a.call("version",{}),new su(a,{transport:"embedded"})}}function iy(e){return AT(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:CT(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&DT(e)?{$uuid:e}:e}function AT(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new z("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new z("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new z("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function NT(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(iy):e.map(iy)}function CT(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}function OT(e){if(typeof Buffer<"u"){let n=Buffer.from(e,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function DT(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function ii(e){if(Array.isArray(e))return e.map(ii);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return OT(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let n=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(n/1000000n))}}let r={};for(let[n,o]of Object.entries(e))r[n]=ii(o);return r}return e}function jT(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function MT(e,t){let r={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return r;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");r.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");r.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");r.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");r.password=t.password}return t.loginUrl!=null&&(r.loginUrl=t.loginUrl),r}function qT(e){if(e.kind!=="embedded")throw new z("EMBEDDED_ONLY",RT)}var si=class{constructor(t){this.db=t}query(t,...r){return this.db.query(t,...r)}execute(t,...r){return this.db.execute(t,...r)}insert(t,r){return this.db.insert(t,r)}bulkInsert(t,r){return this.db.bulkInsert(t,r)}async transaction(){throw au()}},iu=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw au();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new z("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new z("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new si(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){cy(r,n)}throw r}}},su=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=IT,this.cache=new kn(t,this.transport),this.queue=new Sn(t),this.queues=this.queue,this.documents=new En(this);let n=new vr(t);this.kv=Object.assign((o="kv_default")=>new vr(t,o),{put:n.put.bind(n),invalidateTags:n.invalidateTags.bind(n),watch:n.watch.bind(n),watchPrefix:n.watchPrefix.bind(n)}),this.config=(o="red.config")=>new Pn(t,o),this.vault=(o="red.vault")=>new Tn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new z("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=NT(r);return n==null?this.client.call("query",{sql:t}).then(ii):this.client.call("query",{sql:t,params:n}).then(ii)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return BT(n,"insert")}async bulkInsert(t,r){if(Array.isArray(r)&&r.length===0)return{affected:0,rids:[],ids:[]};let n=await this.client.call("bulk_insert",{collection:t,payloads:r});return LT(n,r.length)}tx(){return new iu(this)}async transaction(t){if(this.inTransaction)throw au();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let r=!1;try{await this.query("BEGIN"),r=!0;let n=await t(new si(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){cy(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return ny(this,t)}list(){return ry(this)}from(t){return new zn(this,t)}get(t,r){return this.client.call("get",{collection:t,id:String(r)})}delete(t,r){return this.client.call("delete",{collection:t,id:String(r)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,r){return this.client.call("auth.login",{username:t,password:r})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,r){return this.client.call("auth.change_password",{current_password:t,new_password:r})}createApiKey({username:t,role:r}={}){return this.client.call("auth.create_api_key",{username:t,role:r})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}};function au(){return new z(oy,`${oy}: nested transactions are not supported on one connection`)}function cy(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function BT(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new z("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${sy} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function LT(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new z("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${sy} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new z("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}function Rn(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&ZT(t.chosenOption)&&UT(t.outcome)&&FT(t.cost)}function ZT(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function UT(e){return e==="success"||e==="failure"||e==="escalated"}function FT(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}import{createHash as VT}from"node:crypto";function cu(e){return VT("sha256").update(e).digest("hex")}function uy(e){return cu(JSON.stringify(e))}function ly(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var uu="unknown",ai=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=pu(t.from),i=pu(t.to),s=this.artifacts.filter(f=>f.kind==="event").map(f=>KT(f,n)).filter(f=>f!=null).filter(f=>GT(f,t)).filter(f=>WT(f.ts,o,i)).sort((f,h)=>f.ts-h.ts),a=s.length,c=o??(s.length>0?s[0].ts:null),l=i??(s.length>0?s[s.length-1].ts:null),u=YT(c,l,r),p=[dy(null,s,u,r)];if(t.groupBy){let h=[...JT(s,t.groupBy).entries()].map(([g,_])=>dy(g,_,u,r)).sort((g,_)=>_.total-g.total||ez(g.group,_.group));p.push(...h)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:p}}};function KT(e,t){let r=e.properties.metadata??{},n=HT(e,r,t);return n==null?null:{ts:n,platform:lu(r,"platform")??uu,eventType:lu(r,"event_type")??uu,target:lu(r,"target")??uu}}function HT(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:pu(t.timestamp)??n}function lu(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function GT(e,t){return!(t.platform!=null&&e.platform!==t.platform||t.eventType!=null&&e.eventType!==t.eventType||t.target!=null&&e.target!==t.target)}function WT(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function JT(e,t){let r=new Map;for(let n of e){let o=QT(n,t),i=r.get(o);i?i.push(n):r.set(o,[n])}return r}function QT(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function dy(e,t,r,n){let o=new Map;for(let s of t){let a=du(s.ts,n);o.set(a,(o.get(a)??0)+1)}let i=r.map(s=>({start:s,startIso:new Date(s).toISOString(),count:o.get(s)??0}));return{group:e,total:t.length,buckets:i}}function YT(e,t,r){if(e==null||t==null)return[];let n=[],o=du(e,r),i=du(t,r),s=0;for(;o<=i&&s<1e6;)n.push(o),o=XT(o,r),s++;return n}function du(e,t){let r=new Date(e);switch(t){case"hour":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),r.getUTCHours());case"day":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate());case"week":{let n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),i=(new Date(n).getUTCDay()+6)%7;return n-i*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function XT(e,t){switch(t){case"hour":return e+36e5;case"day":return e+864e5;case"week":return e+6048e5;case"month":{let r=new Date(e);return Date.UTC(r.getUTCFullYear(),r.getUTCMonth()+1,1)}}}function pu(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let t=e.trim();if(t==="")return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isFinite(n)?n:null}let r=Date.parse(t);return Number.isNaN(r)?null:r}function ez(e,t){return String(e??"").localeCompare(String(t??""))}var tz=["validate","simple","complex","think"];var rz={validate:1,simple:.85,complex:.65,think:.45};function nz(){return{schemaVersion:1,buckets:{}}}function fy(e,t={}){let r=uz(t.initial??nz());for(let n of e)oz(r,n,t);return r}function oz(e,t,r={}){let n=(r.tierForEvent??iz)(t);if(!n)return e;let i=az(e,t.taskClass).arms[n],s=sz(t,n);return i.posterior.alpha=py(i.posterior.alpha+s),i.posterior.beta=py(i.posterior.beta+(1-s)),i.observations+=1,t.outcome==="success"?(i.successes+=1,i.consecutiveFailures=0):(i.failures+=1,i.consecutiveFailures+=1),e}function iz(e){let t=e.chosenOption.kind;if(lz(t))return t;let r=e.chosenOption.model?.toLowerCase()??"",n=e.chosenOption.effort?.toLowerCase()??"";if(r.includes("haiku"))return"validate";if(r.includes("sonnet"))return"simple";if(r.includes("opus")&&n==="high")return"think";if(r.includes("opus"))return"complex"}function sz(e,t){return e.outcome!=="success"?0:rz[t]}function az(e,t){let r=t.trim()||"unknown";return e.buckets[r]??=cz(),e.buckets[r]}function cz(){return{arms:{validate:ci(),simple:ci(),complex:ci(),think:ci()}}}function ci(){return{posterior:{alpha:1,beta:1},observations:0,successes:0,failures:0,consecutiveFailures:0}}function uz(e){return JSON.parse(JSON.stringify(e))}function lz(e){return tz.includes(e)}function py(e){return Math.round(e*1e3)/1e3}var ui=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],my={contact:"person"},li=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],Ke={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"};var pi=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;outcomeEventCache=null;modelTierBanditCache=null;static async open(t){let r=new e(t);return r.db=await ay(t.uri),await r.bootstrap(),r}get raw(){return this.db}async close(){await this.db.close()}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${Ke.outcomeEvents}`)}kv(){return this.db.kv(Ke.kv)}async capture(t){let r=by(t.kind??"note"),n=Date.now(),o=mz(t.tags??[]),i=uy([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),s=await this.findArtifactByHash(i);if(s!=null){let g=await this.getArtifact(s);if(g)return g}let a=await this.listArtifacts(),c=`${ly(t.title)}-${i.slice(0,8)}`,l={id:c,title:t.title,content:t.content,tags:o,source_agent:t.sourceAgent,source_runner:t.sourceRunner,source_session:t.sourceSession,source_path:t.sourcePath,created_at:n,updated_at:n,hash:i,metadata:t.metadata},u={label:c,kind:r,properties:l},p=(await this.db.query(`INSERT INTO ${Ke.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,i,l)).rows[0];if(!p)throw new Error("INSERT artifact returned no row");let f=Number(p.red_entity_id??p.rid);await this.kv().put(gy(i),f),this.artifactCache=null;let h={...u,rid:f};return await this.autoLinkArtifact(h,a),await this.materializeTagConnections(h),h}async getArtifact(t){let r=await this.listArtifacts();return typeof t=="number"?r.find(n=>n.rid===t)??null:r.find(n=>n.properties.id===t||n.label===t)??null}async listArtifacts(){if(this.artifactCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.artifacts}`);this.artifactCache=t.rows.map(dz).filter(di)}return this.artifactCache}async search(t,r=10,n={}){let o=hz(t),i=new Set(n.excludeRids??[]),s=await this.listArtifacts(),a=await this.listConnections(),c=new Map(s.map(u=>[u.rid,u]));return s.filter(u=>!i.has(u.rid)).map(u=>{let d=xy(u,o),p=ky({...d,connections:gz(u,o,a,c),vector:0});return{artifact:u,score:p.total,score_breakdown:p,excerpt:_z(u.properties.content,o)}}).filter(u=>u.score>0).sort((u,d)=>d.score-u.score||d.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,r)}async link(t){let r=await this.getArtifact(t.from),n=await this.getArtifact(t.to);if(!r)throw new Error(`Brain artifact not found: ${t.from}`);if(!n)throw new Error(`Brain artifact not found: ${t.to}`);let o=$y(t.kind??"related_to"),i=await this.findConnection(r.rid,n.rid,o);if(i!=null){let u=(await this.listConnections()).find(d=>d.rid===i);if(u)return u}let s={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${Ke.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,s)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let l=Number(c.red_entity_id??c.rid);return await this.kv().put(yy(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:s}}async backlinks(t){let r=await this.getArtifact(t);if(!r)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(n=>n.to_rid===r.rid)}async listConnections(){if(this.connectionCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.connections}`);this.connectionCache=t.rows.map(pz).filter(di)}return this.connectionCache}async status(){let t=await this.listArtifacts(),r=await this.listConnections();return{uri:this.opts.uri,artifacts:t.length,connections:r.length,kinds:Sz(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new ai(r).events(t)}async appendOutcomeEvent(t){if(!Rn(t))throw new Error("invalid Brain outcome event");let r={...t};if(!(await this.db.query(`INSERT INTO ${Ke.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,r)).rows[0])throw new Error("INSERT outcome event returned no row");return this.outcomeEventCache=null,t}async replayOutcomeEvents(){if(this.outcomeEventCache==null){let t=await this.db.query(`SELECT * FROM ${Ke.outcomeEvents}`);this.outcomeEventCache=t.rows.map(fz).filter(di).sort((r,n)=>r.rid-n.rid).map(({rid:r,event:n})=>n)}return[...this.outcomeEventCache]}async loadModelTierBanditDocument(){if(this.modelTierBanditCache!=null)return this.modelTierBanditCache;let t=await this.kv().get(_y());if(t==null)return null;let r=typeof t=="string"?JSON.parse(t):t;return vy(r)?(this.modelTierBanditCache=r,r):null}async saveModelTierBanditDocument(t){if(!vy(t))throw new Error("invalid Brain model-tier bandit document");return await this.kv().put(_y(),JSON.stringify(t)),this.modelTierBanditCache=t,t}async refreshModelTierBanditDocument(){let t=fy(await this.replayOutcomeEvents());return this.saveModelTierBanditDocument(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(i=>!yr(i.artifact)).slice(0,r);return vz(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(gy(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(yy(t,r,n));return o!=null?Number(o):null}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let r of t.properties.tags){let n=await this.capture({title:r,content:`Tag: ${r}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:n.rid,kind:"tagged",confidence:"derived"})}}async autoLinkArtifact(t,r){if(!this.opts.autoLinker||yr(t))return[];let n=new Set(r.filter(o=>o.rid!==t.rid).map(o=>o.rid));if(n.size===0)return[];try{let o=Dg(t),i=new Set([t.rid]);for(let d of r)yr(d)&&i.add(d.rid);let s=await this.think(o,8,{excludeRids:i}),a=s.hits.filter(d=>n.has(d.artifact.rid)&&!yr(d.artifact)).map(d=>({artifact:Hc(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Hc(t),candidates:a,think:{query:o,answer:s.answer},allowedKinds:Kc},l=await this.opts.autoLinker.deriveConnections(c),u=[];for(let d of l){if(!Gc(d.kind))continue;let p=await this.getArtifact(d.from),f=await this.getArtifact(d.to);if(!p||!f)continue;let h=p.rid===t.rid||f.rid===t.rid,g=n.has(p.rid)||n.has(f.rid);if(!h||!g||p.rid===f.rid)continue;let _=await this.link({from:p.rid,to:f.rid,kind:d.kind,reason:d.reason,confidence:"derived",metadata:{...d.metadata??{},derived_by:"brain.autolink.afk-headless",source_artifact_rid:t.rid}});u.push({proposal:d,connection:_})}return u}catch(o){if(this.opts.autoLinkErrors==="throw")throw o;return[]}}};function by(e){let r=my[e]??e;if(ui.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function $y(e){if(li.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function dz(e){let t=Number(e.red_entity_id??e.rid),r=fu(e.properties??e.PROPERTIES),n=String(e.node_type??e.NODE_TYPE??r.kind??"note");if(!Number.isFinite(t))return null;let o=String(r.id??e.label??e.LABEL??t),i=String(r.title??e.label??e.LABEL??o),s=String(r.content??""),a=Array.isArray(r.tags)?r.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??o),kind:by(n),properties:{...r,id:o,title:i,content:s,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function pz(e){let t=Number(e.red_entity_id??e.rid),r=Number(e.from??e.FROM??e.from_rid??e.source),n=Number(e.to??e.TO??e.to_rid??e.target),o=String(e.label??e.LABEL??"related_to");return!Number.isFinite(t)||!Number.isFinite(r)||!Number.isFinite(n)?null:{rid:t,kind:$y(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:fu(e.properties??e.PROPERTIES)}}function fz(e){let t=Number(e.red_entity_id??e.rid),r=fu(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Rn(r)?null:{rid:t,event:r}}function fu(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function di(e){return e!=null}function mz(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function hz(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function hy(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function xy(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(s=>s.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((s,a)=>s+hy(r,a)*3+hy(n,a),0),tags:t.reduce((s,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return s+c},0),kind:t.reduce((s,a)=>i===a?s+3:i.includes(a)||a.includes(i)?s+1:s,0)}}function gz(e,t,r,n){let o=0;for(let i of r){let s=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(s==null)continue;let a=n.get(s);if(!a||yr(a))continue;let c=ky({...xy(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*yz(i.kind))}return Bt(o*.35)}function yz(e){switch(e){case"supports":case"contradicts":case"depends_on":case"derived_from":case"part_of":return 1;case"related_to":case"authored":return .75;case"preceded_by":case"followed_by":return .5;case"tagged":return .2}}function ky(e){return{...e,lexical:Bt(e.lexical),tags:Bt(e.tags),kind:Bt(e.kind),connections:Bt(e.connections),vector:Bt(e.vector),total:Bt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Bt(e){return Math.round(e*1e3)/1e3}function _z(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(i=>r.indexOf(i)).filter(i=>i>=0).sort((i,s)=>i-s)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function vz(e,t){let r=t.map(wz),n=bz(t),o=$z(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:xz(e,r,n,o)}}function wz(e,t){let r=e.artifact,n={};return r.properties.source_path&&(n.path=r.properties.source_path),r.properties.source_session&&(n.session=r.properties.source_session),r.properties.source_agent&&(n.agent=r.properties.source_agent),r.properties.source_runner&&(n.runner=r.properties.source_runner),{ref:`B${t+1}`,rid:r.rid,id:r.properties.id,title:r.properties.title,kind:r.kind,score:e.score,score_breakdown:e.score_breakdown,excerpt:e.excerpt,source:Object.keys(n).length>0?n:void 0}}function bz(e){let t=e[0];if(!t)return"none";let r=Object.entries(t.score_breakdown).filter(([n,o])=>n!=="total"&&o>0).length;return t.score>=8||t.score>=5&&r>=2?"high":t.score>=3?"medium":"low"}function $z(e,t,r){if(t.length===0)return[`No Brain artifacts matched "${e}". Capture or ingest cited artifacts before relying on Brain for this answer.`];let n=[];return r==="low"&&n.push("Only low-scoring deterministic matches were found; open the cited artifacts before treating this as settled."),t.length===1&&n.push("Only one cited artifact matched; missing context or contradictions may not be visible yet."),t.every(o=>o.source==null)&&n.push("The matched artifacts do not carry source path, session, agent, or runner provenance."),n}function xz(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
54
+ `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),i=t.map(a=>{let c=Object.entries(a.score_breakdown).filter(([l,u])=>l!=="total"&&u>0).map(([l,u])=>`${l} ${u}`).join(", ");return`[${a.ref}] ${a.title} (${a.kind}, rid ${a.rid}, score ${a.score})${c?` [${c}]`:""}; ${kz(a)}`}),s=n.length>0?n.map(a=>`- ${a}`):["- No deterministic evidence gap detected in the returned Brain citations."];return[`Brain answer for "${e}"`,"",`Confidence: ${r}`,"","Best cited evidence:",...o,"","Missing evidence:",...s,"","Citations:",...i].join(`
55
+ `)}function kz(e){if(!e.source)return`source: Brain artifact ${e.id}`;let t=[e.source.path?`path ${e.source.path}`:null,e.source.session?`session ${e.source.session}`:null,e.source.agent?`agent ${e.source.agent}`:null,e.source.runner?`runner ${e.source.runner}`:null].filter(di);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function gy(e){return`artifact.hash.${e}`}function yy(e,t,r){return`connection.${e}.${r}.${t}`}function _y(){return`model-tier-bandit.v${1}`}function vy(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.buckets=="object"}function Sz(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function Ez(e=process.cwd()){let t=await Bg(e);if(Zg(t))try{return{config:t,store:await Ug(t),project:Sy(t.rootDir)}}catch(n){let o=ei(t.rootDir);if(await xn(o.socketPath,50))throw n}let r=await pi.open({uri:t.connectionString,autoLinker:jg()});return{config:t,store:r,project:Sy(t.rootDir)}}async function ye(e,t=process.cwd()){let r=await Ez(t);try{return await e(r)}finally{await r.store.close()}}async function Py(e,t){if(e!=="SessionStart")return{};let r=await ye(async({config:o,store:i})=>(await i.status(),o)),n=Ey(r.rootDir,".red","brain","sessions");return await Pz(n,{recursive:!0}),await Tz(Ey(n,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var fi=class{map({event:t,sourceAgent:r}){return{title:zz(t),content:Rz(t),kind:"event",tags:Iz(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Ty(t),metadata:Az(t)}}};function Ty(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${cu(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function zz(e){let t=[];e.platform&&t.push(e.platform),e.target&&t.push(e.target);let r=t.length>0?`[${t.join(":")}]`:"[channel-event]";if(e.message){let n=e.message.slice(0,60).replace(/\n/g," ");return`${r} ${n}`}return e.type?`${r} ${e.type}`:`${r} event`}function Rz(e){let t=[];return e.message&&t.push(e.message),e.type&&t.push(`type: ${e.type}`),e.platform&&t.push(`platform: ${e.platform}`),e.target&&t.push(`target: ${e.target}`),e.timestamp&&t.push(`timestamp: ${e.timestamp}`),t.join(`
56
+ `)||JSON.stringify(e.raw)}function Iz(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function Az(e){let t={event_key:Ty(e)};return e.id!=null&&(t.event_id=e.id),e.cursor!=null&&(t.cursor=e.cursor),e.timestamp!=null&&(t.timestamp=e.timestamp),e.platform!=null&&(t.platform=e.platform),e.target!=null&&(t.target=e.target),e.sessionKey!=null&&(t.session_key=e.sessionKey),e.type!=null&&(t.event_type=e.type),t}async function mi(e){let t=new fi,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(s=>s.rid)),o=0,i=0;for(let s of r.events){let a=t.map({event:s,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?i++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:i,nextCursor:r.nextCursor}}var Lt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Ry(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Lt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Lt("brain_act requires a non-empty message");let o=t.connect??(a=>qt.connect(a)),i=t.process??Nz(t.env??process.env),s;try{s=await o(i)}catch(a){throw new Lt(`brain_act could not reach the channel bridge: ${zy(a)}`,{cause:a})}try{let a;try{a=await s.send(r,n)}catch(c){throw new Lt(`brain_act could not send to "${r}": ${zy(c)}`,{cause:c})}if(!a.ok)throw new Lt(`brain_act could not send to "${r}": ${Cz(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await s.close().catch(()=>{})}}function Nz(e=process.env){let t=e.RED_BRAIN_HERMES_COMMAND?.trim()||void 0,r=e.RED_BRAIN_HERMES_ARGS?.trim(),n=r?r.split(/\s+/).filter(Boolean):void 0;return{command:t,args:n}}function Cz(e){return Oz(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function Oz(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let r=e;for(let n of t){let o=r[n];if(typeof o=="string"&&o.trim())return o}}function zy(e){return e instanceof Error?e.message:String(e)}import{createServer as Dz}from"node:http";async function Ny(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),i=await e.eventKpis({interval:"day"}),s=await e.eventKpis({interval:"day",groupBy:"platform"}),a=await e.eventKpis({interval:"day",groupBy:"event_type"}),c=t.decisionLimit??8,l=t.connectionLimit??12;return{schema_version:"brain.dashboard.v1",generated_at:new Date(t.now??Date.now()).toISOString(),project:t.project,root:t.rootDir,stats:{artifacts:r.length,connections:n.length,decisions:r.filter(u=>u.kind==="decision").length,events:i.total,supports:mu(n,"supports"),contradicts:mu(n,"contradicts"),depends_on:mu(n,"depends_on")},kpis:{events_daily:i,events_by_platform:s,events_by_type:a},recent_decisions:r.filter(u=>u.kind==="decision").sort((u,d)=>d.properties.updated_at-u.properties.updated_at||d.rid-u.rid).slice(0,c).map(u=>jz(u,n)),recent_connections:n.filter(u=>o.has(u.from_rid)&&o.has(u.to_rid)).sort((u,d)=>d.properties.created_at-u.properties.created_at||d.rid-u.rid).slice(0,l).map(u=>Mz(u,o)),attribution:{red_hermes:"Dashboard layout and command-center interaction model are adapted from the red-hermes web surface; NOTICE records the MIT attribution."}}}function Cy(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:qz(e)}}async function Oy(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=Dz((i,s)=>{let a=i.url??"/";if(a==="/"||a==="/dashboard"){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(e);return}s.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),s.end(`not found
57
+ `)});return await new Promise((i,s)=>{o.once("error",s),o.listen(n,r,()=>{o.off("error",s),i()})}),o}function jz(e,t){let r=t.filter(n=>n.from_rid===e.rid||n.to_rid===e.rid);return{rid:e.rid,id:e.properties.id,title:e.properties.title,updated_at:new Date(e.properties.updated_at).toISOString(),tags:e.properties.tags,connection_counts:{supports:r.filter(n=>n.kind==="supports").length,contradicts:r.filter(n=>n.kind==="contradicts").length,depends_on:r.filter(n=>n.kind==="depends_on").length,related_to:r.filter(n=>n.kind==="related_to").length},excerpt:Zz(e.properties.content)}}function Mz(e,t){let r=t.get(e.from_rid),n=t.get(e.to_rid);if(!r||!n)throw new Error(`connection ${e.rid} references missing artifacts`);return{rid:e.rid,kind:e.kind,from:{rid:r.rid,title:r.properties.title},to:{rid:n.rid,title:n.properties.title},created_at:new Date(e.properties.created_at).toISOString(),reason:e.properties.reason??null}}function qz(e){return`<!doctype html>
56
58
  <html lang="en">
57
59
  <head>
58
60
  <meta charset="utf-8">
@@ -244,36 +246,36 @@ var By=Object.create;var _i=Object.defineProperty;var Ly=Object.getOwnPropertyDe
244
246
  <section>
245
247
  <h2>Event KPIs</h2>
246
248
  <div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
247
- ${Ry(e.kpis.events_by_platform,"Platform")}
248
- ${Ry(e.kpis.events_by_type,"Event type")}
249
+ ${Iy(e.kpis.events_by_platform,"Platform")}
250
+ ${Iy(e.kpis.events_by_type,"Event type")}
249
251
  </section>
250
252
  <section>
251
253
  <h2>Recent Decisions</h2>
252
254
  <div class="feed">
253
- ${e.recent_decisions.length===0?Iy("No decision artifacts captured yet."):e.recent_decisions.map(OT).join("")}
255
+ ${e.recent_decisions.length===0?Ay("No decision artifacts captured yet."):e.recent_decisions.map(Bz).join("")}
254
256
  </div>
255
257
  </section>
256
258
  </div>
257
259
  <section>
258
260
  <h2>Recent Connections</h2>
259
261
  <div class="feed">
260
- ${e.recent_connections.length===0?Iy("No graph connections captured yet."):e.recent_connections.map(DT).join("")}
262
+ ${e.recent_connections.length===0?Ay("No graph connections captured yet."):e.recent_connections.map(Lz).join("")}
261
263
  </div>
262
264
  </section>
263
265
  </main>
264
266
  <footer class="meta">${ie(e.attribution.red_hermes)}</footer>
265
- <script id="brain-dashboard-data" type="application/json">${MT(e)}</script>
267
+ <script id="brain-dashboard-data" type="application/json">${Uz(e)}</script>
266
268
  </body>
267
- </html>`}function br(e,t,r){return`<div class="metric"><span>${ie(e)}</span><strong>${t}</strong><div class="meta">${ie(r)}</div></div>`}function Ry(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${ie(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${ie(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${ie(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function OT(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${ie(n)}</span>`).join("")}</div>`;return`<article class="item">
269
+ </html>`}function br(e,t,r){return`<div class="metric"><span>${ie(e)}</span><strong>${t}</strong><div class="meta">${ie(r)}</div></div>`}function Iy(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${ie(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${ie(t)}">${r.map(o=>{let i=o.group??"all",s=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${ie(i)}</div><div class="track"><div class="fill" style="width:${s}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function Bz(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${ie(n)}</span>`).join("")}</div>`;return`<article class="item">
268
270
  <h3>${ie(e.title)}</h3>
269
271
  <div class="meta">#${e.rid} - ${ie(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
270
272
  <p class="meta">${ie(e.excerpt)}</p>
271
273
  ${r}
272
- </article>`}function DT(e){return`<article class="item">
274
+ </article>`}function Lz(e){return`<article class="item">
273
275
  <h3><span class="edge ${ie(e.kind)}">${ie(e.kind)}</span> ${ie(e.from.title)} -> ${ie(e.to.title)}</h3>
274
276
  <div class="meta">#${e.rid} - ${ie(e.created_at)}${e.reason?` - ${ie(e.reason)}`:""}</div>
275
- </article>`}function Iy(e){return`<div class="empty">${ie(e)}</div>`}function fu(e,t){return e.filter(r=>r.kind===t).length}function jT(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function ie(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function MT(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as qT,readFile as BT,writeFile as LT}from"node:fs/promises";import{dirname as ZT}from"node:path";async function Oy(e){let t=await mi({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function Dy(e){try{let t=await BT(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function jy(e,t){await qT(ZT(e),{recursive:!0}),await LT(e,JSON.stringify(t,null,2)+`
276
- `,"utf8")}async function HT(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":uR();return;case"init":await ye(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await ye(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await WT(t);return;case"search":await JT(t);return;case"think":case"query":await QT(t);return;case"get":await YT(t);return;case"link":await XT(t);return;case"backlinks":await eR(t);return;case"act":await iR(t);return;case"hook":await sR(t);return;case"ingest-events":await rR(t);return;case"schedule-ingest":await tR(t);return;case"kpi":case"kpis":await nR(t);return;case"dashboard":await oR(t);return;case"outcome-event":await GT(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function GT(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=He(r),o=await cR(),i=JSON.parse(o);if(!Rn(i))throw new Error("invalid brain outcome event");await ye(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},j(n,"root")??process.cwd())}async function WT(e){let t=He(e),r=(j(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=j(t,"content")??(j(t,"file")?await UT(String(j(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await ye(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:j(t,"kind")??"note",tags:aR(t,"tag"),sourceAgent:j(t,"agent"),sourceRunner:j(t,"runner"),sourceSession:j(t,"session"),sourcePath:process.cwd()});$e(i)})}async function JT(e){let t=He(e),r=j(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=In(t,"limit")??10;await ye(async({store:o})=>$e(await o.search(r,n)))}async function QT(e){let t=He(e),r=j(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=In(t,"limit")??8;await ye(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function YT(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await ye(async({store:r})=>{let n=await r.getArtifact(hi(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function XT(e){let t=He(e),r=j(t,"from"),n=j(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await ye(async({store:o})=>{$e(await o.link({from:hi(r),to:hi(n),kind:j(t,"kind")??"related_to",reason:j(t,"reason")}))})}async function eR(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await ye(async({store:r})=>$e(await r.backlinks(hi(t))))}async function tR(e){let t=He(e),r=j(t,"session-key")??j(t,"session"),n=In(t,"limit"),o=await qt.connect();try{await ye(async({config:i,store:s})=>{let a=j(t,"state")??My(i.rootDir,".red","brain","ingestion-state.json"),c=await Dy(a),l=await Oy({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await jy(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function rR(e){let t=He(e),r=j(t,"after-cursor")??j(t,"cursor"),n=j(t,"session-key")??j(t,"session"),o=In(t,"limit"),i=await qt.connect();try{await ye(async({store:s})=>{let a=await mi({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function nR(e){let t=He(e),r=j(t,"interval"),n=j(t,"group-by"),o=j(t,"time-field");await ye(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:j(t,"from"),to:j(t,"to"),platform:j(t,"platform"),eventType:j(t,"event-type"),target:j(t,"target")}))})}async function oR(e){let t=He(e),r=await ye(async({config:o,store:i,project:s})=>{let a=await Ay(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:Ny(a),defaultOut:My(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=j(t,"host")??"127.0.0.1",i=In(t,"port")??4738,s=await Cy(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=j(t,"out")??r.defaultOut;await FT(KT(n),{recursive:!0}),await VT(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function iR(e){let t=He(e),r=j(t,"target")??t._[0],n=j(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await Ty({target:r,message:n}))}async function sR(e){let[t="SessionStart",...r]=e,n=He(r),o=j(n,"runner")??"unknown";$e(await Ey(t,o))}function hi(e){return/^\d+$/.test(e)?Number(e):e}function He(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function j(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function aR(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function In(e,t){let r=j(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function cR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function uR(){console.log(`brain commands:
277
+ </article>`}function Ay(e){return`<div class="empty">${ie(e)}</div>`}function mu(e,t){return e.filter(r=>r.kind===t).length}function Zz(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function ie(e){return e.replace(/[&<>"']/g,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return t}})}function Uz(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as Fz,readFile as Vz,writeFile as Kz}from"node:fs/promises";import{dirname as Hz}from"node:path";async function Dy(e){let t=await mi({bridge:e.bridge,store:e.store,afterCursor:e.state.cursor,sessionKey:e.sessionKey,limit:e.limit,sourceAgent:e.sourceAgent}),r={cursor:t.nextCursor??e.state.cursor,lastRunAt:new Date().toISOString()};return{polled:t.polled,captured:t.captured,skipped:t.skipped,state:r}}async function jy(e){try{let t=await Vz(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function My(e,t){await Fz(Hz(e),{recursive:!0}),await Kz(e,JSON.stringify(t,null,2)+`
278
+ `,"utf8")}async function Yz(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":mR();return;case"init":await ye(async({config:r,store:n})=>{let o=await n.status();$e({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await ye(async({config:r,store:n})=>{$e({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await eR(t);return;case"search":await tR(t);return;case"think":case"query":await rR(t);return;case"get":await nR(t);return;case"link":await oR(t);return;case"backlinks":await iR(t);return;case"act":await lR(t);return;case"hook":await dR(t);return;case"ingest-events":await aR(t);return;case"schedule-ingest":await sR(t);return;case"kpi":case"kpis":await cR(t);return;case"dashboard":await uR(t);return;case"outcome-event":await Xz(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function Xz(e){let[t,...r]=e;if(t!=="record")throw new Error("brain outcome-event requires subcommand: record");let n=He(r),o=await fR(),i=JSON.parse(o);if(!Rn(i))throw new Error("invalid brain outcome event");await ye(async({store:s})=>{$e(await s.appendOutcomeEvent(i))},j(n,"root")??process.cwd())}async function eR(e){let t=He(e),r=(j(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=j(t,"content")??(j(t,"file")?await Gz(String(j(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await ye(async({store:o})=>{let i=await o.capture({title:r,content:n,kind:j(t,"kind")??"note",tags:pR(t,"tag"),sourceAgent:j(t,"agent"),sourceRunner:j(t,"runner"),sourceSession:j(t,"session"),sourcePath:process.cwd()});$e(i)})}async function tR(e){let t=He(e),r=j(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=In(t,"limit")??10;await ye(async({store:o})=>$e(await o.search(r,n)))}async function rR(e){let t=He(e),r=j(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=In(t,"limit")??8;await ye(async({store:o})=>{let i=await o.think(r,n);t.json===!0?$e(i):console.log(i.answer)})}async function nR(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await ye(async({store:r})=>{let n=await r.getArtifact(hi(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);$e(n)})}async function oR(e){let t=He(e),r=j(t,"from"),n=j(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await ye(async({store:o})=>{$e(await o.link({from:hi(r),to:hi(n),kind:j(t,"kind")??"related_to",reason:j(t,"reason")}))})}async function iR(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await ye(async({store:r})=>$e(await r.backlinks(hi(t))))}async function sR(e){let t=He(e),r=j(t,"session-key")??j(t,"session"),n=In(t,"limit"),o=await qt.connect();try{await ye(async({config:i,store:s})=>{let a=j(t,"state")??qy(i.rootDir,".red","brain","ingestion-state.json"),c=await jy(a),l=await Dy({bridge:o,store:s,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await My(a,l.state),$e(l)})}finally{await o.close().catch(()=>{})}}async function aR(e){let t=He(e),r=j(t,"after-cursor")??j(t,"cursor"),n=j(t,"session-key")??j(t,"session"),o=In(t,"limit"),i=await qt.connect();try{await ye(async({store:s})=>{let a=await mi({bridge:i,store:s,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});$e(a)})}finally{await i.close().catch(()=>{})}}async function cR(e){let t=He(e),r=j(t,"interval"),n=j(t,"group-by"),o=j(t,"time-field");await ye(async({store:i})=>{$e(await i.eventKpis({interval:r,groupBy:n,timeField:o,from:j(t,"from"),to:j(t,"to"),platform:j(t,"platform"),eventType:j(t,"event-type"),target:j(t,"target")}))})}async function uR(e){let t=He(e),r=await ye(async({config:o,store:i,project:s})=>{let a=await Ny(i,{project:s,rootDir:o.rootDir});return{dashboard:a,artifact:Cy(a),defaultOut:qy(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){$e(r.dashboard);return}if(t.serve===!0){let o=j(t,"host")??"127.0.0.1",i=In(t,"port")??4738,s=await Oy(r.artifact.html,{host:o,port:i}),a=s.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>s.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=j(t,"out")??r.defaultOut;await Wz(Qz(n),{recursive:!0}),await Jz(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function lR(e){let t=He(e),r=j(t,"target")??t._[0],n=j(t,"message")??t._.slice(1).join(" ");if(!r)throw new Error("brain act requires --target <channel>");if(!n)throw new Error("brain act requires --message <text>");$e(await Ry({target:r,message:n}))}async function dR(e){let[t="SessionStart",...r]=e,n=He(r),o=j(n,"runner")??"unknown";$e(await Py(t,o))}function hi(e){return/^\d+$/.test(e)?Number(e):e}function He(e){let t={_:[]};for(let r=0;r<e.length;r++){let n=e[r];if(!n.startsWith("--")){t._.push(n);continue}let o=n.slice(2),i=e[r+1],s=i&&!i.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=s:Array.isArray(a)?a.push(String(s)):t[o]=[String(a),String(s)]}return t}function j(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function pR(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function In(e,t){let r=j(e,t);if(r==null)return;let n=Number(r);if(!Number.isFinite(n))throw new Error(`--${t} must be a number`);return n}function $e(e){console.log(JSON.stringify(e,null,2))}async function fR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function mR(){console.log(`brain commands:
277
279
  init
278
280
  status
279
281
  capture [text] --title <title> --kind <${ui.join("|")}> --tag <tag>
@@ -288,4 +290,4 @@ var By=Object.create;var _i=Object.defineProperty;var Ly=Object.getOwnPropertyDe
288
290
  kpi [--interval hour|day|week|month] [--group-by platform|event_type|target] [--time-field event|ingested] [--from T] [--to T] [--platform P] [--event-type T] [--target T]
289
291
  dashboard [--out PATH] [--json] [--serve] [--host 127.0.0.1] [--port 4738]
290
292
  outcome-event record [--root PATH] < event.json
291
- `)}HT().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
293
+ `)}Yz().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});