@reddb-io/red-skills 2.0.0

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.
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
+ var ay=Object.create;var as=Object.defineProperty;var cy=Object.getOwnPropertyDescriptor;var uy=Object.getOwnPropertyNames;var ly=Object.getPrototypeOf,dy=Object.prototype.hasOwnProperty;var st=(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),Yc=(e,t)=>{for(var r in t)as(e,r,{get:t[r],enumerable:!0})},py=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of uy(t))!dy.call(e,o)&&o!==r&&as(e,o,{get:()=>t[o],enumerable:!(n=cy(t,o))||n.enumerable});return e};var cs=(e,t,r)=>(r=e!=null?ay(ly(e)):{},py(t||!e||!e.__esModule?as(r,"default",{value:e,enumerable:!0}):r,e));var Vr=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.regexpCode=B.getEsmExportName=B.getProperty=B.safeStringify=B.stringify=B.strConcat=B.addCodeArg=B.str=B._=B.nil=B._Code=B.Name=B.IDENTIFIER=B._CodeOrName=void 0;var Fr=class{};B._CodeOrName=Fr;B.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var zt=class extends Fr{constructor(t){if(super(),!B.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}}};B.Name=zt;var Ae=class extends Fr{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),{})}};B._Code=Ae;B.nil=new Ae("");function xp(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Pi(r,t[n]),r.push(e[++n]);return new Ae(r)}B._=xp;var Ei=new Ae("+");function kp(e,...t){let r=[Kr(e[0])],n=0;for(;n<t.length;)r.push(Ei),Pi(r,t[n]),r.push(Ei,Kr(e[++n]));return mw(r),new Ae(r)}B.str=kp;function Pi(e,t){t instanceof Ae?e.push(...t._items):t instanceof zt?e.push(t):e.push(yw(t))}B.addCodeArg=Pi;function mw(e){let t=1;for(;t<e.length-1;){if(e[t]===Ei){let r=hw(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function hw(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 gw(e,t){return t.emptyStr()?e:e.emptyStr()?t:kp`${e}${t}`}B.strConcat=gw;function yw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Kr(Array.isArray(e)?e.join(","):e)}function _w(e){return new Ae(Kr(e))}B.stringify=_w;function Kr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}B.safeStringify=Kr;function vw(e){return typeof e=="string"&&B.IDENTIFIER.test(e)?new Ae(`.${e}`):xp`[${e}]`}B.getProperty=vw;function ww(e){if(typeof e=="string"&&B.IDENTIFIER.test(e))return new Ae(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}B.getEsmExportName=ww;function bw(e){return new Ae(e.toString())}B.regexpCode=bw});var Ii=v(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.ValueScope=xe.ValueScopeName=xe.Scope=xe.varKinds=xe.UsedValueState=void 0;var $e=Vr(),Ti=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},no;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(no||(xe.UsedValueState=no={}));xe.varKinds={const:new $e.Name("const"),let:new $e.Name("let"),var:new $e.Name("var")};var oo=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof $e.Name?t:this.name(t)}name(t){return new $e.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}}};xe.Scope=oo;var so=class extends $e.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,$e._)`.${new $e.Name(r)}[${n}]`}};xe.ValueScopeName=so;var $w=(0,$e._)`\n`,Ri=class extends oo{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?$w:$e.nil}}get(){return this._scope}name(t){return new so(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:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,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,$e._)`${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 s=$e.nil;for(let i in t){let a=t[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,no.Started);let u=r(l);if(u){let d=this.opts.es5?xe.varKinds.var:xe.varKinds.const;s=(0,$e._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,$e._)`${s}${u}${this.opts._n}`;else throw new Ti(l);c.set(l,no.Completed)})}return s}};xe.ValueScope=Ri});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=Vr(),Ze=Ii(),lt=Vr();Object.defineProperty(O,"_",{enumerable:!0,get:function(){return lt._}});Object.defineProperty(O,"str",{enumerable:!0,get:function(){return lt.str}});Object.defineProperty(O,"strConcat",{enumerable:!0,get:function(){return lt.strConcat}});Object.defineProperty(O,"nil",{enumerable:!0,get:function(){return lt.nil}});Object.defineProperty(O,"getProperty",{enumerable:!0,get:function(){return lt.getProperty}});Object.defineProperty(O,"stringify",{enumerable:!0,get:function(){return lt.stringify}});Object.defineProperty(O,"regexpCode",{enumerable:!0,get:function(){return lt.regexpCode}});Object.defineProperty(O,"Name",{enumerable:!0,get:function(){return lt.Name}});var uo=Ii();Object.defineProperty(O,"Scope",{enumerable:!0,get:function(){return uo.Scope}});Object.defineProperty(O,"ValueScope",{enumerable:!0,get:function(){return uo.ValueScope}});Object.defineProperty(O,"ValueScopeName",{enumerable:!0,get:function(){return uo.ValueScopeName}});Object.defineProperty(O,"varKinds",{enumerable:!0,get:function(){return uo.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 tt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Ni=class extends tt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Ze.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=Gt(this.rhs,t,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},io=class extends tt{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=Gt(this.rhs,t,r),this}get names(){let t=this.lhs instanceof q.Name?{}:{...this.lhs.names};return co(t,this.rhs)}},Ai=class extends io{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Ci=class extends tt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Oi=class extends tt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},ji=class extends tt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Di=class extends tt{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=Gt(this.code,t,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Hr=class extends tt{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 s=n[o];s.optimizeNames(t,r)||(xw(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Tt(t,r.names),{})}},rt=class extends Hr{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},qi=class extends Hr{},Ht=class extends rt{};Ht.kind="else";var Et=class e extends rt{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 Ht(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Sp(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=Gt(this.condition,t,r),this}get names(){let t=super.names;return co(t,this.condition),this.else&&Tt(t,this.else.names),t}};Et.kind="if";var Pt=class extends rt{};Pt.kind="for";var Zi=class extends Pt{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=Gt(this.iteration,t,r),this}get names(){return Tt(super.names,this.iteration.names)}},Mi=class extends Pt{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?Ze.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=co(super.names,this.from);return co(t,this.to)}},ao=class extends Pt{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=Gt(this.iterable,t,r),this}get names(){return Tt(super.names,this.iterable.names)}},Gr=class extends rt{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)}};Gr.kind="func";var Wr=class extends Hr{render(t){return"return "+super.render(t)}};Wr.kind="return";var Li=class extends rt{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&&Tt(t,this.catch.names),this.finally&&Tt(t,this.finally.names),t}},Jr=class extends rt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Jr.kind="catch";var Qr=class extends rt{render(t){return"finally"+super.render(t)}};Qr.kind="finally";var Bi=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
+ `:""},this._extScope=t,this._scope=new Ze.Scope({parent:t}),this._nodes=[new qi]}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 s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ni(t,s,n)),s}const(t,r,n){return this._def(Ze.varKinds.const,t,r,n)}let(t,r,n){return this._def(Ze.varKinds.let,t,r,n)}var(t,r,n){return this._def(Ze.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new io(t,r,n))}add(t,r){return this._leafNode(new Ai(t,O.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==q.nil&&this._leafNode(new Di(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 Et(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 Et(t))}else(){return this._elseNode(new Ht)}endIf(){return this._endBlockNode(Et,Ht)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Zi(t),r)}forRange(t,r,n,o,s=this.opts.es5?Ze.varKinds.var:Ze.varKinds.let){let i=this._scope.toName(t);return this._for(new Mi(s,i,r,n),()=>o(i))}forOf(t,r,n,o=Ze.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${i}.length`,a=>{this.var(s,(0,q._)`${i}[${a}]`),n(s)})}return this._for(new ao("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?Ze.varKinds.var:Ze.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,q._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new ao("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Pt)}label(t){return this._leafNode(new Ci(t))}break(t){return this._leafNode(new Oi(t))}return(t){let r=new Wr;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Wr)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Li;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new Jr(s),r(s)}return n&&(this._currNode=o.finally=new Qr,this.code(n)),this._endBlockNode(Jr,Qr)}throw(t){return this._leafNode(new ji(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 Gr(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Gr)}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 Et))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=Bi;function Tt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function co(e,t){return t instanceof q._CodeOrName?Tt(e,t.names):e}function Gt(e,t,r){if(e instanceof q.Name)return n(e);if(!o(e))return e;return new q._Code(e._items.reduce((s,i)=>(i instanceof q.Name&&(i=n(i)),i instanceof q._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof q._Code&&s._items.some(i=>i instanceof q.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function xw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Sp(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,q._)`!${Ui(e)}`}O.not=Sp;var kw=zp(O.operators.AND);function Sw(...e){return e.reduce(kw)}O.and=Sw;var zw=zp(O.operators.OR);function Ew(...e){return e.reduce(zw)}O.or=Ew;function zp(e){return(t,r)=>t===q.nil?r:r===q.nil?t:(0,q._)`${Ui(t)} ${e} ${Ui(r)}`}function Ui(e){return e instanceof q.Name?e:(0,q._)`(${e})`}});var M=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var V=C(),Pw=Vr();function Tw(e){let t={};for(let r of e)t[r]=!0;return t}j.toHash=Tw;function Rw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Tp(e,t),!Rp(t,e.self.RULES.all))}j.alwaysValidSchema=Rw;function Tp(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||Ap(e,`unknown keyword: "${s}"`)}j.checkUnknownRules=Tp;function Rp(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}j.schemaHasRules=Rp;function Iw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}j.schemaHasRulesButRef=Iw;function Nw({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,V._)`${r}`}return(0,V._)`${e}${t}${(0,V.getProperty)(n)}`}j.schemaRefOrVal=Nw;function Aw(e){return Ip(decodeURIComponent(e))}j.unescapeFragment=Aw;function Cw(e){return encodeURIComponent(Ki(e))}j.escapeFragment=Cw;function Ki(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Ki;function Ip(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Ip;function Ow(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}j.eachItem=Ow;function Ep({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof V.Name?(s instanceof V.Name?e(o,s,i):t(o,s,i),i):s instanceof V.Name?(t(o,i,s),s):r(s,i);return a===V.Name&&!(c instanceof V.Name)?n(o,c):c}}j.mergeEvaluated={props:Ep({mergeNames:(e,t,r)=>e.if((0,V._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,V._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,V._)`${r} || {}`).code((0,V._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,V._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,V._)`${r} || {}`),Vi(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Np}),items:Ep({mergeNames:(e,t,r)=>e.if((0,V._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,V._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,V._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,V._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Np(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,V._)`{}`);return t!==void 0&&Vi(e,r,t),r}j.evaluatedPropsToName=Np;function Vi(e,t,r){Object.keys(r).forEach(n=>e.assign((0,V._)`${t}${(0,V.getProperty)(n)}`,!0))}j.setEvaluated=Vi;var Pp={};function jw(e,t){return e.scopeValue("func",{ref:t,code:Pp[t.code]||(Pp[t.code]=new Pw._Code(t.code))})}j.useFunc=jw;var Fi;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Fi||(j.Type=Fi={}));function Dw(e,t,r){if(e instanceof V.Name){let n=t===Fi.Num;return r?n?(0,V._)`"[" + ${e} + "]"`:(0,V._)`"['" + ${e} + "']"`:n?(0,V._)`"/" + ${e}`:(0,V._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,V.getProperty)(e).toString():"/"+Ki(e)}j.getErrorPath=Dw;function Ap(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}j.checkStrictMode=Ap});var nt=v(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});var me=C(),qw={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")};Hi.default=qw});var Yr=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(),lo=M(),ve=nt();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 Zw(e,t=he.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=jp(e,t,r);n??(i||a)?Cp(s,c):Op(o,(0,L._)`[${c}]`)}he.reportError=Zw;function Mw(e,t=he.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=jp(e,t,r);Cp(o,a),s||i||Op(n,ve.default.vErrors)}he.reportExtraError=Mw;function Lw(e,t){e.assign(ve.default.errors,t),e.if((0,L._)`${ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,L._)`${ve.default.vErrors}.length`,t),()=>e.assign(ve.default.vErrors,null)))}he.resetErrorsCount=Lw;function Bw({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,ve.default.errors,a=>{e.const(i,(0,L._)`${ve.default.vErrors}[${a}]`),e.if((0,L._)`${i}.instancePath === undefined`,()=>e.assign((0,L._)`${i}.instancePath`,(0,L.strConcat)(ve.default.instancePath,s.errorPath))),e.assign((0,L._)`${i}.schemaPath`,(0,L.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,L._)`${i}.schema`,r),e.assign((0,L._)`${i}.data`,n))})}he.extendErrors=Bw;function Cp(e,t){let r=e.const("err",t);e.if((0,L._)`${ve.default.vErrors} === null`,()=>e.assign(ve.default.vErrors,(0,L._)`[${r}]`),(0,L._)`${ve.default.vErrors}.push(${r})`),e.code((0,L._)`${ve.default.errors}++`)}function Op(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 Rt={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 jp(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,L._)`{}`:Uw(e,t,r)}function Uw(e,t,r={}){let{gen:n,it:o}=e,s=[Fw(o,r),Kw(e,r)];return Vw(e,t,s),n.object(...s)}function Fw({errorPath:e},{instancePath:t}){let r=t?(0,L.str)`${e}${(0,lo.getErrorPath)(t,lo.Type.Str)}`:e;return[ve.default.instancePath,(0,L.strConcat)(ve.default.instancePath,r)]}function Kw({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,lo.getErrorPath)(r,lo.Type.Str)}`),[Rt.schemaPath,o]}function Vw(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Rt.keyword,o],[Rt.params,typeof t=="function"?t(e):t||(0,L._)`{}`]),c.messages&&n.push([Rt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Rt.schema,i],[Rt.parentSchema,(0,L._)`${u}${d}`],[ve.default.data,s]),l&&n.push([Rt.propertyName,l])}});var qp=v(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.boolOrEmptySchema=Wt.topBoolOrEmptySchema=void 0;var Hw=Yr(),Gw=C(),Ww=nt(),Jw={message:"boolean schema is false"};function Qw(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Dp(e,!1):typeof r=="object"&&r.$async===!0?t.return(Ww.default.data):(t.assign((0,Gw._)`${n}.errors`,null),t.return(!0))}Wt.topBoolOrEmptySchema=Qw;function Yw(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Dp(e)):r.var(t,!0)}Wt.boolOrEmptySchema=Yw;function Dp(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,Hw.reportError)(o,Jw,void 0,t)}});var Gi=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.getRules=Jt.isJSONType=void 0;var Xw=["string","number","integer","boolean","null","object","array"],eb=new Set(Xw);function tb(e){return typeof e=="string"&&eb.has(e)}Jt.isJSONType=tb;function rb(){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:{}}}Jt.getRules=rb});var Wi=v(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.shouldUseRule=dt.shouldUseGroup=dt.schemaHasRulesForType=void 0;function nb({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Zp(e,n)}dt.schemaHasRulesForType=nb;function Zp(e,t){return t.rules.some(r=>Mp(e,r))}dt.shouldUseGroup=Zp;function Mp(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))}dt.shouldUseRule=Mp});var Xr=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 ob=Gi(),sb=Wi(),ib=Yr(),A=C(),Lp=M(),Qt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Qt||(ge.DataType=Qt={}));function ab(e){let t=Bp(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=ab;function Bp(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(ob.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}ge.getJSONTypes=Bp;function cb(e,t){let{gen:r,data:n,opts:o}=e,s=ub(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,sb.schemaHasRulesForType)(e,t[0]));if(i){let a=Qi(t,n,o.strictNumbers,Qt.Wrong);r.if(a,()=>{s.length?lb(e,t,s):Yi(e)})}return i}ge.coerceAndCheckDataType=cb;var Up=new Set(["string","number","integer","boolean","null"]);function ub(e,t){return t?e.filter(r=>Up.has(r)||t==="array"&&r==="array"):[]}function lb(e,t,r){let{gen:n,data:o,opts:s}=e,i=n.let("dataType",(0,A._)`typeof ${o}`),a=n.let("coerced",(0,A._)`undefined`);s.coerceTypes==="array"&&n.if((0,A._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,A._)`${o}[0]`).assign(i,(0,A._)`typeof ${o}`).if(Qi(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,A._)`${a} !== undefined`);for(let l of r)(Up.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Yi(e),n.endIf(),n.if((0,A._)`${a} !== undefined`,()=>{n.assign(o,a),db(e,a)});function c(l){switch(l){case"string":n.elseIf((0,A._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":n.elseIf((0,A._)`${i} == "boolean" || ${o} === null
5
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":n.elseIf((0,A._)`${i} === "boolean" || ${o} === null
6
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":n.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,A._)`${i} === "string" || ${i} === "number"
7
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function db({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,A._)`${t} !== undefined`,()=>e.assign((0,A._)`${t}[${r}]`,n))}function Ji(e,t,r,n=Qt.Correct){let o=n===Qt.Correct?A.operators.EQ:A.operators.NEQ,s;switch(e){case"null":return(0,A._)`${t} ${o} null`;case"array":s=(0,A._)`Array.isArray(${t})`;break;case"object":s=(0,A._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,A._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,A._)`typeof ${t} ${o} ${e}`}return n===Qt.Correct?s:(0,A.not)(s);function i(a=A.nil){return(0,A.and)((0,A._)`typeof ${t} == "number"`,a,r?(0,A._)`isFinite(${t})`:A.nil)}}ge.checkDataType=Ji;function Qi(e,t,r,n){if(e.length===1)return Ji(e[0],t,r,n);let o,s=(0,Lp.toHash)(e);if(s.array&&s.object){let i=(0,A._)`typeof ${t} != "object"`;o=s.null?i:(0,A._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=A.nil;s.number&&delete s.integer;for(let i in s)o=(0,A.and)(o,Ji(i,t,r,n));return o}ge.checkDataTypes=Qi;var pb={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,A._)`{type: ${e}}`:(0,A._)`{type: ${t}}`};function Yi(e){let t=fb(e);(0,ib.reportError)(t,pb)}ge.reportTypeError=Yi;function fb(e){let{gen:t,data:r,schema:n}=e,o=(0,Lp.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Kp=v(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.assignDefaults=void 0;var Yt=C(),mb=M();function hb(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Fp(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Fp(e,s,o.default))}po.assignDefaults=hb;function Fp(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,Yt._)`${s}${(0,Yt.getProperty)(t)}`;if(o){(0,mb.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Yt._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Yt._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Yt._)`${a} = ${(0,Yt.stringify)(r)}`)}});var Ce=v(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var Y=C(),Xi=M(),pt=nt(),gb=M();function yb(e,t){let{gen:r,data:n,it:o}=e;r.if(ta(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Y._)`${t}`},!0),e.error()})}K.checkReportMissingProp=yb;function _b({gen:e,data:t,it:{opts:r}},n,o){return(0,Y.or)(...n.map(s=>(0,Y.and)(ta(e,t,s,r.ownProperties),(0,Y._)`${o} = ${s}`)))}K.checkMissingProp=_b;function vb(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=vb;function Vp(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Y._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Vp;function ea(e,t,r){return(0,Y._)`${Vp(e)}.call(${t}, ${r})`}K.isOwnProperty=ea;function wb(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} !== undefined`;return n?(0,Y._)`${o} && ${ea(e,t,r)}`:o}K.propertyInData=wb;function ta(e,t,r,n){let o=(0,Y._)`${t}${(0,Y.getProperty)(r)} === undefined`;return n?(0,Y.or)(o,(0,Y.not)(ea(e,t,r))):o}K.noPropertyInData=ta;function Hp(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=Hp;function bb(e,t){return Hp(t).filter(r=>!(0,Xi.alwaysValidSchema)(e,t[r]))}K.schemaProperties=bb;function $b({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Y._)`${e}, ${t}, ${n}${o}`:t,d=[[pt.default.instancePath,(0,Y.strConcat)(pt.default.instancePath,s)],[pt.default.parentData,i.parentData],[pt.default.parentDataProperty,i.parentDataProperty],[pt.default.rootData,pt.default.rootData]];i.opts.dynamicRef&&d.push([pt.default.dynamicAnchors,pt.default.dynamicAnchors]);let p=(0,Y._)`${u}, ${r.object(...d)}`;return c!==Y.nil?(0,Y._)`${a}.call(${c}, ${p})`:(0,Y._)`${a}(${p})`}K.callValidateCode=$b;var xb=(0,Y._)`new RegExp`;function kb({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Y._)`${o.code==="new RegExp"?xb:(0,gb.useFunc)(e,o)}(${r}, ${n})`})}K.usePattern=kb;function Sb(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,Y._)`${r}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:n,dataProp:l,dataPropType:Xi.Type.Num},s),t.if((0,Y.not)(s),a)})}}K.validateArray=Sb;function zb(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,Xi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=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(i,(0,Y._)`${i} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,Y.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}K.validateUnion=zb});var Jp=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.validateKeywordUsage=He.validSchemaType=He.funcKeywordCode=He.macroKeywordCode=void 0;var we=C(),It=nt(),Eb=Ce(),Pb=Yr();function Tb(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=Wp(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:we.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}He.macroKeywordCode=Tb;function Rb(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;Nb(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,u=Wp(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&&Gp(e),_(()=>e.error());else{let w=t.async?f():h();t.modifying&&Gp(e),_(()=>Ib(e,w))}}function f(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,we._)`await `),b=>n.assign(d,!1).if((0,we._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,we._)`${b}.errors`),()=>n.throw(b))),w}function h(){let w=(0,we._)`${u}.errors`;return n.assign(w,null),g(we.nil),w}function g(w=t.async?(0,we._)`await `:we.nil){let b=c.opts.passContext?It.default.this:It.default.self,$=!("compile"in t&&!a||t.schema===!1);n.assign(d,(0,we._)`${w}${(0,Eb.callValidateCode)(e,u,b,$)}`,t.modifying)}function _(w){var b;n.if((0,we.not)((b=t.valid)!==null&&b!==void 0?b:d),w)}}He.funcKeywordCode=Rb;function Gp(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,we._)`${n.parentData}[${n.parentDataProperty}]`))}function Ib(e,t){let{gen:r}=e;r.if((0,we._)`Array.isArray(${t})`,()=>{r.assign(It.default.vErrors,(0,we._)`${It.default.vErrors} === null ? ${t} : ${It.default.vErrors}.concat(${t})`).assign(It.default.errors,(0,we._)`${It.default.vErrors}.length`),(0,Pb.extendErrors)(e)},()=>e.error())}function Nb({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Wp(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,we.stringify)(r)})}function Ab(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")}He.validSchemaType=Ab;function Cb({schema:e,opts:t,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}He.validateKeywordUsage=Cb});var Yp=v(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.extendSubschemaMode=ft.extendSubschemaData=ft.getSubschema=void 0;var Ge=C(),Qp=M();function Ob(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){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,Ge._)`${e.schemaPath}${(0,Ge.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Ge._)`${e.schemaPath}${(0,Ge.getProperty)(t)}${(0,Ge.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Qp.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ft.getSubschema=Ob;function jb(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,p=a.let("data",(0,Ge._)`${t.data}${(0,Ge.getProperty)(r)}`,!0);c(p),e.errorPath=(0,Ge.str)`${l}${(0,Qp.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Ge._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let l=o instanceof Ge.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);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]}}ft.extendSubschemaData=jb;function Db(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}ft.extendSubschemaMode=Db});var ra=v((xC,Xp)=>{"use strict";Xp.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,s;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(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var tf=v((kC,ef)=>{"use strict";var mt=ef.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(){};fo(t,n,o,e,"",e)};mt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function fo(e,t,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in mt.arrayKeywords)for(var p=0;p<d.length;p++)fo(e,t,r,d[p],o+"/"+u+"/"+p,s,o,u,n,p)}else if(u in mt.propsKeywords){if(d&&typeof d=="object")for(var f in d)fo(e,t,r,d[f],o+"/"+u+"/"+qb(f),s,o,u,n,f)}else(u in mt.keywords||e.allKeys&&!(u in mt.skipKeywords))&&fo(e,t,r,d,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function qb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var en=v(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.getSchemaRefs=ke.resolveUrl=ke.normalizeId=ke._getFullPath=ke.getFullPath=ke.inlineRef=void 0;var Zb=M(),Mb=ra(),Lb=tf(),Bb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Ub(e,t=!0){return typeof e=="boolean"?!0:t===!0?!na(e):t?rf(e)<=t:!1}ke.inlineRef=Ub;var Fb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function na(e){for(let t in e){if(Fb.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(na)||typeof r=="object"&&na(r))return!0}return!1}function rf(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Bb.has(r)&&(typeof e[r]=="object"&&(0,Zb.eachItem)(e[r],n=>t+=rf(n)),t===1/0))return 1/0}return t}function nf(e,t="",r){r!==!1&&(t=Xt(t));let n=e.parse(t);return of(e,n)}ke.getFullPath=nf;function of(e,t){return e.serialize(t).split("#")[0]+"#"}ke._getFullPath=of;var Kb=/#\/?$/;function Xt(e){return e?e.replace(Kb,""):""}ke.normalizeId=Xt;function Vb(e,t,r){return r=Xt(r),e.resolve(t,r)}ke.resolveUrl=Vb;var Hb=/^[a-z_][-a-z0-9._]*$/i;function Gb(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xt(e[r]||t),s={"":o},i=nf(n,o,!1),a={},c=new Set;return Lb(e,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let g=i+p,_=s[h];typeof d[r]=="string"&&(_=w.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[p]=_;function w($){let E=this.opts.uriResolver.resolve;if($=Xt(_?E(_,$):$),c.has($))throw u($);c.add($);let T=this.refs[$];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?l(d,T.schema,$):$!==Xt(g)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=g),$}function b($){if(typeof $=="string"){if(!Hb.test($))throw new Error(`invalid anchor "${$}"`);w.call(this,`#${$}`)}}}),a;function l(d,p,f){if(p!==void 0&&!Mb(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ke.getSchemaRefs=Gb});var nn=v(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.getData=ht.KeywordCxt=ht.validateFunctionCode=void 0;var lf=qp(),sf=Xr(),sa=Wi(),mo=Xr(),Wb=Kp(),rn=Jp(),oa=Yp(),S=C(),N=nt(),Jb=en(),ot=M(),tn=Yr();function Qb(e){if(ff(e)&&(mf(e),pf(e))){e$(e);return}df(e,()=>(0,lf.topBoolOrEmptySchema)(e))}ht.validateFunctionCode=Qb;function df({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,S._)`${N.default.data}, ${N.default.valCxt}`,n.$async,()=>{e.code((0,S._)`"use strict"; ${af(r,o)}`),Xb(e,o),e.code(s)}):e.func(t,(0,S._)`${N.default.data}, ${Yb(o)}`,n.$async,()=>e.code(af(r,o)).code(s))}function Yb(e){return(0,S._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${e.dynamicRef?(0,S._)`, ${N.default.dynamicAnchors}={}`:S.nil}}={}`}function Xb(e,t){e.if(N.default.valCxt,()=>{e.var(N.default.instancePath,(0,S._)`${N.default.valCxt}.${N.default.instancePath}`),e.var(N.default.parentData,(0,S._)`${N.default.valCxt}.${N.default.parentData}`),e.var(N.default.parentDataProperty,(0,S._)`${N.default.valCxt}.${N.default.parentDataProperty}`),e.var(N.default.rootData,(0,S._)`${N.default.valCxt}.${N.default.rootData}`),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,S._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{e.var(N.default.instancePath,(0,S._)`""`),e.var(N.default.parentData,(0,S._)`undefined`),e.var(N.default.parentDataProperty,(0,S._)`undefined`),e.var(N.default.rootData,N.default.data),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,S._)`{}`)})}function e$(e){let{schema:t,opts:r,gen:n}=e;df(e,()=>{r.$comment&&t.$comment&&gf(e),s$(e),n.let(N.default.vErrors,null),n.let(N.default.errors,0),r.unevaluated&&t$(e),hf(e),c$(e)})}function t$(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 af(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 r$(e,t){if(ff(e)&&(mf(e),pf(e))){n$(e,t);return}(0,lf.boolOrEmptySchema)(e,t)}function pf({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 ff(e){return typeof e.schema!="boolean"}function n$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&gf(e),i$(e),a$(e);let s=n.const("_errs",N.default.errors);hf(e,s),n.var(t,(0,S._)`${s} === ${N.default.errors}`)}function mf(e){(0,ot.checkUnknownRules)(e),o$(e)}function hf(e,t){if(e.opts.jtd)return cf(e,[],!1,t);let r=(0,sf.getSchemaTypes)(e.schema),n=(0,sf.coerceAndCheckDataType)(e,r);cf(e,r,!n,t)}function o$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function s$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ot.checkStrictMode)(e,"default is ignored in the schema root")}function i$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Jb.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function a$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function gf({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,S._)`${N.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,S.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,S._)`${N.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function c$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,S._)`${N.default.errors} === 0`,()=>t.return(N.default.data),()=>t.throw((0,S._)`new ${o}(${N.default.vErrors})`)):(t.assign((0,S._)`${n}.errors`,N.default.vErrors),s.unevaluated&&u$(e),t.return((0,S._)`${N.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 cf(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(s,u))){o.block(()=>_f(e,"$ref",u.all.$ref.definition));return}c.jtd||l$(e,t),o.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,sa.shouldUseGroup)(s,p)&&(p.type?(o.if((0,mo.checkDataType)(p.type,i,c.strictNumbers)),uf(e,p),t.length===1&&t[0]===p.type&&r&&(o.else(),(0,mo.reportTypeError)(e)),o.endIf()):uf(e,p),a||o.if((0,S._)`${N.default.errors} === ${n||0}`))}}function uf(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,Wb.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,sa.shouldUseRule)(n,s)&&_f(e,s.keyword,s.definition,t.type)})}function l$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(d$(e,t),e.opts.allowUnionTypes||p$(e,t),f$(e,e.dataTypes))}function d$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{yf(e.dataTypes,r)||ia(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),h$(e,t)}}function p$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&ia(e,"use allowUnionTypes to allow union type keyword")}function f$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,sa.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>m$(t,i))&&ia(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function m$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function yf(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function h$(e,t){let r=[];for(let n of e.dataTypes)yf(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function ia(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ot.checkStrictMode)(e,t,e.opts.strictTypes)}var ho=class{constructor(t,r,n){if((0,rn.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,ot.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",vf(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,rn.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",N.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?tn.reportExtraError:tn.reportError)(this,this.def.error,r)}$dataError(){(0,tn.reportError)(this,this.def.$dataError||tn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,tn.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:s,def:i}=this;n.if((0,S.or)((0,S._)`${o} === undefined`,r)),t!==S.nil&&n.assign(t,!0),(s.length||i.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:s}=this;return(0,S.or)(i(),a());function i(){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,mo.checkDataTypes)(c,r,s.opts.strictNumbers,mo.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,oa.getSubschema)(this.it,t);(0,oa.extendSubschemaData)(n,this.it,t),(0,oa.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return r$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=ot.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=ot.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}};ht.KeywordCxt=ho;function _f(e,t,r,n){let o=new ho(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,rn.funcKeywordCode)(o,r):"macro"in r?(0,rn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,rn.funcKeywordCode)(o,r)}var g$=/^\/(?:[^~]|~0|~1)*$/,y$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vf(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!g$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=N.default.rootData}else{let l=y$.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(s=r[t-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,S._)`${s}${(0,S.getProperty)((0,ot.unescapeJsonPointer)(l))}`,i=(0,S._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}ht.getData=vf});var go=v(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});var aa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};ca.default=aa});var on=v(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});var ua=en(),la=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,ua.resolveUrl)(t,r,n),this.missingSchema=(0,ua.normalizeId)((0,ua.getFullPath)(t,this.missingRef))}};da.default=la});var _o=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Me=C(),_$=go(),Nt=nt(),Le=en(),wf=M(),v$=nn(),er=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,Le.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=er;function fa(e){let t=bf.call(this,e);if(t)return t;let r=(0,Le.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Me.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:_$.default,code:(0,Me._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Nt.default.data,parentData:Nt.default.parentData,parentDataProperty:Nt.default.parentDataProperty,dataNames:[Nt.default.data],dataPathArr:[Me.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Me.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Me.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Me._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,v$.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Nt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let f=new Function(`${Nt.default.self}`,`${Nt.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:i._values}),this.opts.unevaluated){let{props:h,items:g}=l;f.evaluated={props:h instanceof Me.Name?void 0:h,items:g instanceof Me.Name?void 0:g,dynamicProps:h instanceof Me.Name,dynamicItems:g instanceof Me.Name},f.source&&(f.source.evaluated=(0,Me.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=fa;function w$(e,t,r){var n;r=(0,Le.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=x$.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new er({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=b$.call(this,s)}Oe.resolveRef=w$;function b$(e){return(0,Le.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:fa.call(this,e)}function bf(e){for(let t of this._compilations)if($$(t,e))return t}Oe.getCompilingSchema=bf;function $$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function x$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yo.call(this,e,t)}function yo(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Le._getFullPath)(this.opts.uriResolver,r),o=(0,Le.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return pa.call(this,r,e);let s=(0,Le.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=yo.call(this,e,i);return typeof a?.schema!="object"?void 0:pa.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||fa.call(this,i),s===(0,Le.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Le.resolveUrl)(this.opts.uriResolver,o,l)),new er({schema:a,schemaId:c,root:e,baseId:o})}return pa.call(this,r,i)}}Oe.resolveSchema=yo;var k$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function pa(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,wf.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!k$.has(a)&&l&&(t=(0,Le.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,wf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Le.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=yo.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new er({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var $f=v((RC,S$)=>{S$.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 ga=v((IC,Pf)=>{"use strict";var z$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kf=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),ma=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Sf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),E$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ha(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 P$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function xf(e){return e.length=0,!0}function T$(e,t,r){if(e.length){let n=ha(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function R$(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=T$;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=xf}else{o.push(l);continue}}return o.length&&(a===xf?r.zone=o.join(""):i?n.push(o.join("")):n.push(ha(o))),r.address=n.join(""),r}function zf(e){if(I$(e,":")<2)return{host:e,isIPV6:!1};let t=R$(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 I$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function N$(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 A$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},C$=/[@/?#:]/g,O$=/[@/?#]/g;function Ef(e,t){let r=t?O$:C$;return r.lastIndex=0,e.replace(r,n=>A$[n])}function j$(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(ma(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Sf(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function D$(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(ma(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Sf(s)?t+=s:t+="%"+o,r+=2;continue}}E$(e[r])?t+=e[r]:t+=escape(e[r])}return t}function q$(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(ma(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Z$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!kf(r)){let n=zf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Ef(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}Pf.exports={nonSimpleDomain:P$,recomposeAuthority:Z$,reescapeHostDelimiters:Ef,normalizePercentEncoding:j$,normalizePathEncoding:D$,escapePreservingEscapes:q$,removeDotSegments:N$,isIPv4:kf,isUUID:z$,normalizeIPv6:zf,stringArrayToHexStripped:ha}});var Af=v((NC,Nf)=>{"use strict";var{isUUID:M$}=ga(),L$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,B$=["http","https","ws","wss","urn","urn:uuid"];function U$(e){return B$.indexOf(e)!==-1}function ya(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 Tf(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Rf(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 F$(e){return e.secure=ya(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function K$(e){if((e.port===(ya(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 V$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(L$);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}`,s=_a(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function H$(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}`,s=_a(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function G$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!M$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function W$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var If={scheme:"http",domainHost:!0,parse:Tf,serialize:Rf},J$={scheme:"https",domainHost:If.domainHost,parse:Tf,serialize:Rf},vo={scheme:"ws",domainHost:!0,parse:F$,serialize:K$},Q$={scheme:"wss",domainHost:vo.domainHost,parse:vo.parse,serialize:vo.serialize},Y$={scheme:"urn",parse:V$,serialize:H$,skipNormalize:!0},X$={scheme:"urn:uuid",parse:G$,serialize:W$,skipNormalize:!0},wo={http:If,https:J$,ws:vo,wss:Q$,urn:Y$,"urn:uuid":X$};Object.setPrototypeOf(wo,null);function _a(e){return e&&(wo[e]||wo[e.toLowerCase()])||void 0}Nf.exports={wsIsSecure:ya,SCHEMES:wo,isValidSchemeName:U$,getSchemeHandler:_a}});var Zf=v((AC,bo)=>{"use strict";var{normalizeIPv6:e0,removeDotSegments:sn,recomposeAuthority:t0,normalizePercentEncoding:r0,normalizePathEncoding:n0,escapePreservingEscapes:o0,reescapeHostDelimiters:s0,isIPv4:i0,nonSimpleDomain:a0}=ga(),{SCHEMES:c0,getSchemeHandler:Of}=Af();function u0(e,t){return typeof e=="string"?e=m0(e,t):typeof e=="object"&&(e=tr(At(e,t),t)),e}function l0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=jf(tr(e,n),tr(t,n),n,!0);return n.skipEscape=!0,At(o,n)}function jf(e,t,r,n){let o={};return n||(e=tr(At(e,r),r),t=tr(At(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=sn(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=sn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=sn(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=sn(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 d0(e,t,r){let n=Cf(e,r),o=Cf(t,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function At(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=[],s=Of(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=r0(r.path):(r.path=o0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=t0(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=sn(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var p0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f0(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 Df(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,s=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(p0);if(i){n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]);let a=f0(n,i);if(a!==void 0&&(n.error=n.error||a,o=!0),n.host)if(i0(n.host)===!1){let u=e0(n.host);n.host=u.host.toLowerCase(),s=u.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let c=Of(r.scheme||n.scheme);if(!r.unicodeSupport&&(!c||!c.unicodeSupport)&&n.host&&(r.domainHost||c&&c.domainHost)&&s===!1&&a0(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=s0(unescape(n.host),s))),n.path&&(n.path=n0(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 tr(e,t){return Df(e,t).parsed}function m0(e,t){return qf(e,t).normalized}function qf(e,t){let{parsed:r,malformedAuthorityOrPort:n}=Df(e,t);return{normalized:n?e:At(r,t),malformedAuthorityOrPort:n}}function Cf(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=qf(e,t);return n?void 0:r}if(typeof e=="object")return At(e,t)}var va={SCHEMES:c0,normalize:u0,resolve:l0,resolveComponent:jf,equal:d0,serialize:At,parse:tr};bo.exports=va;bo.exports.default=va;bo.exports.fastUri=va});var Lf=v(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});var Mf=Zf();Mf.code='require("ajv/dist/runtime/uri").default';wa.default=Mf});var Wf=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 h0=nn();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return h0.KeywordCxt}});var rr=C();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return rr._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return rr.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return rr.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return rr.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return rr.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return rr.CodeGen}});var g0=go(),Vf=on(),y0=Gi(),an=_o(),_0=C(),cn=en(),$o=Xr(),$a=M(),Bf=$f(),v0=Lf(),Hf=(e,t)=>new RegExp(e,t);Hf.code="new RegExp";var w0=["removeAdditional","useDefaults","coerceTypes"],b0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),$0={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."},x0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Uf=200;function k0(e){var t,r,n,o,s,i,a,c,l,u,d,p,f,h,g,_,w,b,$,E,T,ye,Te,Mt,ss;let br=e.strict,is=(t=e.code)===null||t===void 0?void 0:t.optimize,Jc=is===!0||is===void 0?1:is||0,Qc=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Hf,iy=(o=e.uriResolver)!==null&&o!==void 0?o:v0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:br)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:br)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:br)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:br)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=e.strictRequired)!==null&&f!==void 0?f:br)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:Jc,regExp:Qc}:{optimize:Jc,regExp:Qc},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Uf,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Uf,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:(E=e.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(T=e.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(ye=e.validateSchema)!==null&&ye!==void 0?ye:!0,validateFormats:(Te=e.validateFormats)!==null&&Te!==void 0?Te:!0,unicodeRegExp:(Mt=e.unicodeRegExp)!==null&&Mt!==void 0?Mt:!0,int32range:(ss=e.int32range)!==null&&ss!==void 0?ss:!0,uriResolver:iy}}var un=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,...k0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new _0.ValueScope({scope:{},prefixes:b0,es5:r,lines:n}),this.logger=R0(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,y0.getRules)(),Ff.call(this,$0,t,"NOT SUPPORTED"),Ff.call(this,x0,t,"DEPRECATED","warn"),this._metaOpts=P0.call(this),t.formats&&z0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&E0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),S0.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Bf;n==="id"&&(o={...Bf},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 s.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||i.call(this,p)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Vf.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.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 s.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 i of t)this.addSchema(i,void 0,n,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,cn.normalizeId)(r||s),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 s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let r;for(;typeof(r=Kf.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new an.SchemaEnv({schema:{},schemaId:n});if(r=an.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=Kf.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,cn.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(N0.call(this,n,r),!r)return(0,$a.eachItem)(n,s=>ba.call(this,s)),this;C0.call(this,r);let o={...r,type:(0,$o.getJSONTypes)(r.type),schemaType:(0,$o.getJSONTypes)(r.schemaType)};return(0,$a.eachItem)(n,o.type.length===0?s=>ba.call(this,s,o):s=>o.type.forEach(i=>ba.call(this,s,o,i))),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(s=>s.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,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=Gf(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,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=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,cn.normalizeId)(i||n);let l=cn.getSchemaRefs.call(this,t,n);return c=new an.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!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):an.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{an.compileSchema.call(this,t)}finally{this.opts=r}}};un.ValidationError=g0.default;un.MissingRefError=Vf.default;de.default=un;function Ff(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function Kf(e){return e=(0,cn.normalizeId)(e),this.schemas[e]||this.refs[e]}function S0(){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 z0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function E0(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 P0(){let e={...this.opts};for(let t of w0)delete e[t];return e}var T0={log(){},warn(){},error(){}};function R0(e){if(e===!1)return T0;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 I0=/^[a-z_$][a-z0-9_$:-]*$/i;function N0(e,t){let{RULES:r}=this;if((0,$a.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!I0.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 ba(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,$o.getJSONTypes)(t.type),schemaType:(0,$o.getJSONTypes)(t.schemaType)}};t.before?A0.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function A0(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 C0(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Gf(t)),e.validateSchema=this.compile(t,!0))}var O0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Gf(e){return{anyOf:[e,O0]}}});var Jf=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});var j0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};xa.default=j0});var em=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.callRef=Ct.getValidate=void 0;var D0=on(),Qf=Ce(),Se=C(),nr=nt(),Yf=_o(),xo=M(),q0={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return d();let u=Yf.resolveRef.call(c,l,o,r);if(u===void 0)throw new D0.default(n.opts.uriResolver,o,r);if(u instanceof Yf.SchemaEnv)return p(u);return f(u);function d(){if(s===l)return ko(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return ko(e,(0,Se._)`${h}.validate`,l,l.$async)}function p(h){let g=Xf(e,h);ko(e,g,h,h.$async)}function f(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Se.stringify)(h)}:{ref:h}),_=t.name("valid"),w=e.subschema({schema:h,dataTypes:[],schemaPath:Se.nil,topSchemaRef:g,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Xf(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Se._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ct.getValidate=Xf;function ko(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?nr.default.this:Se.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,Se._)`await ${(0,Qf.callValidateCode)(e,t,l)}`),f(t),i||o.assign(h,!0)},g=>{o.if((0,Se._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(h,!1)}),e.ok(h)}function d(){e.result((0,Qf.callValidateCode)(e,t,l),()=>f(t),()=>p(t))}function p(h){let g=(0,Se._)`${h}.errors`;o.assign(nr.default.vErrors,(0,Se._)`${nr.default.vErrors} === null ? ${g} : ${nr.default.vErrors}.concat(${g})`),o.assign(nr.default.errors,(0,Se._)`${nr.default.vErrors}.length`)}function f(h){var g;if(!s.opts.unevaluated)return;let _=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(s.props=xo.mergeEvaluated.props(o,_.props,s.props));else{let w=o.var("props",(0,Se._)`${h}.evaluated.props`);s.props=xo.mergeEvaluated.props(o,w,s.props,Se.Name)}if(s.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(s.items=xo.mergeEvaluated.items(o,_.items,s.items));else{let w=o.var("items",(0,Se._)`${h}.evaluated.items`);s.items=xo.mergeEvaluated.items(o,w,s.items,Se.Name)}}}Ct.callRef=ko;Ct.default=q0});var tm=v(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});var Z0=Jf(),M0=em(),L0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Z0.default,M0.default];ka.default=L0});var rm=v(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});var So=C(),gt=So.operators,zo={maximum:{okStr:"<=",ok:gt.LTE,fail:gt.GT},minimum:{okStr:">=",ok:gt.GTE,fail:gt.LT},exclusiveMaximum:{okStr:"<",ok:gt.LT,fail:gt.GTE},exclusiveMinimum:{okStr:">",ok:gt.GT,fail:gt.LTE}},B0={message:({keyword:e,schemaCode:t})=>(0,So.str)`must be ${zo[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,So._)`{comparison: ${zo[e].okStr}, limit: ${t}}`},U0={keyword:Object.keys(zo),type:"number",schemaType:"number",$data:!0,error:B0,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,So._)`${r} ${zo[t].fail} ${n} || isNaN(${r})`)}};Sa.default=U0});var nm=v(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var ln=C(),F0={message:({schemaCode:e})=>(0,ln.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ln._)`{multipleOf: ${e}}`},K0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:F0,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,ln._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ln._)`${i} !== parseInt(${i})`;e.fail$data((0,ln._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};za.default=K0});var sm=v(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});function om(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}Ea.default=om;om.code='require("ajv/dist/runtime/ucs2length").default'});var im=v(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var Ot=C(),V0=M(),H0=sm(),G0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Ot.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Ot._)`{limit: ${e}}`},W0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:G0,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?Ot.operators.GT:Ot.operators.LT,i=o.opts.unicode===!1?(0,Ot._)`${r}.length`:(0,Ot._)`${(0,V0.useFunc)(e.gen,H0.default)}(${r})`;e.fail$data((0,Ot._)`${i} ${s} ${n}`)}};Pa.default=W0});var am=v(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var J0=Ce(),Q0=M(),or=C(),Y0={message:({schemaCode:e})=>(0,or.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,or._)`{pattern: ${e}}`},X0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Y0,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,or._)`new RegExp`:(0,Q0.useFunc)(t,c),u=t.let("valid");t.try(()=>t.assign(u,(0,or._)`${l}(${s}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data((0,or._)`!${u}`)}else{let c=(0,J0.usePattern)(e,o);e.fail$data((0,or._)`!${c}.test(${r})`)}}};Ta.default=X0});var cm=v(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});var dn=C(),ex={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,dn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,dn._)`{limit: ${e}}`},tx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ex,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?dn.operators.GT:dn.operators.LT;e.fail$data((0,dn._)`Object.keys(${r}).length ${o} ${n}`)}};Ra.default=tx});var um=v(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var pn=Ce(),fn=C(),rx=M(),nx={message:({params:{missingProperty:e}})=>(0,fn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,fn._)`{missingProperty: ${e}}`},ox={keyword:"required",type:"object",schemaType:"array",$data:!0,error:nx,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.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 _=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${g}" is not defined at "${_}" (strictRequired)`;(0,rx.checkStrictMode)(i,w,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(fn.nil,d);else for(let f of r)(0,pn.checkReportMissingProp)(e,f)}function u(){let f=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>p(f,h)),e.ok(h)}else t.if((0,pn.checkMissingProp)(e,r,f)),(0,pn.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",n,f=>{e.setParams({missingProperty:f}),t.if((0,pn.noPropertyInData)(t,o,f,a.ownProperties),()=>e.error())})}function p(f,h){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(h,(0,pn.propertyInData)(t,o,f,a.ownProperties)),t.if((0,fn.not)(h),()=>{e.error(),t.break()})},fn.nil)}}};Ia.default=ox});var lm=v(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});var mn=C(),sx={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,mn.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,mn._)`{limit: ${e}}`},ix={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:sx,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?mn.operators.GT:mn.operators.LT;e.fail$data((0,mn._)`${r}.length ${o} ${n}`)}};Na.default=ix});var Eo=v(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});var dm=ra();dm.code='require("ajv/dist/runtime/equal").default';Aa.default=dm});var pm=v(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Ca=Xr(),pe=C(),ax=M(),cx=Eo(),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}}`},lx={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ux,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),l=s.items?(0,Ca.getSchemaTypes)(s.items):[];e.block$data(c,u,(0,pe._)`${i} === 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,Ca.checkDataTypes)(l,_,a.opts.strictNumbers,Ca.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,ax.useFunc)(t,cx.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)})))}}};Oa.default=lx});var fm=v(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var ja=C(),dx=M(),px=Eo(),fx={message:"must be equal to constant",params:({schemaCode:e})=>(0,ja._)`{allowedValue: ${e}}`},mx={keyword:"const",$data:!0,error:fx,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,ja._)`!${(0,dx.useFunc)(t,px.default)}(${r}, ${o})`):e.fail((0,ja._)`${s} !== ${r}`)}};Da.default=mx});var mm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var hn=C(),hx=M(),gx=Eo(),yx={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,hn._)`{allowedValues: ${e}}`},_x={keyword:"enum",schemaType:"array",$data:!0,error:yx,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,hx.useFunc)(t,gx.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",s);u=(0,hn.or)(...o.map((h,g)=>p(f,g)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",s,f=>t.if((0,hn._)`${l()}(${r}, ${f})`,()=>t.assign(u,!0).break()))}function p(f,h){let g=o[h];return typeof g=="object"&&g!==null?(0,hn._)`${l()}(${r}, ${f}[${h}])`:(0,hn._)`${r} === ${g}`}}};qa.default=_x});var hm=v(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var vx=rm(),wx=nm(),bx=im(),$x=am(),xx=cm(),kx=um(),Sx=lm(),zx=pm(),Ex=fm(),Px=mm(),Tx=[vx.default,wx.default,bx.default,$x.default,xx.default,kx.default,Sx.default,zx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ex.default,Px.default];Za.default=Tx});var La=v(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.validateAdditionalItems=void 0;var jt=C(),Ma=M(),Rx={message:({params:{len:e}})=>(0,jt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,jt._)`{limit: ${e}}`},Ix={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Rx,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Ma.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gm(e,n)}};function gm(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,jt._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,jt._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Ma.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,jt._)`${a} <= ${t.length}`);r.if((0,jt.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:Ma.Type.Num},l),i.allErrors||r.if((0,jt.not)(l),()=>r.break())})}}gn.validateAdditionalItems=gm;gn.default=Ix});var Ba=v(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateTuple=void 0;var ym=C(),Po=M(),Nx=Ce(),Ax={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _m(e,"additionalItems",t);r.items=!0,!(0,Po.alwaysValidSchema)(r,t)&&e.ok((0,Nx.validateArray)(e))}};function _m(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Po.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,ym._)`${s}.length`);r.forEach((d,p)=>{(0,Po.alwaysValidSchema)(a,d)||(n.if((0,ym._)`${l} > ${p}`,()=>e.subschema({keyword:i,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 _=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Po.checkStrictMode)(a,_,p.strictTuples)}}}yn.validateTuple=_m;yn.default=Ax});var vm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var Cx=Ba(),Ox={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Cx.validateTuple)(e,"items")};Ua.default=Ox});var bm=v(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var wm=C(),jx=M(),Dx=Ce(),qx=La(),Zx={message:({params:{len:e}})=>(0,wm.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,wm._)`{limit: ${e}}`},Mx={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Zx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,jx.alwaysValidSchema)(n,t)&&(o?(0,qx.validateAdditionalItems)(e,o):e.ok((0,Dx.validateArray)(e)))}};Fa.default=Mx});var $m=v(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var je=C(),To=M(),Lx={message:({params:{min:e,max:t}})=>t===void 0?(0,je.str)`must contain at least ${e} valid item(s)`:(0,je.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,je._)`{minContains: ${e}}`:(0,je._)`{minContains: ${e}, maxContains: ${t}}`},Bx={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Lx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=t.const("len",(0,je._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,To.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,To.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,To.alwaysValidSchema)(s,r)){let g=(0,je._)`${u} >= ${i}`;a!==void 0&&(g=(0,je._)`${g} && ${u} <= ${a}`),e.pass(g);return}s.items=!0;let d=t.name("valid");a===void 0&&i===1?f(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,!0),a!==void 0&&t.if((0,je._)`${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:To.Type.Num,compositeRule:!0},g),_()})}function h(g){t.code((0,je._)`${g}++`),a===void 0?t.if((0,je._)`${g} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,je._)`${g} > ${a}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,je._)`${g} >= ${i}`,()=>t.assign(d,!0)))}}};Ka.default=Bx});var Sm=v(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.validateSchemaDeps=We.validatePropertyDeps=We.error=void 0;var Va=C(),Ux=M(),_n=Ce();We.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Va.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Va._)`{property: ${e},
8
+ missingProperty: ${n},
9
+ depsCount: ${t},
10
+ deps: ${r}}`};var Fx={keyword:"dependencies",type:"object",schemaType:"object",error:We.error,code(e){let[t,r]=Kx(e);xm(e,t),km(e,r)}};function Kx({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 xm(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,_n.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,_n.checkReportMissingProp)(e,l)}):(r.if((0,Va._)`${c} && (${(0,_n.checkMissingProp)(e,a,s)})`),(0,_n.reportMissingProp)(e,s),r.else())}}We.validatePropertyDeps=xm;function km(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,Ux.alwaysValidSchema)(s,t[a])||(r.if((0,_n.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i))}We.validateSchemaDeps=km;We.default=Fx});var Em=v(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var zm=C(),Vx=M(),Hx={message:"property name must be valid",params:({params:e})=>(0,zm._)`{propertyName: ${e.propertyName}}`},Gx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Hx,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,Vx.alwaysValidSchema)(o,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,zm.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Ha.default=Gx});var Wa=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Ro=Ce(),Be=C(),Wx=nt(),Io=M(),Jx={message:"must NOT have additional properties",params:({params:e})=>(0,Be._)`{additionalProperty: ${e.additionalProperty}}`},Qx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Jx,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Io.alwaysValidSchema)(i,r))return;let l=(0,Ro.allSchemaProperties)(n.properties),u=(0,Ro.allSchemaProperties)(n.patternProperties);d(),e.ok((0,Be._)`${s} === ${Wx.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,Io.schemaRefOrVal)(i,n.properties,"properties");w=(0,Ro.isOwnProperty)(t,b,_)}else l.length?w=(0,Be.or)(...l.map(b=>(0,Be._)`${_} === ${b}`)):w=Be.nil;return u.length&&(w=(0,Be.or)(w,...u.map(b=>(0,Be._)`${(0,Ro.usePattern)(e,b)}.test(${_})`))),(0,Be.not)(w)}function f(_){t.code((0,Be._)`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,Io.alwaysValidSchema)(i,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(_,w,!1),t.if((0,Be.not)(w),()=>{e.reset(),f(_)})):(g(_,w),a||t.if((0,Be.not)(w),()=>t.break()))}}function g(_,w,b){let $={keyword:"additionalProperties",dataProp:_,dataPropType:Io.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,w)}}};Ga.default=Qx});var Rm=v(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Yx=nn(),Pm=Ce(),Ja=M(),Tm=Wa(),Xx={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Tm.default.code(new Yx.KeywordCxt(s,Tm.default,"additionalProperties"));let i=(0,Pm.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ja.mergeEvaluated.props(t,(0,Ja.toHash)(i),s.props));let a=i.filter(d=>!(0,Ja.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,Pm.propertyInData)(t,o,d,s.opts.ownProperties)),u(d),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Qa.default=Xx});var Cm=v(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Im=Ce(),No=C(),Nm=M(),Am=M(),ek={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Im.allSchemaProperties)(r),c=a.filter(g=>(0,Nm.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof No.Name)&&(s.props=(0,Am.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let g of a)l&&f(g),s.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function f(g){for(let _ in l)new RegExp(g).test(_)&&(0,Nm.checkStrictMode)(s,`property ${_} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,_=>{t.if((0,No._)`${(0,Im.usePattern)(e,g)}.test(${_})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:_,dataPropType:Am.Type.Str},u),s.opts.unevaluated&&d!==!0?t.assign((0,No._)`${d}[${_}]`,!0):!w&&!s.allErrors&&t.if((0,No.not)(u),()=>t.break())})})}}};Ya.default=ek});var Om=v(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var tk=M(),rk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,tk.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"}};Xa.default=rk});var jm=v(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var nk=Ce(),ok={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nk.validateUnion,error:{message:"must match a schema in anyOf"}};ec.default=ok});var Dm=v(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Ao=C(),sk=M(),ik={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Ao._)`{passingSchemas: ${e.passing}}`},ak={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:ik,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 s=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((u,d)=>{let p;(0,sk.alwaysValidSchema)(o,u)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,Ao._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ao._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,d),p&&e.mergeEvaluated(p,Ao.Name)})})}}};tc.default=ak});var qm=v(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var ck=M(),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((s,i)=>{if((0,ck.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};rc.default=uk});var Lm=v(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var Co=C(),Mm=M(),lk={message:({params:e})=>(0,Co.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Co._)`{failingKeyword: ${e.ifClause}}`},dk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:lk,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Mm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Zm(n,"then"),s=Zm(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){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,Co.not)(a),l("else"));e.pass(i,()=>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(i,a),e.mergeValidEvaluated(p,i),d?t.assign(d,(0,Co._)`${u}`):e.setParams({ifClause:u})}}}};function Zm(e,t){let r=e.schema[t];return r!==void 0&&!(0,Mm.alwaysValidSchema)(e,r)}nc.default=dk});var Bm=v(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var pk=M(),fk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,pk.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};oc.default=fk});var Um=v(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var mk=La(),hk=vm(),gk=Ba(),yk=bm(),_k=$m(),vk=Sm(),wk=Em(),bk=Wa(),$k=Rm(),xk=Cm(),kk=Om(),Sk=jm(),zk=Dm(),Ek=qm(),Pk=Lm(),Tk=Bm();function Rk(e=!1){let t=[kk.default,Sk.default,zk.default,Ek.default,Pk.default,Tk.default,wk.default,bk.default,vk.default,$k.default,xk.default];return e?t.push(hk.default,yk.default):t.push(mk.default,gk.default),t.push(_k.default),t}sc.default=Rk});var Fm=v(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var oe=C(),Ik={message:({schemaCode:e})=>(0,oe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,oe._)`{format: ${e}}`},Nk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Ik,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,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}[${i}]`),_=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._)`${i} && !${w}`}function $(){let E=u.$async?(0,oe._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,oe._)`${w}(${n})`,T=(0,oe._)`(typeof ${w} == "function" ? ${E} : ${w}.test(${n}))`;return(0,oe._)`${w} && ${w} !== true && ${_} === ${t} && !${T}`}}function f(){let h=d.formats[s];if(!h){b();return}if(h===!0)return;let[g,_,w]=$(h);g===t&&e.pass(E());function b(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function $(T){let ye=T instanceof RegExp?(0,oe.regexpCode)(T):c.code.formats?(0,oe._)`${c.code.formats}${(0,oe.getProperty)(s)}`:void 0,Te=r.scopeValue("formats",{key:s,ref:T,code:ye});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,oe._)`${Te}.validate`]:["string",T,Te]}function E(){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})`}}}};ic.default=Nk});var Km=v(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Ak=Fm(),Ck=[Ak.default];ac.default=Ck});var Vm=v(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.contentVocabulary=sr.metadataVocabulary=void 0;sr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];sr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Gm=v(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var Ok=tm(),jk=hm(),Dk=Um(),qk=Km(),Hm=Vm(),Zk=[Ok.default,jk.default,(0,Dk.default)(),qk.default,Hm.metadataVocabulary,Hm.contentVocabulary];cc.default=Zk});var Jm=v(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.DiscrError=void 0;var Wm;(function(e){e.Tag="tag",e.Mapping="mapping"})(Wm||(Oo.DiscrError=Wm={}))});var Ym=v(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var ir=C(),uc=Jm(),Qm=_o(),Mk=on(),Lk=M(),Bk={message:({params:{discrError:e,tagName:t}})=>e===uc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,ir._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Uk={keyword:"discriminator",type:"object",schemaType:"object",error:Bk,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,ir._)`${r}${(0,ir.getProperty)(a)}`);t.if((0,ir._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:uc.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,ir._)`${l} === ${h}`),t.assign(c,d(f[h]));t.else(),e.error(!1,{discrError:uc.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,ir.Name),h}function p(){var f;let h={},g=w(o),_=!0;for(let E=0;E<i.length;E++){let T=i[E];if(T?.$ref&&!(0,Lk.schemaHasRulesButRef)(T,s.self.RULES)){let Te=T.$ref;if(T=Qm.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Te),T instanceof Qm.SchemaEnv&&(T=T.schema),T===void 0)throw new Mk.default(s.opts.uriResolver,s.baseId,Te)}let ye=(f=T?.properties)===null||f===void 0?void 0:f[a];if(typeof ye!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);_=_&&(g||w(T)),b(ye,E)}if(!_)throw new Error(`discriminator: "${a}" must be required`);return h;function w({required:E}){return Array.isArray(E)&&E.includes(a)}function b(E,T){if(E.const)$(E.const,T);else if(E.enum)for(let ye of E.enum)$(ye,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(E,T){if(typeof E!="string"||E in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[E]=T}}}};lc.default=Uk});var Xm=v((bO,Fk)=>{Fk.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 pc=v((X,dc)=>{"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 Kk=Wf(),Vk=Gm(),Hk=Ym(),eh=Xm(),Gk=["/properties"],jo="http://json-schema.org/draft-07/schema",ar=class extends Kk.default{_addVocabularies(){super._addVocabularies(),Vk.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Hk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(eh,Gk):eh;this.addMetaSchema(t,jo,!1),this.refs["http://json-schema.org/schema"]=jo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(jo)?jo:void 0)}};X.Ajv=ar;dc.exports=X=ar;dc.exports.Ajv=ar;Object.defineProperty(X,"__esModule",{value:!0});X.default=ar;var Wk=nn();Object.defineProperty(X,"KeywordCxt",{enumerable:!0,get:function(){return Wk.KeywordCxt}});var cr=C();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return cr.Name}});Object.defineProperty(X,"CodeGen",{enumerable:!0,get:function(){return cr.CodeGen}});var Jk=go();Object.defineProperty(X,"ValidationError",{enumerable:!0,get:function(){return Jk.default}});var Qk=on();Object.defineProperty(X,"MissingRefError",{enumerable:!0,get:function(){return Qk.default}})});var ch=v(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.formatNames=Qe.fastFormats=Qe.fullFormats=void 0;function Je(e,t){return{validate:e,compare:t}}Qe.fullFormats={date:Je(oh,gc),time:Je(mc(!0),yc),"date-time":Je(th(!0),ih),"iso-time":Je(mc(),sh),"iso-date-time":Je(th(),ah),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nS,"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:lS,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:oS,int32:{type:"number",validate:aS},int64:{type:"number",validate:cS},float:{type:"number",validate:nh},double:{type:"number",validate:nh},password:!0,binary:!0};Qe.fastFormats={...Qe.fullFormats,date:Je(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,gc),time:Je(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,yc),"date-time":Je(/^\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,ih),"iso-time":Je(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sh),"iso-date-time":Je(/^\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,ah),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};Qe.formatNames=Object.keys(Qe.fullFormats);function Yk(e){return e%4===0&&(e%100!==0||e%400===0)}var Xk=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eS=[0,31,28,31,30,31,30,31,31,30,31,30,31];function oh(e){let t=Xk.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&&Yk(r)?29:eS[n])}function gc(e,t){if(e&&t)return e>t?1:e<t?-1:0}var fc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function mc(e){return function(r){let n=fc.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+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&&s<=59&&i<60)return!0;let d=s-u*c,p=o-l*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function yc(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 sh(e,t){if(!(e&&t))return;let r=fc.exec(e),n=fc.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 hc=/t|\s/i;function th(e){let t=mc(e);return function(n){let o=n.split(hc);return o.length===2&&oh(o[0])&&t(o[1])}}function ih(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function ah(e,t){if(!(e&&t))return;let[r,n]=e.split(hc),[o,s]=t.split(hc),i=gc(r,o);if(i!==void 0)return i||yc(n,s)}var tS=/\/|:/,rS=/^(?:[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 nS(e){return tS.test(e)&&rS.test(e)}var rh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function oS(e){return rh.lastIndex=0,rh.test(e)}var sS=-(2**31),iS=2**31-1;function aS(e){return Number.isInteger(e)&&e<=iS&&e>=sS}function cS(e){return Number.isInteger(e)}function nh(){return!0}var uS=/[^\\]\\Z/;function lS(e){if(uS.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var uh=v(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.formatLimitDefinition=void 0;var dS=pc(),Ue=C(),yt=Ue.operators,Do={formatMaximum:{okStr:"<=",ok:yt.LTE,fail:yt.GT},formatMinimum:{okStr:">=",ok:yt.GTE,fail:yt.LT},formatExclusiveMaximum:{okStr:"<",ok:yt.LT,fail:yt.GTE},formatExclusiveMinimum:{okStr:">",ok:yt.GT,fail:yt.LTE}},pS={message:({keyword:e,schemaCode:t})=>(0,Ue.str)`should be ${Do[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Ue._)`{comparison: ${Do[e].okStr}, limit: ${t}}`};ur.formatLimitDefinition={keyword:Object.keys(Do),type:"string",schemaType:"string",$data:!0,error:pS,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new dS.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=t.const("fmt",(0,Ue._)`${p}[${c.schemaCode}]`);e.fail$data((0,Ue.or)((0,Ue._)`typeof ${f} != "object"`,(0,Ue._)`${f} instanceof RegExp`,(0,Ue._)`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:i.code.formats?(0,Ue._)`${i.code.formats}${(0,Ue.getProperty)(p)}`:void 0});e.fail$data(d(h))}function d(p){return(0,Ue._)`${p}.compare(${r}, ${n}) ${Do[o].fail} 0`}},dependencies:["format"]};var fS=e=>(e.addKeyword(ur.formatLimitDefinition),e);ur.default=fS});var fh=v((vn,ph)=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});var lr=ch(),mS=uh(),_c=C(),lh=new _c.Name("fullFormats"),hS=new _c.Name("fastFormats"),vc=(e,t={keywords:!0})=>{if(Array.isArray(t))return dh(e,t,lr.fullFormats,lh),e;let[r,n]=t.mode==="fast"?[lr.fastFormats,hS]:[lr.fullFormats,lh],o=t.formats||lr.formatNames;return dh(e,o,r,n),t.keywords&&(0,mS.default)(e),e};vc.get=(e,t="full")=>{let n=(t==="fast"?lr.fastFormats:lr.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function dh(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,_c._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}ph.exports=vn=vc;Object.defineProperty(vn,"__esModule",{value:!0});vn.default=vc});var $h=v((OO,bh)=>{bh.exports=wh;wh.sync=vS;var _h=st("fs");function _S(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 vh(e,t,r){return!e.isSymbolicLink()&&!e.isFile()?!1:_S(t,r)}function wh(e,t,r){_h.stat(e,function(n,o){r(n,n?!1:vh(o,e,t))})}function vS(e,t){return vh(_h.statSync(e),e,t)}});var Eh=v((jO,zh)=>{zh.exports=kh;kh.sync=wS;var xh=st("fs");function kh(e,t,r){xh.stat(e,function(n,o){r(n,n?!1:Sh(o,t))})}function wS(e,t){return Sh(xh.statSync(e),t)}function Sh(e,t){return e.isFile()&&bS(e,t)}function bS(e,t){var r=e.mode,n=e.uid,o=e.gid,s=t.uid!==void 0?t.uid:process.getuid&&process.getuid(),i=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===i||r&a&&n===s||r&u&&s===0;return d}});var Th=v((qO,Ph)=>{var DO=st("fs"),Bo;process.platform==="win32"||global.TESTING_WINDOWS?Bo=$h():Bo=Eh();Ph.exports=wc;wc.sync=$S;function wc(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){wc(e,t||{},function(s,i){s?o(s):n(i)})})}Bo(e,t||{},function(n,o){n&&(n.code==="EACCES"||t&&t.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function $S(e,t){try{return Bo.sync(e,t||{})}catch(r){if(t&&t.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var jh=v((ZO,Oh)=>{var dr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",Rh=st("path"),xS=dr?";":":",Ih=Th(),Nh=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),Ah=(e,t)=>{let r=t.colon||xS,n=e.match(/\//)||dr&&e.match(/\\/)?[""]:[...dr?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],o=dr?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=dr?o.split(r):[""];return dr&&e.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},Ch=(e,t,r)=>{typeof t=="function"&&(r=t,t={}),t||(t={});let{pathEnv:n,pathExt:o,pathExtExe:s}=Ah(e,t),i=[],a=l=>new Promise((u,d)=>{if(l===n.length)return t.all&&i.length?u(i):d(Nh(e));let p=n[l],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=Rh.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];Ih(l+h,{pathExt:s},(g,_)=>{if(!g&&_)if(t.all)i.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)},kS=(e,t)=>{t=t||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Ah(e,t),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,l=Rh.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(Ih.sync(p,{pathExt:o}))if(t.all)s.push(p);else return p}catch{}}}if(t.all&&s.length)return s;if(t.nothrow)return null;throw Nh(e)};Oh.exports=Ch;Ch.sync=kS});var qh=v((MO,bc)=>{"use strict";var Dh=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)!=="win32"?"PATH":Object.keys(t).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};bc.exports=Dh;bc.exports.default=Dh});var Bh=v((LO,Lh)=>{"use strict";var Zh=st("path"),SS=jh(),zS=qh();function Mh(e,t){let r=e.options.env||process.env,n=process.cwd(),o=e.options.cwd!=null,s=o&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(e.options.cwd)}catch{}let i;try{i=SS.sync(e.command,{path:r[zS({env:r})],pathExt:t?Zh.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=Zh.resolve(o?e.options.cwd:"",i)),i}function ES(e){return Mh(e)||Mh(e,!0)}Lh.exports=ES});var Uh=v((BO,xc)=>{"use strict";var $c=/([()\][%!^"`<>&|;, *?])/g;function PS(e){return e=e.replace($c,"^$1"),e}function TS(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),e=e.replace(/(?=(\\+?)?)\1$/,"$1$1"),e=`"${e}"`,e=e.replace($c,"^$1"),t&&(e=e.replace($c,"^$1")),e}xc.exports.command=PS;xc.exports.argument=TS});var Kh=v((UO,Fh)=>{"use strict";Fh.exports=/^#!(.*)/});var Hh=v((FO,Vh)=>{"use strict";var RS=Kh();Vh.exports=(e="")=>{let t=e.match(RS);if(!t)return null;let[r,n]=t[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Wh=v((KO,Gh)=>{"use strict";var kc=st("fs"),IS=Hh();function NS(e){let r=Buffer.alloc(150),n;try{n=kc.openSync(e,"r"),kc.readSync(n,r,0,150,0),kc.closeSync(n)}catch{}return IS(r.toString())}Gh.exports=NS});var Xh=v((VO,Yh)=>{"use strict";var AS=st("path"),Jh=Bh(),Qh=Uh(),CS=Wh(),OS=process.platform==="win32",jS=/\.(?:com|exe)$/i,DS=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function qS(e){e.file=Jh(e);let t=e.file&&CS(e.file);return t?(e.args.unshift(e.file),e.command=t,Jh(e)):e.file}function ZS(e){if(!OS)return e;let t=qS(e),r=!jS.test(t);if(e.options.forceShell||r){let n=DS.test(t);e.command=AS.normalize(e.command),e.command=Qh.command(e.command),e.args=e.args.map(s=>Qh.argument(s,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 MS(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:ZS(n)}Yh.exports=MS});var rg=v((HO,tg)=>{"use strict";var Sc=process.platform==="win32";function zc(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 LS(e,t){if(!Sc)return;let r=e.emit;e.emit=function(n,o){if(n==="exit"){let s=eg(o,t);if(s)return r.call(e,"error",s)}return r.apply(e,arguments)}}function eg(e,t){return Sc&&e===1&&!t.file?zc(t.original,"spawn"):null}function BS(e,t){return Sc&&e===1&&!t.file?zc(t.original,"spawnSync"):null}tg.exports={hookChildProcess:LS,verifyENOENT:eg,verifyENOENTSync:BS,notFoundError:zc}});var sg=v((GO,pr)=>{"use strict";var ng=st("child_process"),Ec=Xh(),Pc=rg();function og(e,t,r){let n=Ec(e,t,r),o=ng.spawn(n.command,n.args,n.options);return Pc.hookChildProcess(o,n),o}function US(e,t,r){let n=Ec(e,t,r),o=ng.spawnSync(n.command,n.args,n.options);return o.error=o.error||Pc.verifyENOENTSync(o.status,n),o}pr.exports=og;pr.exports.spawn=og;pr.exports.sync=US;pr.exports._parse=Ec;pr.exports._enoent=Pc});import{readFile as mP,mkdir as hP,writeFile as gP}from"node:fs/promises";import{dirname as yP,join as sy}from"node:path";var CP=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 i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var OP=Symbol("zod_brand"),Xe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},En={};function Re(e){return e&&Object.assign(En,e),En}var U={};Yc(U,{BIGINT_FORMAT_RANGES:()=>eu,Class:()=>ls,NUMBER_FORMAT_RANGES:()=>_s,aborted:()=>$t,allowsEval:()=>hs,assert:()=>yy,assertEqual:()=>fy,assertIs:()=>hy,assertNever:()=>gy,assertNotEqual:()=>my,assignProp:()=>ms,cached:()=>xr,captureStackTrace:()=>Tn,cleanEnum:()=>Ry,cleanRegex:()=>Sr,clone:()=>Ke,createTransparentProxy:()=>xy,defineLazy:()=>H,esc:()=>bt,escapeRegex:()=>it,extend:()=>zy,finalizeIssue:()=>De,floatSafeRemainder:()=>fs,getElementAtPath:()=>_y,getEnumValues:()=>ds,getLengthableOrigin:()=>zr,getParsedType:()=>$y,getSizableOrigin:()=>tu,isObject:()=>Lt,isPlainObject:()=>Bt,issue:()=>vs,joinValues:()=>Pn,jsonStringifyReplacer:()=>ps,merge:()=>Ey,normalizeParams:()=>P,nullish:()=>kr,numKeys:()=>by,omit:()=>Sy,optionalKeys:()=>ys,partial:()=>Py,pick:()=>ky,prefixIssues:()=>Ve,primitiveTypes:()=>Xc,promiseAllObject:()=>vy,propertyKeyTypes:()=>gs,randomString:()=>wy,required:()=>Ty,stringifyPrimitive:()=>Rn,unwrapMessage:()=>$r});function fy(e){return e}function my(e){return e}function hy(e){}function gy(e){throw new Error}function yy(e){}function ds(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 Pn(e,t="|"){return e.map(r=>Rn(r)).join(t)}function ps(e,t){return typeof t=="bigint"?t.toString():t}function xr(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function kr(e){return e==null}function Sr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function fs(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/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 ms(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _y(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function vy(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function wy(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function bt(e){return JSON.stringify(e)}var Tn=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var hs=xr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Bt(e){if(Lt(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Lt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function by(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var $y=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}`)}},gs=new Set(["string","number","symbol"]),Xc=new Set(["string","number","bigint","boolean","symbol","undefined"]);function it(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function P(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 xy(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},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 Rn(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function ys(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var _s={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]},eu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ky(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 Ke(e,{...e._zod.def,shape:r,checks:[]})}function Sy(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 Ke(e,{...e._zod.def,shape:r,checks:[]})}function zy(e,t){if(!Bt(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 ms(this,"shape",n),n},checks:[]};return Ke(e,r)}function Ey(e,t){return Ke(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ms(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Py(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return Ke(t,{...t._zod.def,shape:o,checks:[]})}function Ty(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return Ke(t,{...t._zod.def,shape:o,checks:[]})}function $t(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Ve(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function $r(e){return typeof e=="string"?e:e?.message}function De(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=$r(e.inst?._zod.def?.error?.(e))??$r(t?.error?.(e))??$r(r.customError?.(e))??$r(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function tu(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function zr(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function vs(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Ry(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var ls=class{constructor(...t){}};var ru=(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,ps,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},In=y("$ZodError",ru),ws=y("$ZodError",ru,{Parent:Error});function nu(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 ou(e,t){let r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(e),n}var su=e=>(t,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Xe;if(i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>De(c,s,Re())));throw Tn(a,o?.callee),a}return i.value};var iu=e=>async(t,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??e)(i.issues.map(c=>De(c,s,Re())));throw Tn(a,o?.callee),a}return i.value};var bs=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Xe;return s.issues.length?{success:!1,error:new(e??In)(s.issues.map(i=>De(i,o,Re())))}:{success:!0,data:s.value}},Er=bs(ws),$s=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>De(i,o,Re())))}:{success:!0,data:s.value}},Nn=$s(ws);var au=/^[cC][^\s-]{8,}$/,cu=/^[0-9a-z]+$/,uu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lu=/^[0-9a-vA-V]{20}$/,du=/^[A-Za-z0-9]{27}$/,pu=/^[a-zA-Z0-9_-]{21}$/,fu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var mu=/^([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})$/,xs=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 hu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Ny="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gu(){return new RegExp(Ny,"u")}var yu=/^(?:(?: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])$/,_u=/^(([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})$/,vu=/^((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])$/,wu=/^(([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}=))?$/,ks=/^[A-Za-z0-9_-]*$/,$u=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var xu=/^\+(?:[0-9]){6,14}[0-9]$/,ku="(?:(?:\\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])))",Su=new RegExp(`^${ku}$`);function zu(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 Eu(e){return new RegExp(`^${zu(e)}$`)}function Pu(e){let t=zu({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(`^${ku}T(?:${n})$`)}var Tu=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ru=/^\d+$/,Iu=/^-?\d+(?:\.\d+)?/i,Nu=/true|false/i,Au=/null/i;var Cu=/^[^A-Z]*$/,Ou=/^[^a-z]*$/;var fe=y("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ju={number:"number",bigint:"bigint",object:"date"},zs=y("$ZodCheckLessThan",(e,t)=>{fe.init(e,t);let r=ju[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(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})}}),Es=y("$ZodCheckGreaterThan",(e,t)=>{fe.init(e,t);let r=ju[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(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})}}),Du=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):fs(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})}}),qu=y("$ZodCheckNumberFormat",(e,t)=>{fe.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=_s[t.format];e._zod.onattach.push(i=>{let a=i._zod.bag;a.format=t.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Ru)}),e._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.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&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var Zu=y("$ZodCheckMaxLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kr(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 i=zr(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Mu=y("$ZodCheckMinLength",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kr(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 i=zr(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Lu=y("$ZodCheckLengthEquals",(e,t)=>{var r;fe.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!kr(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,s=o.length;if(s===t.length)return;let i=zr(o),a=s>t.length;n.issues.push({origin:i,...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})}}),Pr=y("$ZodCheckStringFormat",(e,t)=>{var r,n;fe.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.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=()=>{})}),Bu=y("$ZodCheckRegex",(e,t)=>{Pr.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})}}),Uu=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Cu),Pr.init(e,t)}),Fu=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ou),Pr.init(e,t)}),Ku=y("$ZodCheckIncludes",(e,t)=>{fe.init(e,t);let r=it(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),Vu=y("$ZodCheckStartsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`^${it(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})}}),Hu=y("$ZodCheckEndsWith",(e,t)=>{fe.init(e,t);let r=new RegExp(`.*${it(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 Gu=y("$ZodCheckOverwrite",(e,t)=>{fe.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var An=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
+ `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
12
+ `))}};var Ju={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=Ju;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,i,a)=>{let c=$t(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Xe;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=$t(s,d)))});else{if(s.issues.length===d)continue;c||(c=$t(s,d))}}return l?l.then(()=>s):s};e._zod.run=(s,i)=>{let a=e._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Xe;return a.then(c=>o(c,n,i))}return o(a,n,i)}}e["~standard"]={validate:o=>{try{let s=Er(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Nn(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),On=y("$ZodString",(e,t)=>{G.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Tu(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)=>{Pr.init(e,t),On.init(e,t)}),il=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=mu),J.init(e,t)}),al=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=xs(n))}else t.pattern??(t.pattern=xs());J.init(e,t)}),cl=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=hu),J.init(e,t)}),ul=y("$ZodURL",(e,t)=>{J.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),s=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:$u.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("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ll=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=gu()),J.init(e,t)}),dl=y("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pu),J.init(e,t)}),pl=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=au),J.init(e,t)}),fl=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cu),J.init(e,t)}),ml=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=uu),J.init(e,t)}),hl=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lu),J.init(e,t)}),gl=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=du),J.init(e,t)}),yl=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Pu(t)),J.init(e,t)}),_l=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Su),J.init(e,t)}),vl=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Eu(t)),J.init(e,t)}),wl=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fu),J.init(e,t)}),bl=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yu),J.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),$l=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_u),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})}}}),xl=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=vu),J.init(e,t)}),kl=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=wu),J.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>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 Sl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var zl=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=>{Sl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Ay(e){if(!ks.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Sl(r)}var El=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ks),J.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Ay(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Pl=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xu),J.init(e,t)});function Cy(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 Tl=y("$ZodJWT",(e,t)=>{J.init(e,t),e._zod.check=r=>{Cy(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ts=y("$ZodNumber",(e,t)=>{G.init(e,t),e._zod.pattern=e._zod.bag.pattern??Iu,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 s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Rl=y("$ZodNumber",(e,t)=>{qu.init(e,t),Ts.init(e,t)}),Il=y("$ZodBoolean",(e,t)=>{G.init(e,t),e._zod.pattern=Nu,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 Nl=y("$ZodNull",(e,t)=>{G.init(e,t),e._zod.pattern=Au,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 Al=y("$ZodUnknown",(e,t)=>{G.init(e,t),e._zod.parse=r=>r}),Cl=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 Qu(e,t,r){e.issues.length&&t.issues.push(...Ve(r,e.issues)),t.value[r]=e.value}var Ol=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 s=[];for(let i=0;i<o.length;i++){let a=o[i],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>Qu(l,r,i))):Qu(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Cn(e,t,r){e.issues.length&&t.issues.push(...Ve(r,e.issues)),t.value[r]=e.value}function Yu(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(...Ve(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var jl=y("$ZodObject",(e,t)=>{G.init(e,t);let r=xr(()=>{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=ys(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 An(["shape","payload","ctx"]),f=r.value,h=b=>{let $=bt(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 E=bt(b);p.write(`
13
+ if (${$}.issues.length) {
14
+ if (input[${E}] === undefined) {
15
+ if (${E} in input) {
16
+ newResult[${E}] = undefined;
17
+ }
18
+ } else {
19
+ payload.issues = payload.issues.concat(
20
+ ${$}.issues.map((iss) => ({
21
+ ...iss,
22
+ path: iss.path ? [${E}, ...iss.path] : [${E}],
23
+ }))
24
+ );
25
+ }
26
+ } else if (${$}.value === undefined) {
27
+ if (${E} in input) newResult[${E}] = undefined;
28
+ } else {
29
+ newResult[${E}] = ${$}.value;
30
+ }
31
+ `)}else{let $=g[b];p.write(`const ${$} = ${h(b)};`),p.write(`
32
+ if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
33
+ ...iss,
34
+ path: iss.path ? [${bt(b)}, ...iss.path] : [${bt(b)}]
35
+ })));`),p.write(`newResult[${bt(b)}] = ${$}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,$)=>w(d,b,$)},o,s=Lt,i=!En.jitless,c=i&&hs.value,l=t.catchall,u;e._zod.parse=(d,p)=>{u??(u=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d;let h=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),d=o(d,p);else{d.value={};let $=u.shape;for(let E of u.keys){let T=$[E],ye=T._zod.run({value:f[E],issues:[]},p),Te=T._zod.optin==="optional"&&T._zod.optout==="optional";ye instanceof Promise?h.push(ye.then(Mt=>Te?Yu(Mt,d,E,f):Cn(Mt,d,E))):Te?Yu(ye,d,E,f):Cn(ye,d,E)}}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 E=w.run({value:f[$],issues:[]},p);E instanceof Promise?h.push(E.then(T=>Cn(T,d,$))):Cn(E,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 Xu(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(s=>De(s,n,Re())))}),t}var Rs=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=>Sr(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of t.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Xu(i,r,e,n)):Xu(s,r,e,n)}}),Dl=y("$ZodDiscriminatedUnion",(e,t)=>{Rs.init(e,t);let r=e._zod.parse;H(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=xr(()=>{let o=t.options,s=new Map;for(let i of o){let a=i._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!Lt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=n.value.get(i?.[t.discriminator]);return a?a._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),o)}}),ql=y("$ZodIntersection",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>el(r,c,l)):el(r,s,i)}});function Ps(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(Bt(e)&&Bt(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=Ps(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.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],s=t[n],i=Ps(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function el(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),$t(e))return e;let n=Ps(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 Zl=y("$ZodRecord",(e,t)=>{G.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Bt(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[];if(t.keyType._zod.values){let i=t.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=t.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...Ve(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Ve(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.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 i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=t.keyType._zod.run({value:i,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=>De(l,n,Re())),input:i,path:[i],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...Ve(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Ve(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Ml=y("$ZodEnum",(e,t)=>{G.init(e,t);let r=ds(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>gs.has(typeof n)).map(n=>typeof n=="string"?it(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Ll=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"?it(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 Bl=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(i=>(r.value=i,r));if(o instanceof Promise)throw new Xe;return r.value=o,r}}),Ul=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(`^(${Sr(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)}),Fl=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(`^(${Sr(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)}),Kl=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(s=>tl(s,t)):tl(o,t)}});function tl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Vl=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))}),Hl=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(s=>rl(s,e)):rl(o,e)}});function rl(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 Gl=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(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>De(i,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(s=>De(s,n,Re()))},input:r.value}),r.issues=[]),r)}});var Wl=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(s=>nl(s,t,n)):nl(o,t,n)}});function nl(e,t,r){return $t(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var Jl=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(ol):ol(o)}});function ol(e){return e.value=Object.freeze(e.value),e}var Ql=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(s=>sl(s,r,n,e));sl(o,r,n,e)}});function sl(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(vs(o))}}var Oy=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},jy=()=>{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 ${Oy(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Rn(n.values[0])}`:`Invalid option: expected one of ${Pn(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=t(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=t(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.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":""}: ${Pn(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 Yl(){return{localeError:jy()}}var WP=Symbol("ZodOutput"),JP=Symbol("ZodInput"),Is=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 Dy(){return new Is}var Tr=Dy();function Xl(e,t){return new e({type:"string",...P(t)})}function ed(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}function Ns(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function td(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}function sd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}function id(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}function ad(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}function cd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}function ud(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}function ld(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}function dd(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}function pd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}function fd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}function md(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}function hd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}function gd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}function yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}function _d(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}function vd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}function wd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}function bd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}function $d(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}function xd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}function kd(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}function Sd(e,t){return new e({type:"number",checks:[],...P(t)})}function zd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}function Ed(e,t){return new e({type:"boolean",...P(t)})}function Pd(e,t){return new e({type:"null",...P(t)})}function Td(e){return new e({type:"unknown"})}function Rd(e,t){return new e({type:"never",...P(t)})}function jn(e,t){return new zs({check:"less_than",...P(t),value:e,inclusive:!1})}function Rr(e,t){return new zs({check:"less_than",...P(t),value:e,inclusive:!0})}function Dn(e,t){return new Es({check:"greater_than",...P(t),value:e,inclusive:!1})}function Ir(e,t){return new Es({check:"greater_than",...P(t),value:e,inclusive:!0})}function qn(e,t){return new Du({check:"multiple_of",...P(t),value:e})}function Zn(e,t){return new Zu({check:"max_length",...P(t),maximum:e})}function Ut(e,t){return new Mu({check:"min_length",...P(t),minimum:e})}function Mn(e,t){return new Lu({check:"length_equals",...P(t),length:e})}function As(e,t){return new Bu({check:"string_format",format:"regex",...P(t),pattern:e})}function Cs(e){return new Uu({check:"string_format",format:"lowercase",...P(e)})}function Os(e){return new Fu({check:"string_format",format:"uppercase",...P(e)})}function js(e,t){return new Ku({check:"string_format",format:"includes",...P(t),includes:e})}function Ds(e,t){return new Vu({check:"string_format",format:"starts_with",...P(t),prefix:e})}function qs(e,t){return new Hu({check:"string_format",format:"ends_with",...P(t),suffix:e})}function xt(e){return new Gu({check:"overwrite",tx:e})}function Zs(e){return xt(t=>t.normalize(e))}function Ms(){return xt(e=>e.trim())}function Ls(){return xt(e=>e.toLowerCase())}function Bs(){return xt(e=>e.toUpperCase())}function Id(e,t,r){return new e({type:"array",element:t,...P(r)})}function Nd(e,t,r){let n=P(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ad(e,t,r){return new e({type:"custom",check:"custom",fn:t,...P(r)})}function Ft(e){return!!e._zod}function qe(e,t){return Ft(e)?Er(e,t):e.safeParse(t)}function Ln(e){if(!e)return;let t;if(Ft(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Cd(e){if(Ft(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=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 Ar={};Yc(Ar,{ZodISODate:()=>jd,ZodISODateTime:()=>Od,ZodISODuration:()=>qd,ZodISOTime:()=>Dd,date:()=>Fs,datetime:()=>Us,duration:()=>Vs,time:()=>Ks});var Od=y("ZodISODateTime",(e,t)=>{yl.init(e,t),ee.init(e,t)});function Us(e){return bd(Od,e)}var jd=y("ZodISODate",(e,t)=>{_l.init(e,t),ee.init(e,t)});function Fs(e){return $d(jd,e)}var Dd=y("ZodISOTime",(e,t)=>{vl.init(e,t),ee.init(e,t)});function Ks(e){return xd(Dd,e)}var qd=y("ZodISODuration",(e,t)=>{wl.init(e,t),ee.init(e,t)});function Vs(e){return kd(qd,e)}var Zd=(e,t)=>{In.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ou(e,r)},flatten:{value:r=>nu(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},RT=y("ZodError",Zd),Cr=y("ZodError",Zd,{Parent:Error});var Md=su(Cr),Ld=iu(Cr),Bd=bs(Cr),Ud=$s(Cr);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)=>Ke(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>Md(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Bd(e,r,n),e.parseAsync=async(r,n)=>Ld(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ud(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(C_(r,n)),e.superRefine=r=>e.check(O_(r)),e.overwrite=r=>e.check(xt(r)),e.optional=()=>re(e),e.nullable=()=>Vd(e),e.nullish=()=>re(Vd(e)),e.nonoptional=r=>E_(e,r),e.array=()=>D(e),e.or=r=>Q([e,r]),e.and=r=>Un(e,r),e.transform=r=>Gs(e,Yd(r)),e.default=r=>k_(e,r),e.prefault=r=>z_(e,r),e.catch=r=>T_(e,r),e.pipe=r=>Gs(e,r),e.readonly=()=>N_(e),e.describe=r=>{let n=e.clone();return Tr.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Tr.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Tr.get(e);let n=e.clone();return Tr.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Hd=y("_ZodString",(e,t)=>{On.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(As(...n)),e.includes=(...n)=>e.check(js(...n)),e.startsWith=(...n)=>e.check(Ds(...n)),e.endsWith=(...n)=>e.check(qs(...n)),e.min=(...n)=>e.check(Ut(...n)),e.max=(...n)=>e.check(Zn(...n)),e.length=(...n)=>e.check(Mn(...n)),e.nonempty=(...n)=>e.check(Ut(1,...n)),e.lowercase=n=>e.check(Cs(n)),e.uppercase=n=>e.check(Os(n)),e.trim=()=>e.check(Ms()),e.normalize=(...n)=>e.check(Zs(...n)),e.toLowerCase=()=>e.check(Ls()),e.toUpperCase=()=>e.check(Bs())}),Vy=y("ZodString",(e,t)=>{On.init(e,t),Hd.init(e,t),e.email=r=>e.check(ed(Hy,r)),e.url=r=>e.check(sd(Gy,r)),e.jwt=r=>e.check(wd(u_,r)),e.emoji=r=>e.check(id(Wy,r)),e.guid=r=>e.check(Ns(Fd,r)),e.uuid=r=>e.check(td(Bn,r)),e.uuidv4=r=>e.check(rd(Bn,r)),e.uuidv6=r=>e.check(nd(Bn,r)),e.uuidv7=r=>e.check(od(Bn,r)),e.nanoid=r=>e.check(ad(Jy,r)),e.guid=r=>e.check(Ns(Fd,r)),e.cuid=r=>e.check(cd(Qy,r)),e.cuid2=r=>e.check(ud(Yy,r)),e.ulid=r=>e.check(ld(Xy,r)),e.base64=r=>e.check(yd(i_,r)),e.base64url=r=>e.check(_d(a_,r)),e.xid=r=>e.check(dd(e_,r)),e.ksuid=r=>e.check(pd(t_,r)),e.ipv4=r=>e.check(fd(r_,r)),e.ipv6=r=>e.check(md(n_,r)),e.cidrv4=r=>e.check(hd(o_,r)),e.cidrv6=r=>e.check(gd(s_,r)),e.e164=r=>e.check(vd(c_,r)),e.datetime=r=>e.check(Us(r)),e.date=r=>e.check(Fs(r)),e.time=r=>e.check(Ks(r)),e.duration=r=>e.check(Vs(r))});function m(e){return Xl(Vy,e)}var ee=y("ZodStringFormat",(e,t)=>{J.init(e,t),Hd.init(e,t)}),Hy=y("ZodEmail",(e,t)=>{cl.init(e,t),ee.init(e,t)});var Fd=y("ZodGUID",(e,t)=>{il.init(e,t),ee.init(e,t)});var Bn=y("ZodUUID",(e,t)=>{al.init(e,t),ee.init(e,t)});var Gy=y("ZodURL",(e,t)=>{ul.init(e,t),ee.init(e,t)});var Wy=y("ZodEmoji",(e,t)=>{ll.init(e,t),ee.init(e,t)});var Jy=y("ZodNanoID",(e,t)=>{dl.init(e,t),ee.init(e,t)});var Qy=y("ZodCUID",(e,t)=>{pl.init(e,t),ee.init(e,t)});var Yy=y("ZodCUID2",(e,t)=>{fl.init(e,t),ee.init(e,t)});var Xy=y("ZodULID",(e,t)=>{ml.init(e,t),ee.init(e,t)});var e_=y("ZodXID",(e,t)=>{hl.init(e,t),ee.init(e,t)});var t_=y("ZodKSUID",(e,t)=>{gl.init(e,t),ee.init(e,t)});var r_=y("ZodIPv4",(e,t)=>{bl.init(e,t),ee.init(e,t)});var n_=y("ZodIPv6",(e,t)=>{$l.init(e,t),ee.init(e,t)});var o_=y("ZodCIDRv4",(e,t)=>{xl.init(e,t),ee.init(e,t)});var s_=y("ZodCIDRv6",(e,t)=>{kl.init(e,t),ee.init(e,t)});var i_=y("ZodBase64",(e,t)=>{zl.init(e,t),ee.init(e,t)});var a_=y("ZodBase64URL",(e,t)=>{El.init(e,t),ee.init(e,t)});var c_=y("ZodE164",(e,t)=>{Pl.init(e,t),ee.init(e,t)});var u_=y("ZodJWT",(e,t)=>{Tl.init(e,t),ee.init(e,t)});var Gd=y("ZodNumber",(e,t)=>{Ts.init(e,t),ne.init(e,t),e.gt=(n,o)=>e.check(Dn(n,o)),e.gte=(n,o)=>e.check(Ir(n,o)),e.min=(n,o)=>e.check(Ir(n,o)),e.lt=(n,o)=>e.check(jn(n,o)),e.lte=(n,o)=>e.check(Rr(n,o)),e.max=(n,o)=>e.check(Rr(n,o)),e.int=n=>e.check(Kd(n)),e.safe=n=>e.check(Kd(n)),e.positive=n=>e.check(Dn(0,n)),e.nonnegative=n=>e.check(Ir(0,n)),e.negative=n=>e.check(jn(0,n)),e.nonpositive=n=>e.check(Rr(0,n)),e.multipleOf=(n,o)=>e.check(qn(n,o)),e.step=(n,o)=>e.check(qn(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 Sd(Gd,e)}var l_=y("ZodNumberFormat",(e,t)=>{Rl.init(e,t),Gd.init(e,t)});function Kd(e){return zd(l_,e)}var d_=y("ZodBoolean",(e,t)=>{Il.init(e,t),ne.init(e,t)});function ae(e){return Ed(d_,e)}var p_=y("ZodNull",(e,t)=>{Nl.init(e,t),ne.init(e,t)});function Wd(e){return Pd(p_,e)}var f_=y("ZodUnknown",(e,t)=>{Al.init(e,t),ne.init(e,t)});function te(){return Td(f_)}var m_=y("ZodNever",(e,t)=>{Cl.init(e,t),ne.init(e,t)});function h_(e){return Rd(m_,e)}var g_=y("ZodArray",(e,t)=>{Ol.init(e,t),ne.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ut(r,n)),e.nonempty=r=>e.check(Ut(1,r)),e.max=(r,n)=>e.check(Zn(r,n)),e.length=(r,n)=>e.check(Mn(r,n)),e.unwrap=()=>e.element});function D(e,t){return Id(g_,e,t)}var Jd=y("ZodObject",(e,t)=>{jl.init(e,t),ne.init(e,t),U.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>be(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:h_()}),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(Xd,e,r[0]),e.required=(...r)=>U.required(ep,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 Jd(r)}function _e(e,t){return new Jd({type:"object",get shape(){return U.assignProp(this,"shape",{...e}),this.shape},catchall:te(),...U.normalizeParams(t)})}var Qd=y("ZodUnion",(e,t)=>{Rs.init(e,t),ne.init(e,t),e.options=t.options});function Q(e,t){return new Qd({type:"union",options:e,...U.normalizeParams(t)})}var y_=y("ZodDiscriminatedUnion",(e,t)=>{Qd.init(e,t),Dl.init(e,t)});function Ws(e,t,r){return new y_({type:"union",options:t,discriminator:e,...U.normalizeParams(r)})}var __=y("ZodIntersection",(e,t)=>{ql.init(e,t),ne.init(e,t)});function Un(e,t){return new __({type:"intersection",left:e,right:t})}var v_=y("ZodRecord",(e,t)=>{Zl.init(e,t),ne.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function W(e,t,r){return new v_({type:"record",keyType:e,valueType:t,...U.normalizeParams(r)})}var Hs=y("ZodEnum",(e,t)=>{Ml.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 s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hs({...t,checks:[],...U.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hs({...t,checks:[],...U.normalizeParams(o),entries:s})}});function be(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Hs({type:"enum",entries:r,...U.normalizeParams(t)})}var w_=y("ZodLiteral",(e,t)=>{Ll.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 w_({type:"literal",values:Array.isArray(e)?e:[e],...U.normalizeParams(t)})}var b_=y("ZodTransform",(e,t)=>{Bl.init(e,t),ne.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),r.issues.push(U.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Yd(e){return new b_({type:"transform",transform:e})}var Xd=y("ZodOptional",(e,t)=>{Ul.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function re(e){return new Xd({type:"optional",innerType:e})}var $_=y("ZodNullable",(e,t)=>{Fl.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vd(e){return new $_({type:"nullable",innerType:e})}var x_=y("ZodDefault",(e,t)=>{Kl.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function k_(e,t){return new x_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var S_=y("ZodPrefault",(e,t)=>{Vl.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function z_(e,t){return new S_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var ep=y("ZodNonOptional",(e,t)=>{Hl.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType});function E_(e,t){return new ep({type:"nonoptional",innerType:e,...U.normalizeParams(t)})}var P_=y("ZodCatch",(e,t)=>{Gl.init(e,t),ne.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function T_(e,t){return new P_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var R_=y("ZodPipe",(e,t)=>{Wl.init(e,t),ne.init(e,t),e.in=t.in,e.out=t.out});function Gs(e,t){return new R_({type:"pipe",in:e,out:t})}var I_=y("ZodReadonly",(e,t)=>{Jl.init(e,t),ne.init(e,t)});function N_(e){return new I_({type:"readonly",innerType:e})}var tp=y("ZodCustom",(e,t)=>{Ql.init(e,t),ne.init(e,t)});function A_(e){let t=new fe({check:"custom"});return t._zod.check=e,t}function rp(e,t){return Nd(tp,e??(()=>!0),t)}function C_(e,t={}){return Ad(tp,e,t)}function O_(e){let t=A_(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 Js(e,t){return Gs(Yd(e),t)}Re(Yl());var Ys="2025-11-25";var np=[Ys,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],at="io.modelcontextprotocol/related-task",Kn="2.0",ie=rp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),op=Q([m(),F().int()]),sp=m(),xR=_e({ttl:F().optional(),pollInterval:F().optional()}),j_=x({ttl:F().optional()}),D_=x({taskId:m()}),Xs=_e({progressToken:op.optional(),[at]:D_.optional()}),Ee=x({_meta:Xs.optional()}),Or=Ee.extend({task:j_.optional()}),ip=e=>Or.safeParse(e).success,ce=x({method:m(),params:Ee.loose().optional()}),Ie=x({_meta:Xs.optional()}),Ne=x({method:m(),params:Ie.loose().optional()}),ue=_e({_meta:Xs.optional()}),Vn=Q([m(),F().int()]),ap=x({jsonrpc:k(Kn),id:Vn,...ce.shape}).strict(),ei=e=>ap.safeParse(e).success,cp=x({jsonrpc:k(Kn),...Ne.shape}).strict(),up=e=>cp.safeParse(e).success,ti=x({jsonrpc:k(Kn),id:Vn,result:ue}).strict(),jr=e=>ti.safeParse(e).success;var R;(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"})(R||(R={}));var ri=x({jsonrpc:k(Kn),id:Vn.optional(),error:x({code:F().int(),message:m(),data:te().optional()})}).strict();var lp=e=>ri.safeParse(e).success;var dp=Q([ap,cp,ti,ri]),kR=Q([ti,ri]),kt=ue.strict(),q_=Ie.extend({requestId:Vn.optional(),reason:m().optional()}),Hn=Ne.extend({method:k("notifications/cancelled"),params:q_}),Z_=x({src:m(),mimeType:m().optional(),sizes:D(m()).optional(),theme:be(["light","dark"]).optional()}),Dr=x({icons:D(Z_).optional()}),Kt=x({name:m(),title:m().optional()}),pp=Kt.extend({...Kt.shape,...Dr.shape,version:m(),websiteUrl:m().optional(),description:m().optional()}),M_=Un(x({applyDefaults:ae().optional()}),W(m(),te())),L_=Js(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Un(x({form:M_.optional(),url:ie.optional()}),W(m(),te()).optional())),B_=_e({list:ie.optional(),cancel:ie.optional(),requests:_e({sampling:_e({createMessage:ie.optional()}).optional(),elicitation:_e({create:ie.optional()}).optional()}).optional()}),U_=_e({list:ie.optional(),cancel:ie.optional(),requests:_e({tools:_e({call:ie.optional()}).optional()}).optional()}),F_=x({experimental:W(m(),ie).optional(),sampling:x({context:ie.optional(),tools:ie.optional()}).optional(),elicitation:L_.optional(),roots:x({listChanged:ae().optional()}).optional(),tasks:B_.optional(),extensions:W(m(),ie).optional()}),K_=Ee.extend({protocolVersion:m(),capabilities:F_,clientInfo:pp}),V_=ce.extend({method:k("initialize"),params:K_});var H_=x({experimental:W(m(),ie).optional(),logging:ie.optional(),completions:ie.optional(),prompts:x({listChanged:ae().optional()}).optional(),resources:x({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:x({listChanged:ae().optional()}).optional(),tasks:U_.optional(),extensions:W(m(),ie).optional()}),ni=ue.extend({protocolVersion:m(),capabilities:H_,serverInfo:pp,instructions:m().optional()}),G_=Ne.extend({method:k("notifications/initialized"),params:Ie.optional()});var Gn=ce.extend({method:k("ping"),params:Ee.optional()}),W_=x({progress:F(),total:re(F()),message:re(m())}),J_=x({...Ie.shape,...W_.shape,progressToken:op}),Wn=Ne.extend({method:k("notifications/progress"),params:J_}),Q_=Ee.extend({cursor:sp.optional()}),qr=ce.extend({params:Q_.optional()}),Zr=ue.extend({nextCursor:sp.optional()}),Y_=be(["working","input_required","completed","failed","cancelled"]),Mr=x({taskId:m(),status:Y_,ttl:Q([F(),Wd()]),createdAt:m(),lastUpdatedAt:m(),pollInterval:re(F()),statusMessage:re(m())}),St=ue.extend({task:Mr}),X_=Ie.merge(Mr),Lr=Ne.extend({method:k("notifications/tasks/status"),params:X_}),Jn=ce.extend({method:k("tasks/get"),params:Ee.extend({taskId:m()})}),Qn=ue.merge(Mr),Yn=ce.extend({method:k("tasks/result"),params:Ee.extend({taskId:m()})}),SR=ue.loose(),Xn=qr.extend({method:k("tasks/list")}),eo=Zr.extend({tasks:D(Mr)}),to=ce.extend({method:k("tasks/cancel"),params:Ee.extend({taskId:m()})}),fp=ue.merge(Mr),mp=x({uri:m(),mimeType:re(m()),_meta:W(m(),te()).optional()}),hp=mp.extend({text:m()}),oi=m().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),gp=mp.extend({blob:oi}),Br=be(["user","assistant"]),Vt=x({audience:D(Br).optional(),priority:F().min(0).max(1).optional(),lastModified:Ar.datetime({offset:!0}).optional()}),yp=x({...Kt.shape,...Dr.shape,uri:m(),description:re(m()),mimeType:re(m()),size:re(F()),annotations:Vt.optional(),_meta:re(_e({}))}),ev=x({...Kt.shape,...Dr.shape,uriTemplate:m(),description:re(m()),mimeType:re(m()),annotations:Vt.optional(),_meta:re(_e({}))}),tv=qr.extend({method:k("resources/list")}),si=Zr.extend({resources:D(yp)}),rv=qr.extend({method:k("resources/templates/list")}),ii=Zr.extend({resourceTemplates:D(ev)}),ai=Ee.extend({uri:m()}),nv=ai,ov=ce.extend({method:k("resources/read"),params:nv}),ci=ue.extend({contents:D(Q([hp,gp]))}),ui=Ne.extend({method:k("notifications/resources/list_changed"),params:Ie.optional()}),sv=ai,iv=ce.extend({method:k("resources/subscribe"),params:sv}),av=ai,cv=ce.extend({method:k("resources/unsubscribe"),params:av}),uv=Ie.extend({uri:m()}),lv=Ne.extend({method:k("notifications/resources/updated"),params:uv}),dv=x({name:m(),description:re(m()),required:re(ae())}),pv=x({...Kt.shape,...Dr.shape,description:re(m()),arguments:re(D(dv)),_meta:re(_e({}))}),fv=qr.extend({method:k("prompts/list")}),li=Zr.extend({prompts:D(pv)}),mv=Ee.extend({name:m(),arguments:W(m(),m()).optional()}),hv=ce.extend({method:k("prompts/get"),params:mv}),di=x({type:k("text"),text:m(),annotations:Vt.optional(),_meta:W(m(),te()).optional()}),pi=x({type:k("image"),data:oi,mimeType:m(),annotations:Vt.optional(),_meta:W(m(),te()).optional()}),fi=x({type:k("audio"),data:oi,mimeType:m(),annotations:Vt.optional(),_meta:W(m(),te()).optional()}),gv=x({type:k("tool_use"),name:m(),id:m(),input:W(m(),te()),_meta:W(m(),te()).optional()}),yv=x({type:k("resource"),resource:Q([hp,gp]),annotations:Vt.optional(),_meta:W(m(),te()).optional()}),_v=yp.extend({type:k("resource_link")}),mi=Q([di,pi,fi,_v,yv]),vv=x({role:Br,content:mi}),hi=ue.extend({description:m().optional(),messages:D(vv)}),gi=Ne.extend({method:k("notifications/prompts/list_changed"),params:Ie.optional()}),wv=x({title:m().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),bv=x({taskSupport:be(["required","optional","forbidden"]).optional()}),_p=x({...Kt.shape,...Dr.shape,description:m().optional(),inputSchema:x({type:k("object"),properties:W(m(),ie).optional(),required:D(m()).optional()}).catchall(te()),outputSchema:x({type:k("object"),properties:W(m(),ie).optional(),required:D(m()).optional()}).catchall(te()).optional(),annotations:wv.optional(),execution:bv.optional(),_meta:W(m(),te()).optional()}),$v=qr.extend({method:k("tools/list")}),yi=Zr.extend({tools:D(_p)}),ct=ue.extend({content:D(mi).default([]),structuredContent:W(m(),te()).optional(),isError:ae().optional()}),zR=ct.or(ue.extend({toolResult:te()})),xv=Or.extend({name:m(),arguments:W(m(),te()).optional()}),kv=ce.extend({method:k("tools/call"),params:xv}),_i=Ne.extend({method:k("notifications/tools/list_changed"),params:Ie.optional()}),vp=x({autoRefresh:ae().default(!0),debounceMs:F().int().nonnegative().default(300)}),wp=be(["debug","info","notice","warning","error","critical","alert","emergency"]),Sv=Ee.extend({level:wp}),zv=ce.extend({method:k("logging/setLevel"),params:Sv}),Ev=Ie.extend({level:wp,logger:m().optional(),data:te()}),Pv=Ne.extend({method:k("notifications/message"),params:Ev}),Tv=x({name:m().optional()}),Rv=x({hints:D(Tv).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),Iv=x({mode:be(["auto","required","none"]).optional()}),Nv=x({type:k("tool_result"),toolUseId:m().describe("The unique identifier for the corresponding tool call."),content:D(mi).default([]),structuredContent:x({}).loose().optional(),isError:ae().optional(),_meta:W(m(),te()).optional()}),Av=Ws("type",[di,pi,fi]),Fn=Ws("type",[di,pi,fi,gv,Nv]),Cv=x({role:Br,content:Q([Fn,D(Fn)]),_meta:W(m(),te()).optional()}),Ov=Or.extend({messages:D(Cv),modelPreferences:Rv.optional(),systemPrompt:m().optional(),includeContext:be(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:D(m()).optional(),metadata:ie.optional(),tools:D(_p).optional(),toolChoice:Iv.optional()}),vi=ce.extend({method:k("sampling/createMessage"),params:Ov}),wi=ue.extend({model:m(),stopReason:re(be(["endTurn","stopSequence","maxTokens"]).or(m())),role:Br,content:Av}),bi=ue.extend({model:m(),stopReason:re(be(["endTurn","stopSequence","maxTokens","toolUse"]).or(m())),role:Br,content:Q([Fn,D(Fn)])}),jv=x({type:k("boolean"),title:m().optional(),description:m().optional(),default:ae().optional()}),Dv=x({type:k("string"),title:m().optional(),description:m().optional(),minLength:F().optional(),maxLength:F().optional(),format:be(["email","uri","date","date-time"]).optional(),default:m().optional()}),qv=x({type:be(["number","integer"]),title:m().optional(),description:m().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),Zv=x({type:k("string"),title:m().optional(),description:m().optional(),enum:D(m()),default:m().optional()}),Mv=x({type:k("string"),title:m().optional(),description:m().optional(),oneOf:D(x({const:m(),title:m()})),default:m().optional()}),Lv=x({type:k("string"),title:m().optional(),description:m().optional(),enum:D(m()),enumNames:D(m()).optional(),default:m().optional()}),Bv=Q([Zv,Mv]),Uv=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:k("string"),enum:D(m())}),default:D(m()).optional()}),Fv=x({type:k("array"),title:m().optional(),description:m().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:D(x({const:m(),title:m()}))}),default:D(m()).optional()}),Kv=Q([Uv,Fv]),Vv=Q([Lv,Bv,Kv]),Hv=Q([Vv,jv,Dv,qv]),Gv=Or.extend({mode:k("form").optional(),message:m(),requestedSchema:x({type:k("object"),properties:W(m(),Hv),required:D(m()).optional()})}),Wv=Or.extend({mode:k("url"),message:m(),elicitationId:m(),url:m().url()}),Jv=Q([Gv,Wv]),$i=ce.extend({method:k("elicitation/create"),params:Jv}),Qv=Ie.extend({elicitationId:m()}),Yv=Ne.extend({method:k("notifications/elicitation/complete"),params:Qv}),xi=ue.extend({action:be(["accept","decline","cancel"]),content:Js(e=>e===null?void 0:e,W(m(),Q([m(),F(),ae(),D(m())])).optional())}),Xv=x({type:k("ref/resource"),uri:m()});var ew=x({type:k("ref/prompt"),name:m()}),tw=Ee.extend({ref:Q([ew,Xv]),argument:x({name:m(),value:m()}),context:x({arguments:W(m(),m()).optional()}).optional()}),rw=ce.extend({method:k("completion/complete"),params:tw});var ki=ue.extend({completion:_e({values:D(m()).max(100),total:re(F().int()),hasMore:re(ae())})}),nw=x({uri:m().startsWith("file://"),name:m().optional(),_meta:W(m(),te()).optional()}),ow=ce.extend({method:k("roots/list"),params:Ee.optional()}),sw=ue.extend({roots:D(nw)}),iw=Ne.extend({method:k("notifications/roots/list_changed"),params:Ie.optional()}),ER=Q([Gn,V_,rw,zv,hv,fv,tv,rv,ov,iv,cv,kv,$v,Jn,Yn,Xn,to]),PR=Q([Hn,Wn,G_,iw,Lr]),TR=Q([kt,wi,bi,xi,sw,Qn,eo,St]),RR=Q([Gn,vi,$i,ow,Jn,Yn,Xn,to]),IR=Q([Hn,Wn,Pv,lv,ui,_i,gi,Lr,Yv]),NR=Q([kt,ni,ki,hi,li,si,ii,ci,ct,yi,Qn,eo,St]),z=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===R.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qs(o.elicitations,r)}return new e(t,r,n)}},Qs=class extends z{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(R.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function ut(e){return e==="completed"||e==="failed"||e==="cancelled"}var aw=Symbol("Let zodToJsonSchema decide on which parser to use");var dI=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Si(e){let r=Ln(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Cd(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zi(e,t){let r=qe(e,t);if(!r.success)throw r.error;return r.data}var fw=6e4,ro=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(Hn,r=>{this._oncancel(r)}),this.setNotificationHandler(Wn,r=>{this._onprogress(r)}),this.setRequestHandler(Gn,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Jn,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(R.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Yn,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,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 z(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 i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new z(R.InvalidParams,`Task not found: ${s}`);if(!ut(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(ut(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[at]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Xn,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(R.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(to,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(R.InvalidParams,`Task not found: ${r.params.taskId}`);if(ut(o.status))throw new z(R.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new z(R.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(R.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,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,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),z.fromError(R.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=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),jr(s)||lp(s)?this._onresponse(s):ei(s)?this._onrequest(s,i):up(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},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=z.fromError(R.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,s=t.params?._meta?.[at]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:R.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{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 i=new AbortController;this._requestHandlerAbortControllers.set(t.id,i);let a=ip(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let d={relatedRequestId:t.id};s&&(d.relatedTask={taskId:s}),await this.notification(u,d)},sendRequest:async(u,d,p)=>{if(i.signal.aborted)throw new z(R.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:t.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;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:s,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(i.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async u=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:R.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{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)===i&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),jr(t))n(t);else{let i=new z(t.error.code,t.error.message,t.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(jr(t)&&t.result&&typeof t.result=="object"){let i=t.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),jr(t))o(t);else{let i=z.fromError(t.error.code,t.error.message,t.error.data);o(i)}}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(i){yield{type:"error",error:i instanceof z?i:new z(R.InternalError,String(i))}}return}let s;try{let i=await this.request(t,St,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(R.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},ut(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new z(R.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(R.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(R.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,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||{},[at]: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:s,onresumptiontoken:i}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let $=b instanceof z?b:new z(R.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??fw,_=()=>h(z.fromError(R.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=c?.taskId;if(w){let b=$=>{let E=this._responseHandlers.get(p);E?E($):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:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),u(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Qn,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},eo,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},fp,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||{},[at]: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||{},[at]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[at]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=Si(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=zi(t,o);return Promise.resolve(r(i,s))})}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=Si(t);this._notificationHandlers.set(n,o=>{let s=zi(t,o);return Promise.resolve(r(s))})}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"&&ei(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(R.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} 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,s)=>{if(r.aborted){s(new z(R.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(R.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 s=await n.getTask(o,r);if(!s)throw new z(R.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Lr.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ut(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new z(R.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(ut(a.status))throw new z(R.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Lr.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ut(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function bp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $p(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];bp(i)&&bp(s)?r[o]={...i,...s}:r[o]=s}return r}var mh=cs(pc(),1),hh=cs(fh(),1);function gS(){let e=new mh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,hh.default)(e),e}var qo=class{constructor(t){this._ajv=t??gS()}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 Zo=class{constructor(t){this._client=t}async*callToolStream(t,r=ct,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:t},r,s),a=o.getToolOutputValidator(t.name);for await(let c of i){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new z(R.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 z(R.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof z){yield{type:"error",error:u};return}yield{type:"error",error:new z(R.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 gh(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 yh(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 Mo(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 s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Mo(s,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Mo(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Mo(r,t)}}function yS(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 Lo=class extends ro{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 qo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",_i,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",gi,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",ui,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Zo(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=$p(this._capabilities,t)}setRequestHandler(t,r){let o=Ln(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ft(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,l)=>{let u=qe($i,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new z(R.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=yS(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new z(R.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new z(R.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let b=qe(St,h);if(!b.success){let $=b.error instanceof Error?b.error.message:String(b.error);throw new z(R.InvalidParams,`Invalid task creation result: ${$}`)}return b.data}let g=qe(xi,h);if(!g.success){let b=g.error instanceof Error?g.error.message:String(g.error);throw new z(R.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{Mo(w,_.content)}catch{}return _};return super.setRequestHandler(t,a)}if(i==="sampling/createMessage"){let a=async(c,l)=>{let u=qe(vi,c);if(!u.success){let _=u.error instanceof Error?u.error.message:String(u.error);throw new z(R.InvalidParams,`Invalid sampling request: ${_}`)}let{params:d}=u.data,p=await Promise.resolve(r(c,l));if(d.task){let _=qe(St,p);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new z(R.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let h=d.tools||d.toolChoice?bi:wi,g=qe(h,p);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new z(R.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:Ys,capabilities:this._capabilities,clientInfo:this._clientInfo}},ni,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!np.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){gh(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&yh(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},kt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},ki,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},kt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},hi,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},li,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},si,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},ii,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},ci,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},kt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},kt,r)}async callTool(t,r=ct,n){if(this.isToolTaskRequired(t.name))throw new z(R.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),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new z(R.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new z(R.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof z?i:new z(R.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}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},yi,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){let s=vp.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,l=async()=>{if(!i){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 ag=cs(sg(),1);import Tc from"node:process";import{PassThrough as KS}from"node:stream";var Uo=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),FS(r)}clear(){this._buffer=void 0}};function FS(e){return dp.parse(JSON.parse(e))}function ig(e){return JSON.stringify(e)+`
37
+ `}var VS=Tc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function HS(){let e={};for(let t of VS){let r=Tc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Fo=class{constructor(t){this._readBuffer=new Uo,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new KS)}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,ag.default)(this._serverParams.command,this._serverParams.args??[],{env:{...HS(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Tc.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=ig(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var GS=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var Dt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new Fo({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??WS(),stderr:t.stderr??"pipe"}),n=new Lo({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:QS(r).map(YS),nextCursor:cg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!Ko(n,["error"])&&tz(n,["ok","success"],!0),target:t,messageId:Fe(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:XS(r).map(ez).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=GS.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:JS(r)},ct);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let s=(Array.isArray(n.content)?n.content:[]).filter(i=>i.type==="text").map(i=>i.text??"").join(`
38
+ `).trim();if(!s)return{};try{return JSON.parse(s)}catch{return{text:s}}}};function WS(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function JS(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function QS(e){if(Array.isArray(e))return e;if(!fr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&fr(r)?[r]:[]}function YS(e){return fr(e)?{id:Fe(e,["id","message_id","messageId"]),cursor:cg(e,["cursor"]),type:Fe(e,["type","event_type","eventType"]),platform:Fe(e,["platform"]),target:Fe(e,["target"]),sessionKey:Fe(e,["session_key","sessionKey"]),timestamp:Fe(e,["timestamp","created_at","createdAt"]),message:Fe(e,["message","text","content"]),raw:e}:{raw:e}}function XS(e){if(Array.isArray(e))return e;if(!fr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function ez(e){if(!fr(e))return null;let t=Fe(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Fe(e,["platform"]),name:Fe(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Fe(e,t){let r=Ko(e,t);return typeof r=="string"?r:void 0}function tz(e,t,r){let n=Ko(e,t);return typeof n=="boolean"?n:r}function cg(e,t){let r=Ko(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function Ko(e,t){if(fr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as KE,writeFile as VE}from"node:fs/promises";import{join as Vg}from"node:path";import{existsSync as Vo}from"node:fs";import{mkdir as rz,readFile as Rc,writeFile as nz}from"node:fs/promises";import{dirname as Ic,isAbsolute as oz,join as mr,resolve as _t}from"node:path";var Ho="file://./.red/brain/brain.rdb",sz="RED_BRAIN_ROOT",iz="brain.root";async function az(e=process.cwd(),t={}){let n=(t.env??process.env)[sz];if(n)return _t(e,n);let o=await cz(e);if(o)return o;let s=_t(e),i=null;for(;;){let a=mr(s,".red");if(Vo(a)&&(i??=s,Vo(mr(a,"brain"))||Vo(mr(a,iz))))return s;let c=Ic(s);if(c===s)return i??_t(e);s=c}}async function cz(e){let t=_t(e);for(;;){let r=mr(t,".red","config.yaml");try{let o=await Rc(r,"utf8"),s=uz(o);if(s)return _t(t,s)}catch(o){if(o.code!=="ENOENT")throw o}let n=Ic(t);if(n===t)return null;t=n}}function uz(e){let t=lz(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 lz(e){let t={},r=[],n=[];for(let o of e.split(`
39
+ `)){let s=o.replace(/\r$/,"");if(!/".*"/.test(s)&&!/'.*'/.test(s)){let p=s.indexOf("#");p>=0&&(s=s.slice(0,p))}if(s.replace(/\s/g,"")==="")continue;let i=s.match(/^ */)?.[0].length??0;if(i%2!==0)continue;let a=s.slice(i).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]>=i;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(i)):t[d]=u}return t}function ug(e){return mr(_t(e),".red","brain","config.yaml")}function dz(e){return mr(_t(e),".env")}async function pz(e){let t=ug(e);return Vo(t)||(await rz(Ic(t),{recursive:!0}),await nz(t,`connection_string: ${Ho}
40
+ `,"utf8")),t}async function fz(e){let t=ug(e);try{let r=await Rc(t,"utf8");return mz(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function mz(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:Ho};let r=t.slice(18).trim();return{connection_string:lg(r)||Ho}}function lg(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function Go(e=process.cwd()){let t=await az(e),r=await pz(t),n=await fz(t)??{connection_string:Ho},o=await hz(t),s=n.connection_string,i=gz(s,o);return{rootDir:t,configPath:r,rawConnectionString:s,connectionString:yz(t,i)}}async function hz(e){let t={...process.env};try{let r=await Rc(dz(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s<=0)continue;let i=o.slice(0,s).trim(),a=lg(o.slice(s+1).trim());t[i]==null&&(t[i]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function gz(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let s=String(n??o),i=t[s];if(i==null||i==="")throw new Error(`Brain connection_string references missing environment variable ${s}`);return i})}function yz(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return oz(r)?t:`file://${_t(e,r)}`}var _z=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",vz=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function dg(e,t){return _z?bz(e,t):vz?xz(e,t):wz(e,t)}async function wz(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((s,i)=>{n.stdin.write(o,a=>a?i(a):s())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",s=>o(s??0))})}}}function bz(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:$z(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*$z(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 xz(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(s){await o.write(s)},end(){try{o.close()}catch{}}},stdout:kz(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*kz(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 Ez}from"node:url";import{dirname as Pz,resolve as Tz,join as h1}from"node:path";import{existsSync as Sz}from"node:fs";import{join as zz}from"node:path";function pg(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 s=zz(r,"bin",t);if(Sz(s))return s;throw new Error(`reddb: binary "${t}" not found.
41
+ expected at: ${s}
42
+ override: set ${n}=/path/to/${t}
43
+ fix: re-run \`pnpm install\` (the postinstall script downloads it),
44
+ or check the postinstall log for a download error.`)}var Rz=Pz(Ez(import.meta.url)),Iz=Tz(Rz,"..");function Nz(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function fg(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:pg({name:Nz(),packageRoot:Iz,envVar:"REDDB_BIN"})}var Az=new TextEncoder,Cz=new TextDecoder("utf-8"),I=class extends Error{constructor(t,r,n){super(r),this.name="RedDBError",this.code=t,this.data=n??null}},Wo=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 I("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((s,i)=>{this.pending.set(n,{resolve:s,reject:i}),this.child.stdin.write(Az.encode(o+`
45
+ `)).catch(a=>{this.pending.delete(n),i(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 s=0;s<t.length;s++)if(t[s]===10){let i=t.subarray(o,s);this.#r(Cz.decode(i)),o=s+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(s){this.#e(`malformed server response: ${s.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 I(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 I("CLIENT_CLOSED",t);for(let{reject:n}of this.pending.values())n(r);this.pending.clear()}};function Ac(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:/"?Oz(e):jz(e)}function Oz(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 I("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let n=r.searchParams,o=(n.get("proto")||"").toLowerCase(),s=r.pathname&&r.pathname!=="/"?r.pathname:"";if(r.hostname==="embedded.local")return s?{kind:"embedded",path:s,params:n,originalUri:e}:{kind:"embedded",params:n,originalUri:e};let i=Dz(o),a=r.port?Number(r.port):Nc(i),c=r.username?decodeURIComponent(r.username):void 0,l=r.password?decodeURIComponent(r.password):void 0;return{kind:i,host:r.hostname,port:a,path:s||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 jz(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=e.slice(`${t}://`.length),[n]=r.split(/[/?]/,1),[o,s]=n.split(":");if(!o)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let i=t==="reds"?"reds":t==="grpcs"?"grpcs":t==="grpc"?"grpc":"red";return{kind:i,host:o,port:s?Number(s):Nc(i),originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(r){throw new I("UNPARSEABLE_URI",`failed to parse '${e}': ${r.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Nc(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 I("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function Dz(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 I("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Nc(e){switch(e){case"http":return 8080;case"https":return 8443;case"red":case"reds":case"redwire":return 5050;case"grpc":return 5055;case"grpcs":return 5056;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var qz=new Set(["embedded"]),wn=class{constructor(t,r){this._client=t,this._transport=r??null}_guard(t){if(this._transport&&qz.has(this._transport))throw new I("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:Mz(n.value)}async put(t,r,n,o={}){this._guard("put");let s=Zz(n);await this._client.call("cache.put",{namespace:t,key:r,value:s,...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 Zz(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return mg(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return mg(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function mg(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 Mz(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 hr=class{constructor(t,r="kv_default"){this.client=t,this.collection=r}put(t,r,n={}){let o=n.collection??this.collection,s=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(hg).join(", ")}]`:"",i=n.expireMs!=null?` EXPIRE ${Number(n.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Cc(o,t)} = ${Bz(r)}${i}${s}`})}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 ${Cc(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 ${Cc(n,t)}`}),s=o.affected??o.affected_rows??0;return{affected:s,deleted:s>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 I("INVALID_ARGUMENT","kv.list limit must be a positive integer");let o=t.prefix==null?"":String(t.prefix),i=(await this.client.call("query",{sql:`SELECT key, value FROM ${Oc(r)} ORDER BY key ASC LIMIT ${n}`})).rows??[];return{items:o.length>0?i.filter(c=>String(c.key).startsWith(o)):i}}async invalidateTags(t,r={}){let n=r.collection??this.collection,o=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(hg).join(", ")}] FROM ${Oc(n)}`});return o.affected??o.affected_rows??o.rows?.[0]?.invalidated??0}async*watch(t,r={}){if(!this.client.baseUrl)throw new I("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 s=o.toString()?`?${o}`:"",i=`${this.client.baseUrl}/collections/${encodeURIComponent(n)}/kv/${encodeURIComponent(String(t))}/watch${s}`,a=await fetch(i,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new I("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
46
+
47
+ `)){let u=l.split(`
48
+ `).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,r={}){return this.watch(`${t}.*`,r)}};function Cc(e,t){return`${Oc(e)}.${Lz(t)}`}function Oc(e){let t=String(e),r=t.match(/[^A-Za-z0-9_]/);if(r)throw new I("INVALID_KV_KEY",`invalid KV key "${t}": character "${r[0]}" is not supported`);return t}function Lz(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function Bz(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 hg(e){return`'${String(e).replace(/'/g,"''")}'`}var bn=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${gr(t)}`})}push(t,r,n={}){let o=n.priority!=null?` PRIORITY ${Uz(n.priority)}`:"";return this.client.call("query",{sql:`QUEUE PUSH ${gr(t)} ${Fz(r)}${o}`})}async pop(t,r){let n=await this.client.call("query",{sql:`QUEUE POP ${gr(t)}${gg(r)}`});return yg(n)}async peek(t,r){let n=await this.client.call("query",{sql:`QUEUE PEEK ${gr(t)}${gg(r)}`});return yg(n)}async len(t){let r=await this.client.call("query",{sql:`QUEUE LEN ${gr(t)}`});return Number(r?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${gr(t)}`})}};function gr(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new I("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function gg(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new I("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function Uz(e){if(!Number.isInteger(e))throw new I("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Fz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?`'${e.replace(/'/g,"''")}'`:JSON.stringify(e)}function yg(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var $n=class{constructor(t){this.db=t}async insert(t,r){_g(r,"documents.insert document"),await this.ensureCollection(t);let n=await this.db.query(`INSERT INTO ${Jo(t)} DOCUMENT (body) VALUES (${wg(r)}) RETURNING *`),o=n.rows?.[0];if(!o||o.rid==null)throw new I("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 I("NOT_FOUND",`document ${String(r)} was not found`);return n.entity}async list(t,r={}){let n=Kz(r.limit),o=r.orderBy??r.order_by??"rid ASC",s=r.filter?` WHERE ${String(r.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${Jo(t)}${s} ORDER BY ${o} LIMIT ${n}`)).rows??[]}}async patch(t,r,n){_g(n,"documents.patch patch");let o=Object.entries(n);if(o.length===0)throw new I("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of o)if(c.includes("/"))throw new I("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let s=o.map(([c,l])=>`${vg(c)} = ${Vz(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Jo(t)} DOCUMENTS SET ${s} WHERE rid = $1 RETURNING *`,r)).rows?.[0];if(!a)throw new I("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 ${Jo(t)}`)}catch(r){if(!String(r?.message??"").includes("already exists"))throw r}}};function _g(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I("INVALID_ARGUMENT",`${t} must be an object`)}function Kz(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new I("INVALID_ARGUMENT","limit must be a positive integer");return e}function Jo(e){return String(e).split(".").map(vg).join(".")}function vg(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new I("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function wg(e){return bg(JSON.stringify(e))}function Vz(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?wg(e):bg(e)}function bg(e){return`'${String(e).replace(/'/g,"''")}'`}var xn=class{constructor(t,r="red.config"){this.client=t,this.collection=r}put(t,r,n={}){Gz(n,"config");let o=n.collection??this.collection,s=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map($g).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${vt(o)} ${vt(t)} = ${Hz(r,n)}${s}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${vt(n)} ${vt(t)}`})}resolve(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${vt(n)} ${vt(t)}`})}};function Hz(e,t){if(t.secretRef){let{collection:r,key:n}=t.secretRef;return`SECRET_REF(vault, ${vt(r)}.${vt(n)})`}return Wz(e)}function Gz(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 vt(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 Wz(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):$g(e)}function $g(e){return`'${String(e).replace(/'/g,"''")}'`}var kn=class{constructor(t,r="red.vault"){this.client=t,this.collection=r}put(t,r,n={}){Jz(n,"vault");let o=n.collection??this.collection,s=Array.isArray(n.tags)&&n.tags.length>0?` TAGS [${n.tags.map(xg).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${yr(o)}.${yr(t)} = ${Qz(r)}${s}`})}get(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${yr(n)}.${yr(t)}`})}unseal(t,r={}){let n=r.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${yr(n)}.${yr(t)}`})}};function Jz(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 yr(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 Qz(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 Sg(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(Yz)}async function zg(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${eE(t)}`)).rows??[]).some(n=>n.name===String(t))}var Sn=class e{constructor(t,r,n=null,o=[],s=[]){this.db=t,this.collection=r,this.columns=n,this.whereClauses=o,this.params=s}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 I("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(kg).join(", "),r=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(i=>`(${i})`).join(" AND ")}`:"",n=`SELECT ${t} FROM ${kg(this.collection)}${r}`,s=(this.params.length>0?await this.db.query(n,this.params):await this.db.query(n)).rows??[];return this.columns==null?s:s.map(i=>{let a={};for(let c of this.columns)a[c]=i[c];return a})}};function Yz(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function kg(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 I("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function eE(e){return`'${String(e).replace(/'/g,"''")}'`}var tE="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",rE="1.0",Tg="1.0.9",Eg="NESTED_TX_NOT_SUPPORTED";async function Rg(e,t={}){let r=Ac(e);if(lE(r),r.kind==="embedded"){let n=uE(r,t.auth);if(n.token||n.username)throw new I("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let o=cE(r),s=t.binary??fg(),i=await dg(s,o),a=new Wo(i);return await a.call("version",{}),new Dc(a,{transport:"embedded"})}}function Pg(e){return nE(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:sE(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&aE(e)?{$uuid:e}:e}function nE(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new I("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 I("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new I("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function oE(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Pg):e.map(Pg)}function sE(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 iE(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 aE(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Qo(e){if(Array.isArray(e))return e.map(Qo);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return iE(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]=Qo(o);return r}return e}function cE(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function uE(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 lE(e){if(e.kind!=="embedded")throw new I("EMBEDDED_ONLY",tE)}var Yo=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 qc()}},jc=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw qc();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 I("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 I("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 I("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let r=await t(new Yo(this.db));return await this.commit(),r}catch(r){if(this.active)try{await this.rollback()}catch(n){Ig(r,n)}throw r}}},Dc=class{constructor(t,r={}){this.client=t,this.transport=r.transport??null,this.helperSpecVersion=rE,this.cache=new wn(t,this.transport),this.queue=new bn(t),this.queues=this.queue,this.documents=new $n(this);let n=new hr(t);this.kv=Object.assign((o="kv_default")=>new hr(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 xn(t,o),this.vault=(o="red.vault")=>new kn(t,o),this.inTransaction=!1}query(t,...r){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new I("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let n=oE(r);return n==null?this.client.call("query",{sql:t}).then(Qo):this.client.call("query",{sql:t,params:n}).then(Qo)}execute(t,...r){return this.query(t,...r)}async insert(t,r){let n=await this.client.call("insert",{collection:t,payload:r});return dE(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 pE(n,r.length)}tx(){return new jc(this)}async transaction(t){if(this.inTransaction)throw qc();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 Yo(this));return await this.query("COMMIT"),n}catch(n){if(r)try{await this.query("ROLLBACK")}catch(o){Ig(n,o)}throw n}finally{this.inTransaction=!1}}exists(t){return zg(this,t)}list(){return Sg(this)}from(t){return new Sn(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 qc(){return new I(Eg,`${Eg}: nested transactions are not supported on one connection`)}function Ig(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function dE(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new I("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Tg} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function pE(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new I("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Tg} 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 I("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}import{createHash as fE}from"node:crypto";function Zc(e){return fE("sha256").update(e).digest("hex")}function Ng(e){return Zc(JSON.stringify(e))}function Ag(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"")||"artifact"}var Mc="unknown",Xo=class{artifacts;constructor(t){this.artifacts=t}events(t={}){let r=t.interval??"day",n=t.timeField??"event",o=Uc(t.from),s=Uc(t.to),i=this.artifacts.filter(f=>f.kind==="event").map(f=>mE(f,n)).filter(f=>f!=null).filter(f=>gE(f,t)).filter(f=>yE(f.ts,o,s)).sort((f,h)=>f.ts-h.ts),a=i.length,c=o??(i.length>0?i[0].ts:null),l=s??(i.length>0?i[i.length-1].ts:null),u=wE(c,l,r),p=[Cg(null,i,u,r)];if(t.groupBy){let h=[..._E(i,t.groupBy).entries()].map(([g,_])=>Cg(g,_,u,r)).sort((g,_)=>_.total-g.total||$E(g.group,_.group));p.push(...h)}return{kind:"event",interval:r,timeField:n,range:{from:c,to:l},total:a,series:p}}};function mE(e,t){let r=e.properties.metadata??{},n=hE(e,r,t);return n==null?null:{ts:n,platform:Lc(r,"platform")??Mc,eventType:Lc(r,"event_type")??Mc,target:Lc(r,"target")??Mc}}function hE(e,t,r){let n=Number.isFinite(e.properties.created_at)?e.properties.created_at:null;return r==="ingested"?n:Uc(t.timestamp)??n}function Lc(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function gE(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 yE(e,t,r){return!(t!=null&&e<t||r!=null&&e>r)}function _E(e,t){let r=new Map;for(let n of e){let o=vE(n,t),s=r.get(o);s?s.push(n):r.set(o,[n])}return r}function vE(e,t){switch(t){case"platform":return e.platform;case"event_type":return e.eventType;case"target":return e.target}}function Cg(e,t,r,n){let o=new Map;for(let i of t){let a=Bc(i.ts,n);o.set(a,(o.get(a)??0)+1)}let s=r.map(i=>({start:i,startIso:new Date(i).toISOString(),count:o.get(i)??0}));return{group:e,total:t.length,buckets:s}}function wE(e,t,r){if(e==null||t==null)return[];let n=[],o=Bc(e,r),s=Bc(t,r),i=0;for(;o<=s&&i<1e6;)n.push(o),o=bE(o,r),i++;return n}function Bc(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()),s=(new Date(n).getUTCDay()+6)%7;return n-s*864e5}case"month":return Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),1)}}function bE(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 Uc(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 $E(e,t){return String(e??"").localeCompare(String(t??""))}import{spawn as xE}from"node:child_process";var Kc=["supports","contradicts","related_to"];function Vc(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"&&Kc.includes(e)}function _r(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(`
49
+ `)}function kE(e){return{deriveConnections(t){return zE(e,t)}}}function jg(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return kE({command:t,args:EE(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:PE(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function SE(e){let t=JSON.parse(TE(e));return(Array.isArray(t)?t:Fc(t)&&Array.isArray(t.connections)?t.connections:[]).filter(RE).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 zE(e,t){let r=xE(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],s,i=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&&(s=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 i;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return SE(Buffer.concat(n).toString("utf8"))}finally{s&&clearTimeout(s)}}function EE(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 PE(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function TE(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function RE(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)}var es=["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"],Dg={contact:"person"},ts=["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"],wt={artifacts:"brain_artifacts",connections:"brain_connections",kv:"brain_kv"};var vr=class e{constructor(t){this.opts=t}db;artifactCache=null;connectionCache=null;static async open(t){let r=new e(t);return r.db=await Rg(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 ${wt.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${wt.connections}`)}kv(){return this.db.kv(wt.kv)}async capture(t){let r=Lg(t.kind??"note"),n=Date.now(),o=AE(t.tags??[]),s=Ng([r,t.title,t.content,o,t.sourcePath,t.sourceSession]),i=await this.findArtifactByHash(s);if(i!=null){let g=await this.getArtifact(i);if(g)return g}let a=await this.listArtifacts(),c=`${Ag(t.title)}-${s.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:s,metadata:t.metadata},u={label:c,kind:r,properties:l},p=(await this.db.query(`INSERT INTO ${wt.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u.label,u.kind,s,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(Zg(s),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 ${wt.artifacts}`);this.artifactCache=t.rows.map(IE).filter(Gc)}return this.artifactCache}async search(t,r=10,n={}){let o=CE(t),s=new Set(n.excludeRids??[]),i=await this.listArtifacts(),a=await this.listConnections(),c=new Map(i.map(u=>[u.rid,u]));return i.filter(u=>!s.has(u.rid)).map(u=>{let d=Fg(u,o),p=Kg({...d,connections:OE(u,o,a,c),vector:0});return{artifact:u,score:p.total,score_breakdown:p,excerpt:DE(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=Bg(t.kind??"related_to"),s=await this.findConnection(r.rid,n.rid,o);if(s!=null){let u=(await this.listConnections()).find(d=>d.rid===s);if(u)return u}let i={reason:t.reason,confidence:t.confidence??"explicit",created_at:Date.now(),metadata:t.metadata},c=(await this.db.query(`INSERT INTO ${wt.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,o,r.rid,n.rid,1,i)).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(Mg(r.rid,n.rid,o),l),this.connectionCache=null,{rid:l,kind:o,from_rid:r.rid,to_rid:n.rid,weight:1,properties:i}}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 ${wt.connections}`);this.connectionCache=t.rows.map(NE).filter(Gc)}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:FE(t.map(n=>n.kind))}}async eventKpis(t={}){let r=await this.listArtifacts();return new Xo(r).events(t)}async think(t,r=8,n={}){let o=(await this.search(t,Math.max(r*2,r+5),n)).filter(s=>!_r(s.artifact)).slice(0,r);return qE(t,o)}async deriveAutoLinks(t){return this.autoLinkArtifact(t,await this.listArtifacts())}async findArtifactByHash(t){let r=await this.kv().get(Zg(t));return r!=null?Number(r):null}async findConnection(t,r,n){let o=await this.kv().get(Mg(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||_r(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),s=new Set([t.rid]);for(let d of r)_r(d)&&s.add(d.rid);let i=await this.think(o,8,{excludeRids:s}),a=i.hits.filter(d=>n.has(d.artifact.rid)&&!_r(d.artifact)).map(d=>({artifact:Vc(d.artifact),score:d.score,excerpt:d.excerpt}));if(a.length===0)return[];let c={newArtifact:Vc(t),candidates:a,think:{query:o,answer:i.answer},allowedKinds:Kc},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 Lg(e){let r=Dg[e]??e;if(es.includes(r))return r;throw new Error(`invalid Brain artifact kind: ${e}`)}function Bg(e){if(ts.includes(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function IE(e){let t=Number(e.red_entity_id??e.rid),r=Ug(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),s=String(r.title??e.label??e.LABEL??o),i=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:Lg(n),properties:{...r,id:o,title:s,content:i,tags:a,created_at:Number(r.created_at??c),updated_at:Number(r.updated_at??r.created_at??c),hash:String(r.hash??"")}}}function NE(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:Bg(o),from_rid:r,to_rid:n,weight:Number(e.weight??1),properties:Ug(e.properties??e.PROPERTIES)}}function Ug(e){return e==null?{}:typeof e=="string"?JSON.parse(e):e}function Gc(e){return e!=null}function AE(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function CE(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function qg(e,t){let r=0,n=e.indexOf(t);for(;n>=0;)r++,n=e.indexOf(t,n+t.length);return r}function Fg(e,t){let r=e.properties.title.toLowerCase(),n=e.properties.content.toLowerCase(),o=e.properties.tags.map(i=>i.toLowerCase()),s=e.kind.toLowerCase();return{lexical:t.reduce((i,a)=>i+qg(r,a)*3+qg(n,a),0),tags:t.reduce((i,a)=>{let c=o.reduce((l,u)=>u===a?l+4:u.includes(a)||a.includes(u)?l+2:l,0);return i+c},0),kind:t.reduce((i,a)=>s===a?i+3:s.includes(a)||a.includes(s)?i+1:i,0)}}function OE(e,t,r,n){let o=0;for(let s of r){let i=s.from_rid===e.rid?s.to_rid:s.to_rid===e.rid?s.from_rid:null;if(i==null)continue;let a=n.get(i);if(!a||_r(a))continue;let c=Kg({...Fg(a,t),connections:0,vector:0}).total;c<=0||(o+=Math.min(c,12)*jE(s.kind))}return qt(o*.35)}function jE(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 Kg(e){return{...e,lexical:qt(e.lexical),tags:qt(e.tags),kind:qt(e.kind),connections:qt(e.connections),vector:qt(e.vector),total:qt(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function qt(e){return Math.round(e*1e3)/1e3}function DE(e,t){if(e.length<=220)return e;let r=e.toLowerCase(),n=t.map(s=>r.indexOf(s)).filter(s=>s>=0).sort((s,i)=>s-i)[0]??0,o=Math.max(0,n-80);return`${o>0?"...":""}${e.slice(o,o+220)}${o+220<e.length?"...":""}`}function qE(e,t){let r=t.map(ZE),n=ME(t),o=LE(e,r,n);return{hits:t,citations:r,confidence:n,missing_evidence:o,answer:BE(e,r,n,o)}}function ZE(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 ME(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 LE(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 BE(e,t,r,n){if(t.length===0)return[`Brain has no cited evidence for "${e}".`,"","Missing evidence:",...n.map(a=>`- ${a}`)].join(`
50
+ `);let o=t.slice(0,5).map(a=>`- ${a.title}: ${a.excerpt} [${a.ref}]`),s=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}]`:""}; ${UE(a)}`}),i=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:",...i,"","Citations:",...s].join(`
51
+ `)}function UE(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(Gc);return`source: ${t.length>0?t.join(", "):`Brain artifact ${e.id}`}`}function Zg(e){return`artifact.hash.${e}`}function Mg(e,t,r){return`connection.${e}.${r}.${t}`}function FE(e){let t={};for(let r of e)t[r]=(t[r]??0)+1;return t}async function Hg(e,t){if(e!=="SessionStart")return{};let r=await Go(process.cwd()),n=await vr.open({uri:r.connectionString});try{await n.status()}finally{await n.close()}let o=Vg(r.rootDir,".red","brain","sessions");return await KE(o,{recursive:!0}),await VE(Vg(o,"last-session.json"),JSON.stringify({runner:t,lifecycle:e,rootDir:r.rootDir,connectionString:r.connectionString,startedAt:new Date().toISOString()},null,2),"utf8"),{}}var rs=class{map({event:t,sourceAgent:r}){return{title:HE(t),content:GE(t),kind:"event",tags:WE(t),sourceAgent:r??"brain.ingest-events",sourceRunner:"hermes",sourceSession:Gg(t),metadata:JE(t)}}};function Gg(e){return e.id?`evt:${e.id}`:e.cursor!=null?`cursor:${String(e.cursor)}`:`hash:${Zc(JSON.stringify({platform:e.platform??null,target:e.target??null,timestamp:e.timestamp??null,message:e.message??null}))}`}function HE(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 GE(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(`
52
+ `)||JSON.stringify(e.raw)}function WE(e){let t=new Set(["channel-event"]);return e.platform&&t.add(e.platform),e.type&&t.add(e.type),Array.from(t)}function JE(e){let t={event_key:Gg(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 ns(e){let t=new rs,r=await e.bridge.poll({afterCursor:e.afterCursor,sessionKey:e.sessionKey,limit:e.limit}),n=new Set((await e.store.listArtifacts()).map(i=>i.rid)),o=0,s=0;for(let i of r.events){let a=t.map({event:i,sourceAgent:e.sourceAgent}),c=await e.store.capture(a);n.has(c.rid)?s++:(o++,n.add(c.rid))}return{polled:r.events.length,captured:o,skipped:s,nextCursor:r.nextCursor}}import{basename as QE}from"node:path";async function YE(e=process.cwd()){let t=await Go(e),r=await vr.open({uri:t.connectionString,autoLinker:jg()});return{config:t,store:r,project:QE(t.rootDir)}}async function Pe(e,t=process.cwd()){let r=await YE(t);try{return await e(r)}finally{await r.store.close()}}var Zt=class extends Error{constructor(t,r){super(t),this.name="BrainActError",r?.cause!==void 0&&(this.cause=r.cause)}};async function Jg(e,t={}){let r=e.target?.trim(),n=e.message;if(!r)throw new Zt("brain_act requires a non-empty channel target");if(!n||!n.trim())throw new Zt("brain_act requires a non-empty message");let o=t.connect??(a=>Dt.connect(a)),s=t.process??XE(t.env??process.env),i;try{i=await o(s)}catch(a){throw new Zt(`brain_act could not reach the channel bridge: ${Wg(a)}`,{cause:a})}try{let a;try{a=await i.send(r,n)}catch(c){throw new Zt(`brain_act could not send to "${r}": ${Wg(c)}`,{cause:c})}if(!a.ok)throw new Zt(`brain_act could not send to "${r}": ${eP(a)}`);return{ok:!0,target:a.target,messageId:a.messageId,raw:a.raw}}finally{await i.close().catch(()=>{})}}function XE(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 eP(e){return tP(e.raw,["error","message","reason","detail"])??"the channel bridge reported a failed send"}function tP(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 Wg(e){return e instanceof Error?e.message:String(e)}import{createServer as rP}from"node:http";async function Xg(e,t){let r=await e.listArtifacts(),n=await e.listConnections(),o=new Map(r.map(u=>[u.rid,u])),s=await e.eventKpis({interval:"day"}),i=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:s.total,supports:Wc(n,"supports"),contradicts:Wc(n,"contradicts"),depends_on:Wc(n,"depends_on")},kpis:{events_daily:s,events_by_platform:i,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=>nP(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=>oP(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 ey(e){return{contract:{name:"brain.dashboard.viewer",version:"brain.dashboard.viewer.v1",consumes:"brain.dashboard.v1"},html:sP(e)}}async function ty(e,t={}){let r=t.host??"127.0.0.1",n=t.port??4738,o=rP((s,i)=>{let a=s.url??"/";if(a==="/"||a==="/dashboard"){i.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),i.end(e);return}i.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),i.end(`not found
53
+ `)});return await new Promise((s,i)=>{o.once("error",i),o.listen(n,r,()=>{o.off("error",i),s()})}),o}function nP(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:cP(e.properties.content)}}function oP(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 sP(e){return`<!doctype html>
54
+ <html lang="en">
55
+ <head>
56
+ <meta charset="utf-8">
57
+ <meta name="viewport" content="width=device-width, initial-scale=1">
58
+ <title>Brain Dashboard</title>
59
+ <style>
60
+ :root {
61
+ color-scheme: light;
62
+ --ink: #17202a;
63
+ --muted: #667085;
64
+ --line: #d8dee8;
65
+ --surface: #ffffff;
66
+ --band: #f6f7f9;
67
+ --accent: #2f6f73;
68
+ --accent-2: #8b5f2a;
69
+ --risk: #9f3a38;
70
+ --good: #2f7d56;
71
+ }
72
+ * { box-sizing: border-box; }
73
+ body {
74
+ margin: 0;
75
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
76
+ background: var(--band);
77
+ color: var(--ink);
78
+ letter-spacing: 0;
79
+ }
80
+ header {
81
+ display: grid;
82
+ gap: 12px;
83
+ padding: 28px clamp(18px, 4vw, 48px) 18px;
84
+ border-bottom: 1px solid var(--line);
85
+ background: var(--surface);
86
+ }
87
+ h1 {
88
+ margin: 0;
89
+ font-size: 30px;
90
+ line-height: 1.1;
91
+ font-weight: 720;
92
+ }
93
+ h2 {
94
+ margin: 0 0 12px;
95
+ font-size: 16px;
96
+ line-height: 1.2;
97
+ }
98
+ .meta {
99
+ color: var(--muted);
100
+ font-size: 13px;
101
+ line-height: 1.45;
102
+ overflow-wrap: anywhere;
103
+ }
104
+ main {
105
+ display: grid;
106
+ gap: 18px;
107
+ padding: 18px clamp(18px, 4vw, 48px) 48px;
108
+ }
109
+ .metrics {
110
+ display: grid;
111
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
112
+ gap: 10px;
113
+ }
114
+ .metric, section {
115
+ background: var(--surface);
116
+ border: 1px solid var(--line);
117
+ border-radius: 8px;
118
+ box-shadow: 0 1px 2px rgba(23, 32, 42, 0.04);
119
+ }
120
+ .metric {
121
+ min-height: 92px;
122
+ padding: 14px;
123
+ display: grid;
124
+ align-content: space-between;
125
+ gap: 10px;
126
+ }
127
+ .metric strong {
128
+ display: block;
129
+ font-size: 26px;
130
+ line-height: 1;
131
+ font-weight: 760;
132
+ }
133
+ .metric span {
134
+ color: var(--muted);
135
+ font-size: 12px;
136
+ text-transform: uppercase;
137
+ letter-spacing: .08em;
138
+ }
139
+ section { padding: 16px; }
140
+ .grid {
141
+ display: grid;
142
+ grid-template-columns: minmax(0, 1.2fr) minmax(280px, .8fr);
143
+ gap: 18px;
144
+ align-items: start;
145
+ }
146
+ .bars {
147
+ display: grid;
148
+ gap: 8px;
149
+ margin-top: 10px;
150
+ }
151
+ .bar {
152
+ display: grid;
153
+ grid-template-columns: 120px minmax(0, 1fr) 42px;
154
+ gap: 10px;
155
+ align-items: center;
156
+ font-size: 13px;
157
+ }
158
+ .track {
159
+ height: 10px;
160
+ border-radius: 999px;
161
+ background: #e8edf2;
162
+ overflow: hidden;
163
+ }
164
+ .fill {
165
+ height: 100%;
166
+ background: var(--accent);
167
+ }
168
+ .feed {
169
+ display: grid;
170
+ gap: 10px;
171
+ }
172
+ .item {
173
+ border-top: 1px solid var(--line);
174
+ padding-top: 10px;
175
+ }
176
+ .item:first-child {
177
+ border-top: 0;
178
+ padding-top: 0;
179
+ }
180
+ .item h3 {
181
+ margin: 0 0 5px;
182
+ font-size: 14px;
183
+ line-height: 1.3;
184
+ }
185
+ .tags {
186
+ display: flex;
187
+ flex-wrap: wrap;
188
+ gap: 6px;
189
+ margin-top: 8px;
190
+ }
191
+ .tag {
192
+ border: 1px solid var(--line);
193
+ border-radius: 999px;
194
+ padding: 2px 8px;
195
+ font-size: 12px;
196
+ color: var(--muted);
197
+ background: #fbfcfd;
198
+ }
199
+ .edge {
200
+ display: inline-flex;
201
+ align-items: center;
202
+ min-height: 22px;
203
+ border-radius: 999px;
204
+ padding: 2px 8px;
205
+ font-size: 12px;
206
+ color: #fff;
207
+ background: var(--accent-2);
208
+ }
209
+ .edge.supports { background: var(--good); }
210
+ .edge.contradicts { background: var(--risk); }
211
+ .empty {
212
+ color: var(--muted);
213
+ border-top: 1px solid var(--line);
214
+ padding-top: 10px;
215
+ font-size: 13px;
216
+ }
217
+ footer {
218
+ padding: 0 clamp(18px, 4vw, 48px) 28px;
219
+ }
220
+ @media (max-width: 780px) {
221
+ .grid { grid-template-columns: 1fr; }
222
+ .bar { grid-template-columns: 86px minmax(0, 1fr) 34px; }
223
+ h1 { font-size: 24px; }
224
+ }
225
+ </style>
226
+ </head>
227
+ <body>
228
+ <header>
229
+ <h1>${se(e.project)} Brain Dashboard</h1>
230
+ <div class="meta">${se(e.root)} - ${se(e.generated_at)}</div>
231
+ </header>
232
+ <main>
233
+ <div class="metrics">
234
+ ${wr("Artifacts",e.stats.artifacts,"captured knowledge")}
235
+ ${wr("Decisions",e.stats.decisions,"curated choices")}
236
+ ${wr("Events",e.stats.events,"KpiQuery total")}
237
+ ${wr("Connections",e.stats.connections,"typed graph edges")}
238
+ ${wr("Supports",e.stats.supports,"positive evidence")}
239
+ ${wr("Contradicts",e.stats.contradicts,"open tension")}
240
+ </div>
241
+ <div class="grid">
242
+ <section>
243
+ <h2>Event KPIs</h2>
244
+ <div class="meta">Derived from kind:event artifacts through KpiQuery. No separate metrics store.</div>
245
+ ${Qg(e.kpis.events_by_platform,"Platform")}
246
+ ${Qg(e.kpis.events_by_type,"Event type")}
247
+ </section>
248
+ <section>
249
+ <h2>Recent Decisions</h2>
250
+ <div class="feed">
251
+ ${e.recent_decisions.length===0?Yg("No decision artifacts captured yet."):e.recent_decisions.map(iP).join("")}
252
+ </div>
253
+ </section>
254
+ </div>
255
+ <section>
256
+ <h2>Recent Connections</h2>
257
+ <div class="feed">
258
+ ${e.recent_connections.length===0?Yg("No graph connections captured yet."):e.recent_connections.map(aP).join("")}
259
+ </div>
260
+ </section>
261
+ </main>
262
+ <footer class="meta">${se(e.attribution.red_hermes)}</footer>
263
+ <script id="brain-dashboard-data" type="application/json">${uP(e)}</script>
264
+ </body>
265
+ </html>`}function wr(e,t,r){return`<div class="metric"><span>${se(e)}</span><strong>${t}</strong><div class="meta">${se(r)}</div></div>`}function Qg(e,t){let r=e.series.filter(o=>o.group!=null);if(r.length===0)return`<div class="empty">No ${se(t.toLowerCase())} split available.</div>`;let n=Math.max(...r.map(o=>o.total),1);return`<div class="bars" aria-label="${se(t)}">${r.map(o=>{let s=o.group??"all",i=Math.round(o.total/n*100);return`<div class="bar"><div class="meta">${se(s)}</div><div class="track"><div class="fill" style="width:${i}%"></div></div><strong>${o.total}</strong></div>`}).join("")}</div>`}function iP(e){let t=e.connection_counts,r=e.tags.length===0?"":`<div class="tags">${e.tags.slice(0,6).map(n=>`<span class="tag">${se(n)}</span>`).join("")}</div>`;return`<article class="item">
266
+ <h3>${se(e.title)}</h3>
267
+ <div class="meta">#${e.rid} - ${se(e.updated_at)} - supports ${t.supports}, contradicts ${t.contradicts}, depends_on ${t.depends_on}, related_to ${t.related_to}</div>
268
+ <p class="meta">${se(e.excerpt)}</p>
269
+ ${r}
270
+ </article>`}function aP(e){return`<article class="item">
271
+ <h3><span class="edge ${se(e.kind)}">${se(e.kind)}</span> ${se(e.from.title)} -> ${se(e.to.title)}</h3>
272
+ <div class="meta">#${e.rid} - ${se(e.created_at)}${e.reason?` - ${se(e.reason)}`:""}</div>
273
+ </article>`}function Yg(e){return`<div class="empty">${se(e)}</div>`}function Wc(e,t){return e.filter(r=>r.kind===t).length}function cP(e){let t=e.replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}function se(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 uP(e){return JSON.stringify(e).replace(/</g,"\\u003c")}import{mkdir as lP,readFile as dP,writeFile as pP}from"node:fs/promises";import{dirname as fP}from"node:path";async function ry(e){let t=await ns({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 ny(e){try{let t=await dP(e,"utf8");return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return{};throw t}}async function oy(e,t){await lP(fP(e),{recursive:!0}),await pP(e,JSON.stringify(t,null,2)+`
274
+ `,"utf8")}async function _P(){let[e="help",...t]=process.argv.slice(2);switch(e){case"help":case"--help":case"-h":NP();return;case"init":await Pe(async({config:r,store:n})=>{let o=await n.status();ze({rootDir:r.rootDir,configPath:r.configPath,...o})});return;case"status":await Pe(async({config:r,store:n})=>{ze({rootDir:r.rootDir,configPath:r.configPath,...await n.status()})});return;case"capture":await vP(t);return;case"search":await wP(t);return;case"think":case"query":await bP(t);return;case"get":await $P(t);return;case"link":await xP(t);return;case"backlinks":await kP(t);return;case"act":await TP(t);return;case"hook":await RP(t);return;case"ingest-events":await zP(t);return;case"schedule-ingest":await SP(t);return;case"kpi":case"kpis":await EP(t);return;case"dashboard":await PP(t);return;default:throw new Error(`unknown brain command: ${e}`)}}async function vP(e){let t=Ye(e),r=(Z(t,"title")??t._.join(" ").slice(0,80))||"Untitled artifact",n=Z(t,"content")??(Z(t,"file")?await mP(String(Z(t,"file")),"utf8"):t._.join(" "));if(!n.trim())throw new Error("brain capture requires content, --content, or --file");await Pe(async({store:o})=>{let s=await o.capture({title:r,content:n,kind:Z(t,"kind")??"note",tags:IP(t,"tag"),sourceAgent:Z(t,"agent"),sourceRunner:Z(t,"runner"),sourceSession:Z(t,"session"),sourcePath:process.cwd()});ze(s)})}async function wP(e){let t=Ye(e),r=Z(t,"query")??t._.join(" ");if(!r)throw new Error("brain search requires a query");let n=zn(t,"limit")??10;await Pe(async({store:o})=>ze(await o.search(r,n)))}async function bP(e){let t=Ye(e),r=Z(t,"query")??t._.join(" ");if(!r)throw new Error("brain think requires a query");let n=zn(t,"limit")??8;await Pe(async({store:o})=>{let s=await o.think(r,n);t.json===!0?ze(s):console.log(s.answer)})}async function $P(e){let t=e[0];if(!t)throw new Error("brain get requires a rid or artifact id");await Pe(async({store:r})=>{let n=await r.getArtifact(os(t));if(!n)throw new Error(`Brain artifact not found: ${t}`);ze(n)})}async function xP(e){let t=Ye(e),r=Z(t,"from"),n=Z(t,"to");if(!r||!n)throw new Error("brain link requires --from and --to");await Pe(async({store:o})=>{ze(await o.link({from:os(r),to:os(n),kind:Z(t,"kind")??"related_to",reason:Z(t,"reason")}))})}async function kP(e){let t=e[0];if(!t)throw new Error("brain backlinks requires a rid or artifact id");await Pe(async({store:r})=>ze(await r.backlinks(os(t))))}async function SP(e){let t=Ye(e),r=Z(t,"session-key")??Z(t,"session"),n=zn(t,"limit"),o=await Dt.connect();try{await Pe(async({config:s,store:i})=>{let a=Z(t,"state")??sy(s.rootDir,".red","brain","ingestion-state.json"),c=await ny(a),l=await ry({bridge:o,store:i,state:c,sessionKey:r??void 0,limit:n??void 0,sourceAgent:"brain.schedule-ingest"});await oy(a,l.state),ze(l)})}finally{await o.close().catch(()=>{})}}async function zP(e){let t=Ye(e),r=Z(t,"after-cursor")??Z(t,"cursor"),n=Z(t,"session-key")??Z(t,"session"),o=zn(t,"limit"),s=await Dt.connect();try{await Pe(async({store:i})=>{let a=await ns({bridge:s,store:i,afterCursor:r??void 0,sessionKey:n??void 0,limit:o??void 0,sourceAgent:"brain.ingest-events"});ze(a)})}finally{await s.close().catch(()=>{})}}async function EP(e){let t=Ye(e),r=Z(t,"interval"),n=Z(t,"group-by"),o=Z(t,"time-field");await Pe(async({store:s})=>{ze(await s.eventKpis({interval:r,groupBy:n,timeField:o,from:Z(t,"from"),to:Z(t,"to"),platform:Z(t,"platform"),eventType:Z(t,"event-type"),target:Z(t,"target")}))})}async function PP(e){let t=Ye(e),r=await Pe(async({config:o,store:s,project:i})=>{let a=await Xg(s,{project:i,rootDir:o.rootDir});return{dashboard:a,artifact:ey(a),defaultOut:sy(o.rootDir,".red","brain","dashboard.html")}});if(t.json===!0){ze(r.dashboard);return}if(t.serve===!0){let o=Z(t,"host")??"127.0.0.1",s=zn(t,"port")??4738,i=await ty(r.artifact.html,{host:o,port:s}),a=i.address();console.log(`brain: dashboard serving at http://${a.address}:${a.port}/`),await new Promise(c=>{let l=()=>i.close(()=>c());process.once("SIGINT",l),process.once("SIGTERM",l)});return}let n=Z(t,"out")??r.defaultOut;await hP(yP(n),{recursive:!0}),await gP(n,r.artifact.html,"utf8"),console.log(`brain: dashboard written ${n}`)}async function TP(e){let t=Ye(e),r=Z(t,"target")??t._[0],n=Z(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>");ze(await Jg({target:r,message:n}))}async function RP(e){let[t="SessionStart",...r]=e,n=Ye(r),o=Z(n,"runner")??"unknown";ze(await Hg(t,o))}function os(e){return/^\d+$/.test(e)?Number(e):e}function Ye(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),s=e[r+1],i=s&&!s.startsWith("--")?e[++r]:!0,a=t[o];a==null||a===!1?t[o]=i:Array.isArray(a)?a.push(String(i)):t[o]=[String(a),String(i)]}return t}function Z(e,t){let r=e[t];if(typeof r=="string")return r;if(Array.isArray(r))return r[r.length-1]}function IP(e,t){let r=e[t];return typeof r=="string"?[r]:Array.isArray(r)?r:[]}function zn(e,t){let r=Z(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 ze(e){console.log(JSON.stringify(e,null,2))}function NP(){console.log(`brain commands:
275
+ init
276
+ status
277
+ capture [text] --title <title> --kind <${es.join("|")}> --tag <tag>
278
+ search <query> [--limit N]
279
+ think <query> [--limit N] [--json]
280
+ get <rid|id>
281
+ link --from <rid|id> --to <rid|id> --kind <${ts.join("|")}>
282
+ backlinks <rid|id>
283
+ act --target <channel> --message <text>
284
+ ingest-events [--after-cursor N] [--session-key KEY] [--limit N]
285
+ schedule-ingest [--session-key KEY] [--limit N] [--state PATH]
286
+ 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]
287
+ dashboard [--out PATH] [--json] [--serve] [--host 127.0.0.1] [--port 4738]
288
+ `)}_P().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});