@aifight/aifight 0.1.0-alpha.1 → 0.1.0-alpha.3

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.
package/dist/bin.mjs CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "module"; const require = createRequire(import.meta.url);
3
- var ph=Object.create;var Ec=Object.defineProperty;var gh=Object.getOwnPropertyDescriptor;var yh=Object.getOwnPropertyNames;var _h=Object.getPrototypeOf,wh=Object.prototype.hasOwnProperty;var Z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yh(e))!wh.call(t,o)&&o!==n&&Ec(t,o,{get:()=>e[o],enumerable:!(r=gh(e,o))||r.enumerable});return t};var Ae=(t,e,n)=>(n=t!=null?ph(_h(t)):{},vh(e||!t||!t.__esModule?Ec(n,"default",{value:t,enumerable:!0}):n,t));var ir=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var rr=class{};D._CodeOrName=rr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qt=class extends rr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=qt;var xe=class extends rr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof qt&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Dc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)yi(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Dc;var gi=new xe("+");function Fc(t,...e){let n=[or(t[0])],r=0;for(;r<e.length;)n.push(gi),yi(n,e[r]),n.push(gi,or(t[++r]));return Nh(n),new xe(n)}D.str=Fc;function yi(t,e){e instanceof xe?t.push(...e._items):e instanceof qt?t.push(e):t.push(jh(e))}D.addCodeArg=yi;function Nh(t){let e=1;for(;e<t.length-1;){if(t[e]===gi){let n=Mh(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Mh(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof qt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof qt))return`"${t}${e.slice(1)}`}function Lh(t,e){return e.emptyStr()?t:t.emptyStr()?e:Fc`${t}${e}`}D.strConcat=Lh;function jh(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:or(Array.isArray(t)?t.join(","):t)}function Dh(t){return new xe(or(t))}D.stringify=Dh;function or(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=or;function Fh(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Dc`[${t}]`}D.getProperty=Fh;function Bh(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Bh;function qh(t){return new xe(t.toString())}D.regexpCode=qh});var vi=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.ValueScope=we.ValueScopeName=we.Scope=we.varKinds=we.UsedValueState=void 0;var _e=ir(),_i=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},no;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(no||(we.UsedValueState=no={}));we.varKinds={const:new _e.Name("const"),let:new _e.Name("let"),var:new _e.Name("var")};var ro=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _e.Name?e:this.name(e)}name(e){return new _e.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};we.Scope=ro;var oo=class extends _e.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_e._)`.${new _e.Name(n)}[${r}]`}};we.ValueScopeName=oo;var Uh=(0,_e._)`\n`,wi=class extends ro{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Uh:_e.nil}}get(){return this._scope}name(e){return new oo(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_e._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=_e.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,no.Started);let u=n(l);if(u){let d=this.opts.es5?we.varKinds.var:we.varKinds.const;i=(0,_e._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,_e._)`${i}${u}${this.opts._n}`;else throw new _i(l);c.set(l,no.Completed)})}return i}};we.ValueScope=wi});var A=_(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.or=C.and=C.not=C.CodeGen=C.operators=C.varKinds=C.ValueScopeName=C.ValueScope=C.Scope=C.Name=C.regexpCode=C.stringify=C.getProperty=C.nil=C.strConcat=C.str=C._=void 0;var N=ir(),Le=vi(),St=ir();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return St._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return St.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return St.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return St.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return St.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return St.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return St.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return St.Name}});var co=vi();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return co.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return co.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return co.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return co.varKinds}});C.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var st=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},bi=class extends st{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?Le.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=_n(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},io=class extends st{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=_n(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return ao(e,this.rhs)}},Si=class extends io{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ei=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},$i=class extends st{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ki=class extends st{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ri=class extends st{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=_n(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},sr=class extends st{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Hh(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wt(e,n.names),{})}},at=class extends sr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Pi=class extends sr{},yn=class extends at{};yn.kind="else";var Ut=class t extends at{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new yn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Bc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=_n(this.condition,e,n),this}get names(){let e=super.names;return ao(e,this.condition),this.else&&Wt(e,this.else.names),e}};Ut.kind="if";var Ht=class extends at{};Ht.kind="for";var Ti=class extends Ht{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=_n(this.iteration,e,n),this}get names(){return Wt(super.names,this.iteration.names)}},Ai=class extends Ht{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?Le.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=ao(super.names,this.from);return ao(e,this.to)}},so=class extends Ht{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=_n(this.iterable,e,n),this}get names(){return Wt(super.names,this.iterable.names)}},ar=class extends at{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ar.kind="func";var cr=class extends sr{render(e){return"return "+super.render(e)}};cr.kind="return";var xi=class extends at{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Wt(e,this.catch.names),this.finally&&Wt(e,this.finally.names),e}},lr=class extends at{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};lr.kind="catch";var ur=class extends at{render(e){return"finally"+super.render(e)}};ur.kind="finally";var Ci=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
- `:""},this._extScope=e,this._scope=new Le.Scope({parent:e}),this._nodes=[new Pi]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new bi(e,i,r)),i}const(e,n,r){return this._def(Le.varKinds.const,e,n,r)}let(e,n,r){return this._def(Le.varKinds.let,e,n,r)}var(e,n,r){return this._def(Le.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new io(e,n,r))}add(e,n){return this._leafNode(new Si(e,C.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ri(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Ut(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ut(e))}else(){return this._elseNode(new yn)}endIf(){return this._endBlockNode(Ut,yn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Ti(e),n)}forRange(e,n,r,o,i=this.opts.es5?Le.varKinds.var:Le.varKinds.let){let s=this._scope.toName(e);return this._for(new Ai(i,s,n,r),()=>o(s))}forOf(e,n,r,o=Le.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new so("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?Le.varKinds.var:Le.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new so("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Ht)}label(e){return this._leafNode(new Ei(e))}break(e){return this._leafNode(new $i(e))}return(e){let n=new cr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(cr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new xi;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new lr(i),n(i)}return r&&(this._currNode=o.finally=new ur,this.code(r)),this._endBlockNode(lr,ur)}throw(e){return this._leafNode(new ki(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new ar(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ar)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ut))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};C.CodeGen=Ci;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function ao(t,e){return e instanceof N._CodeOrName?Wt(t,e.names):t}function _n(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Hh(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Bc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${Ii(t)}`}C.not=Bc;var Wh=qc(C.operators.AND);function Vh(...t){return t.reduce(Wh)}C.and=Vh;var Gh=qc(C.operators.OR);function zh(...t){return t.reduce(Gh)}C.or=zh;function qc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${Ii(e)} ${t} ${Ii(n)}`}function Ii(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=A(),Kh=ir();function Jh(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=Jh;function Yh(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Wc(t,e),!Vc(e,t.self.RULES.all))}I.alwaysValidSchema=Yh;function Wc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Kc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Wc;function Vc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=Vc;function Qh(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=Qh;function Xh({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=Xh;function Zh(t){return Gc(decodeURIComponent(t))}I.unescapeFragment=Zh;function ep(t){return encodeURIComponent(Ni(t))}I.escapeFragment=ep;function Ni(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=Ni;function Gc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Gc;function tp(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=tp;function Uc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:Uc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),Mi(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:zc}),items:Uc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function zc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Mi(t,n,e),n}I.evaluatedPropsToName=zc;function Mi(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Mi;var Hc={};function np(t,e){return t.scopeValue("func",{ref:e,code:Hc[e.code]||(Hc[e.code]=new Kh._Code(e.code))})}I.useFunc=np;var Oi;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Oi||(I.Type=Oi={}));function rp(t,e,n){if(t instanceof q.Name){let r=e===Oi.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+Ni(t)}I.getErrorPath=rp;function Kc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Kc});var ct=_(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});var le=A(),op={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Li.default=op});var dr=_(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var L=A(),lo=M(),pe=ct();ue.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ip(t,e=ue.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=Qc(t,e,n);r??(s||a)?Jc(i,c):Yc(o,(0,L._)`[${c}]`)}ue.reportError=ip;function sp(t,e=ue.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=Qc(t,e,n);Jc(o,a),i||s||Yc(r,pe.default.vErrors)}ue.reportExtraError=sp;function ap(t,e){t.assign(pe.default.errors,e),t.if((0,L._)`${pe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${pe.default.vErrors}.length`,e),()=>t.assign(pe.default.vErrors,null)))}ue.resetErrorsCount=ap;function cp({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,pe.default.errors,a=>{t.const(s,(0,L._)`${pe.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(pe.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}ue.extendErrors=cp;function Jc(t,e){let n=t.const("err",e);t.if((0,L._)`${pe.default.vErrors} === null`,()=>t.assign(pe.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${pe.default.vErrors}.push(${n})`),t.code((0,L._)`${pe.default.errors}++`)}function Yc(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Vt={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 Qc(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:lp(t,e,n)}function lp(t,e,n={}){let{gen:r,it:o}=t,i=[up(o,n),dp(t,n)];return fp(t,e,i),r.object(...i)}function up({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,lo.getErrorPath)(e,lo.Type.Str)}`:t;return[pe.default.instancePath,(0,L.strConcat)(pe.default.instancePath,n)]}function dp({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,lo.getErrorPath)(n,lo.Type.Str)}`),[Vt.schemaPath,o]}function fp(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([Vt.keyword,o],[Vt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Vt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vt.schema,s],[Vt.parentSchema,(0,L._)`${u}${d}`],[pe.default.data,i]),l&&r.push([Vt.propertyName,l])}});var Zc=_(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.boolOrEmptySchema=wn.topBoolOrEmptySchema=void 0;var mp=dr(),hp=A(),pp=ct(),gp={message:"boolean schema is false"};function yp(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Xc(t,!1):typeof n=="object"&&n.$async===!0?e.return(pp.default.data):(e.assign((0,hp._)`${r}.errors`,null),e.return(!0))}wn.topBoolOrEmptySchema=yp;function _p(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Xc(t)):n.var(e,!0)}wn.boolOrEmptySchema=_p;function Xc(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,mp.reportError)(o,gp,void 0,e)}});var ji=_(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.getRules=vn.isJSONType=void 0;var wp=["string","number","integer","boolean","null","object","array"],vp=new Set(wp);function bp(t){return typeof t=="string"&&vp.has(t)}vn.isJSONType=bp;function Sp(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vn.getRules=Sp});var Di=_(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function Ep({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&el(t,r)}Et.schemaHasRulesForType=Ep;function el(t,e){return e.rules.some(n=>tl(t,n))}Et.shouldUseGroup=el;function tl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Et.shouldUseRule=tl});var fr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.reportTypeError=de.checkDataTypes=de.checkDataType=de.coerceAndCheckDataType=de.getJSONTypes=de.getSchemaTypes=de.DataType=void 0;var $p=ji(),kp=Di(),Rp=dr(),T=A(),nl=M(),bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(bn||(de.DataType=bn={}));function Pp(t){let e=rl(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}de.getSchemaTypes=Pp;function rl(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every($p.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}de.getJSONTypes=rl;function Tp(t,e){let{gen:n,data:r,opts:o}=t,i=Ap(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,kp.schemaHasRulesForType)(t,e[0]));if(s){let a=Bi(e,r,o.strictNumbers,bn.Wrong);n.if(a,()=>{i.length?xp(t,e,i):qi(t)})}return s}de.coerceAndCheckDataType=Tp;var ol=new Set(["string","number","integer","boolean","null"]);function Ap(t,e){return e?t.filter(n=>ol.has(n)||e==="array"&&n==="array"):[]}function xp(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,T._)`typeof ${o}`),a=r.let("coerced",(0,T._)`undefined`);i.coerceTypes==="array"&&r.if((0,T._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,T._)`${o}[0]`).assign(s,(0,T._)`typeof ${o}`).if(Bi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,T._)`${a} !== undefined`);for(let l of n)(ol.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),qi(t),r.endIf(),r.if((0,T._)`${a} !== undefined`,()=>{r.assign(o,a),Cp(t,a)});function c(l){switch(l){case"string":r.elseIf((0,T._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,T._)`"" + ${o}`).elseIf((0,T._)`${o} === null`).assign(a,(0,T._)`""`);return;case"number":r.elseIf((0,T._)`${s} == "boolean" || ${o} === null
3
+ var _p=Object.create;var $c=Object.defineProperty;var wp=Object.getOwnPropertyDescriptor;var vp=Object.getOwnPropertyNames;var bp=Object.getPrototypeOf,Sp=Object.prototype.hasOwnProperty;var Z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ep=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vp(e))!Sp.call(t,o)&&o!==n&&$c(t,o,{get:()=>e[o],enumerable:!(r=wp(e,o))||r.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?_p(bp(t)):{},Ep(e||!t||!t.__esModule?$c(n,"default",{value:t,enumerable:!0}):n,t));var cr=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var sr=class{};D._CodeOrName=sr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ut=class extends sr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=Ut;var xe=class extends sr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ut&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Bc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)vi(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Bc;var wi=new xe("+");function qc(t,...e){let n=[ar(t[0])],r=0;for(;r<e.length;)n.push(wi),vi(n,e[r]),n.push(wi,ar(t[++r]));return jp(n),new xe(n)}D.str=qc;function vi(t,e){e instanceof xe?t.push(...e._items):e instanceof Ut?t.push(e):t.push(Bp(e))}D.addCodeArg=vi;function jp(t){let e=1;for(;e<t.length-1;){if(t[e]===wi){let n=Dp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Dp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ut||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ut))return`"${t}${e.slice(1)}`}function Fp(t,e){return e.emptyStr()?t:t.emptyStr()?e:qc`${t}${e}`}D.strConcat=Fp;function Bp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function qp(t){return new xe(ar(t))}D.stringify=qp;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=ar;function Up(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Bc`[${t}]`}D.getProperty=Up;function Hp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Hp;function Gp(t){return new xe(t.toString())}D.regexpCode=Gp});var Ei=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.ValueScope=we.ValueScopeName=we.Scope=we.varKinds=we.UsedValueState=void 0;var _e=cr(),bi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oo||(we.UsedValueState=oo={}));we.varKinds={const:new _e.Name("const"),let:new _e.Name("let"),var:new _e.Name("var")};var io=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _e.Name?e:this.name(e)}name(e){return new _e.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};we.Scope=io;var so=class extends _e.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_e._)`.${new _e.Name(n)}[${r}]`}};we.ValueScopeName=so;var Wp=(0,_e._)`\n`,Si=class extends io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Wp:_e.nil}}get(){return this._scope}name(e){return new so(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_e._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=_e.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,oo.Started);let u=n(l);if(u){let d=this.opts.es5?we.varKinds.var:we.varKinds.const;i=(0,_e._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,_e._)`${i}${u}${this.opts._n}`;else throw new bi(l);c.set(l,oo.Completed)})}return i}};we.ValueScope=Si});var A=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.or=x.and=x.not=x.CodeGen=x.operators=x.varKinds=x.ValueScopeName=x.ValueScope=x.Scope=x.Name=x.regexpCode=x.stringify=x.getProperty=x.nil=x.strConcat=x.str=x._=void 0;var N=cr(),je=Ei(),St=cr();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return St._}});Object.defineProperty(x,"str",{enumerable:!0,get:function(){return St.str}});Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return St.strConcat}});Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return St.nil}});Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return St.getProperty}});Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return St.stringify}});Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return St.regexpCode}});Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return St.Name}});var uo=Ei();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return uo.Scope}});Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return uo.ValueScope}});Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return uo.ValueScopeName}});Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return uo.varKinds}});x.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},ki=class extends ct{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?je.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},ao=class extends ct{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return lo(e,this.rhs)}},$i=class extends ao{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ri=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Pi=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ti=class extends ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ai=class extends ct{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=bn(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},lr=class extends ct{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Vp(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wt(e,n.names),{})}},lt=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ci=class extends lr{},vn=class extends lt{};vn.kind="else";var Ht=class t extends lt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Uc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=bn(this.condition,e,n),this}get names(){let e=super.names;return lo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Ht.kind="if";var Gt=class extends lt{};Gt.kind="for";var xi=class extends Gt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=bn(this.iteration,e,n),this}get names(){return Wt(super.names,this.iteration.names)}},Ii=class extends Gt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?je.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=lo(super.names,this.from);return lo(e,this.to)}},co=class extends Gt{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=bn(this.iterable,e,n),this}get names(){return Wt(super.names,this.iterable.names)}},ur=class extends lt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ur.kind="func";var dr=class extends lr{render(e){return"return "+super.render(e)}};dr.kind="return";var Oi=class extends lt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Wt(e,this.catch.names),this.finally&&Wt(e,this.finally.names),e}},fr=class extends lt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var mr=class extends lt{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Ni=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
4
+ `:""},this._extScope=e,this._scope=new je.Scope({parent:e}),this._nodes=[new Ci]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new ki(e,i,r)),i}const(e,n,r){return this._def(je.varKinds.const,e,n,r)}let(e,n,r){return this._def(je.varKinds.let,e,n,r)}var(e,n,r){return this._def(je.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ao(e,n,r))}add(e,n){return this._leafNode(new $i(e,x.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ai(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Ht(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ht(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Ht,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new xi(e),n)}forRange(e,n,r,o,i=this.opts.es5?je.varKinds.var:je.varKinds.let){let s=this._scope.toName(e);return this._for(new Ii(i,s,n,r),()=>o(s))}forOf(e,n,r,o=je.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new co("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?je.varKinds.var:je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new co("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Gt)}label(e){return this._leafNode(new Ri(e))}break(e){return this._leafNode(new Pi(e))}return(e){let n=new dr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Oi;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new fr(i),n(i)}return r&&(this._currNode=o.finally=new mr,this.code(r)),this._endBlockNode(fr,mr)}throw(e){return this._leafNode(new Ti(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new ur(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ur)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ht))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};x.CodeGen=Ni;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function lo(t,e){return e instanceof N._CodeOrName?Wt(t,e.names):t}function bn(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Vp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Uc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${Mi(t)}`}x.not=Uc;var zp=Hc(x.operators.AND);function Kp(...t){return t.reduce(zp)}x.and=Kp;var Jp=Hc(x.operators.OR);function Yp(...t){return t.reduce(Jp)}x.or=Yp;function Hc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${Mi(e)} ${t} ${Mi(n)}`}function Mi(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=A(),Qp=cr();function Xp(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=Xp;function Zp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vc(t,e),!zc(e,t.self.RULES.all))}I.alwaysValidSchema=Zp;function Vc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Yc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Vc;function zc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=zc;function eh(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=eh;function th({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=th;function nh(t){return Kc(decodeURIComponent(t))}I.unescapeFragment=nh;function rh(t){return encodeURIComponent(ji(t))}I.escapeFragment=rh;function ji(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=ji;function Kc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Kc;function oh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=oh;function Gc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),Di(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jc}),items:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Di(t,n,e),n}I.evaluatedPropsToName=Jc;function Di(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Di;var Wc={};function ih(t,e){return t.scopeValue("func",{ref:e,code:Wc[e.code]||(Wc[e.code]=new Qp._Code(e.code))})}I.useFunc=ih;var Li;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Li||(I.Type=Li={}));function sh(t,e,n){if(t instanceof q.Name){let r=e===Li.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+ji(t)}I.getErrorPath=sh;function Yc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Yc});var ut=_(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var le=A(),ah={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Fi.default=ah});var pr=_(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var L=A(),fo=M(),he=ut();ue.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ch(t,e=ue.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=Zc(t,e,n);r??(s||a)?Qc(i,c):Xc(o,(0,L._)`[${c}]`)}ue.reportError=ch;function lh(t,e=ue.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=Zc(t,e,n);Qc(o,a),i||s||Xc(r,he.default.vErrors)}ue.reportExtraError=lh;function uh(t,e){t.assign(he.default.errors,e),t.if((0,L._)`${he.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${he.default.vErrors}.length`,e),()=>t.assign(he.default.vErrors,null)))}ue.resetErrorsCount=uh;function dh({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,he.default.errors,a=>{t.const(s,(0,L._)`${he.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(he.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}ue.extendErrors=dh;function Qc(t,e){let n=t.const("err",e);t.if((0,L._)`${he.default.vErrors} === null`,()=>t.assign(he.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${he.default.vErrors}.push(${n})`),t.code((0,L._)`${he.default.errors}++`)}function Xc(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Vt={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 Zc(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:fh(t,e,n)}function fh(t,e,n={}){let{gen:r,it:o}=t,i=[mh(o,n),ph(t,n)];return hh(t,e,i),r.object(...i)}function mh({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,fo.getErrorPath)(e,fo.Type.Str)}`:t;return[he.default.instancePath,(0,L.strConcat)(he.default.instancePath,n)]}function ph({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,fo.getErrorPath)(n,fo.Type.Str)}`),[Vt.schemaPath,o]}function hh(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([Vt.keyword,o],[Vt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Vt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vt.schema,s],[Vt.parentSchema,(0,L._)`${u}${d}`],[he.default.data,i]),l&&r.push([Vt.propertyName,l])}});var tl=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var gh=pr(),yh=A(),_h=ut(),wh={message:"boolean schema is false"};function vh(t){let{gen:e,schema:n,validateName:r}=t;n===!1?el(t,!1):typeof n=="object"&&n.$async===!0?e.return(_h.default.data):(e.assign((0,yh._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=vh;function bh(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),el(t)):n.var(e,!0)}Sn.boolOrEmptySchema=bh;function el(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gh.reportError)(o,wh,void 0,e)}});var Bi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Sh=["string","number","integer","boolean","null","object","array"],Eh=new Set(Sh);function kh(t){return typeof t=="string"&&Eh.has(t)}En.isJSONType=kh;function $h(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}En.getRules=$h});var qi=_(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function Rh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&nl(t,r)}Et.schemaHasRulesForType=Rh;function nl(t,e){return e.rules.some(n=>rl(t,n))}Et.shouldUseGroup=nl;function rl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Et.shouldUseRule=rl});var hr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.reportTypeError=de.checkDataTypes=de.checkDataType=de.coerceAndCheckDataType=de.getJSONTypes=de.getSchemaTypes=de.DataType=void 0;var Ph=Bi(),Th=qi(),Ah=pr(),T=A(),ol=M(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(de.DataType=kn={}));function Ch(t){let e=il(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}de.getSchemaTypes=Ch;function il(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ph.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}de.getJSONTypes=il;function xh(t,e){let{gen:n,data:r,opts:o}=t,i=Ih(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Th.schemaHasRulesForType)(t,e[0]));if(s){let a=Hi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Oh(t,e,i):Gi(t)})}return s}de.coerceAndCheckDataType=xh;var sl=new Set(["string","number","integer","boolean","null"]);function Ih(t,e){return e?t.filter(n=>sl.has(n)||e==="array"&&n==="array"):[]}function Oh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,T._)`typeof ${o}`),a=r.let("coerced",(0,T._)`undefined`);i.coerceTypes==="array"&&r.if((0,T._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,T._)`${o}[0]`).assign(s,(0,T._)`typeof ${o}`).if(Hi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,T._)`${a} !== undefined`);for(let l of n)(sl.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Gi(t),r.endIf(),r.if((0,T._)`${a} !== undefined`,()=>{r.assign(o,a),Nh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,T._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,T._)`"" + ${o}`).elseIf((0,T._)`${o} === null`).assign(a,(0,T._)`""`);return;case"number":r.elseIf((0,T._)`${s} == "boolean" || ${o} === null
5
5
  || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,T._)`+${o}`);return;case"integer":r.elseIf((0,T._)`${s} === "boolean" || ${o} === null
6
6
  || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,T._)`+${o}`);return;case"boolean":r.elseIf((0,T._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,T._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,T._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,T._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,T._)`[${o}]`)}}}function Cp({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${n}]`,r))}function Fi(t,e,n,r=bn.Correct){let o=r===bn.Correct?T.operators.EQ:T.operators.NEQ,i;switch(t){case"null":return(0,T._)`${e} ${o} null`;case"array":i=(0,T._)`Array.isArray(${e})`;break;case"object":i=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,T._)`typeof ${e} ${o} ${t}`}return r===bn.Correct?i:(0,T.not)(i);function s(a=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,a,n?(0,T._)`isFinite(${e})`:T.nil)}}de.checkDataType=Fi;function Bi(t,e,n,r){if(t.length===1)return Fi(t[0],e,n,r);let o,i=(0,nl.toHash)(t);if(i.array&&i.object){let s=(0,T._)`typeof ${e} != "object"`;o=i.null?s:(0,T._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=T.nil;i.number&&delete i.integer;for(let s in i)o=(0,T.and)(o,Fi(s,e,n,r));return o}de.checkDataTypes=Bi;var Ip={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function qi(t){let e=Op(t);(0,Rp.reportError)(e,Ip)}de.reportTypeError=qi;function Op(t){let{gen:e,data:n,schema:r}=t,o=(0,nl.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var sl=_(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.assignDefaults=void 0;var Sn=A(),Np=M();function Mp(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)il(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>il(t,i,o.default))}uo.assignDefaults=Mp;function il(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,Sn._)`${i}${(0,Sn.getProperty)(e)}`;if(o){(0,Np.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Sn._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,Sn._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Sn._)`${a} = ${(0,Sn.stringify)(n)}`)}});var Ce=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var H=A(),Ui=M(),$t=ct(),Lp=M();function jp(t,e){let{gen:n,data:r,it:o}=t;n.if(Wi(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,H._)`${e}`},!0),t.error()})}F.checkReportMissingProp=jp;function Dp({gen:t,data:e,it:{opts:n}},r,o){return(0,H.or)(...r.map(i=>(0,H.and)(Wi(t,e,i,n.ownProperties),(0,H._)`${o} = ${i}`)))}F.checkMissingProp=Dp;function Fp(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Fp;function al(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,H._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=al;function Hi(t,e,n){return(0,H._)`${al(t)}.call(${e}, ${n})`}F.isOwnProperty=Hi;function Bp(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} !== undefined`;return r?(0,H._)`${o} && ${Hi(t,e,n)}`:o}F.propertyInData=Bp;function Wi(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} === undefined`;return r?(0,H.or)(o,(0,H.not)(Hi(t,e,n))):o}F.noPropertyInData=Wi;function cl(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=cl;function qp(t,e){return cl(e).filter(n=>!(0,Ui.alwaysValidSchema)(t,e[n]))}F.schemaProperties=qp;function Up({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,H._)`${t}, ${e}, ${r}${o}`:e,d=[[$t.default.instancePath,(0,H.strConcat)($t.default.instancePath,i)],[$t.default.parentData,s.parentData],[$t.default.parentDataProperty,s.parentDataProperty],[$t.default.rootData,$t.default.rootData]];s.opts.dynamicRef&&d.push([$t.default.dynamicAnchors,$t.default.dynamicAnchors]);let p=(0,H._)`${u}, ${n.object(...d)}`;return c!==H.nil?(0,H._)`${a}.call(${c}, ${p})`:(0,H._)`${a}(${p})`}F.callValidateCode=Up;var Hp=(0,H._)`new RegExp`;function Wp({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,H._)`${o.code==="new RegExp"?Hp:(0,Lp.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=Wp;function Vp(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,H._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:Ui.Type.Num},i),e.if((0,H.not)(i),a)})}}F.validateArray=Vp;function Gp(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ui.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,H._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,H.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Gp});var dl=_(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.validateKeywordUsage=Ke.validSchemaType=Ke.funcKeywordCode=Ke.macroKeywordCode=void 0;var ge=A(),Gt=ct(),zp=Ce(),Kp=dr();function Jp(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=ul(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ke.macroKeywordCode=Jp;function Yp(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;Xp(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=ul(r,o,l),d=r.let("valid");t.block$data(d,p),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function p(){if(e.errors===!1)m(),e.modifying&&ll(t),g(()=>t.error());else{let y=e.async?h():f();e.modifying&&ll(t),g(()=>Qp(t,y))}}function h(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(d,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ge._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ge._)`${u}.errors`;return r.assign(y,null),m(ge.nil),y}function m(y=e.async?(0,ge._)`await `:ge.nil){let v=c.opts.passContext?Gt.default.this:Gt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ge._)`${y}${(0,zp.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ge.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Ke.funcKeywordCode=Yp;function ll(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function Qp(t,e){let{gen:n}=t;n.if((0,ge._)`Array.isArray(${e})`,()=>{n.assign(Gt.default.vErrors,(0,ge._)`${Gt.default.vErrors} === null ? ${e} : ${Gt.default.vErrors}.concat(${e})`).assign(Gt.default.errors,(0,ge._)`${Gt.default.vErrors}.length`),(0,Kp.extendErrors)(t)},()=>t.error())}function Xp({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ul(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function Zp(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ke.validSchemaType=Zp;function eg({schema:t,opts:e,self:n,errSchemaPath:r},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ke.validateKeywordUsage=eg});var ml=_(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.extendSubschemaMode=kt.extendSubschemaData=kt.getSubschema=void 0;var Je=A(),fl=M();function tg(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Je._)`${t.schemaPath}${(0,Je.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Je._)`${t.schemaPath}${(0,Je.getProperty)(e)}${(0,Je.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,fl.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}kt.getSubschema=tg;function ng(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,p=a.let("data",(0,Je._)`${e.data}${(0,Je.getProperty)(n)}`,!0);c(p),t.errorPath=(0,Je.str)`${l}${(0,fl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Je._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Je.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}kt.extendSubschemaData=ng;function rg(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}kt.extendSubschemaMode=rg});var Vi=_((xk,hl)=>{"use strict";hl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var gl=_((Ck,pl)=>{"use strict";var Rt=pl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};fo(e,r,o,t,"",t)};Rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function fo(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Rt.arrayKeywords)for(var p=0;p<d.length;p++)fo(t,e,n,d[p],o+"/"+u+"/"+p,i,o,u,r,p)}else if(u in Rt.propsKeywords){if(d&&typeof d=="object")for(var h in d)fo(t,e,n,d[h],o+"/"+u+"/"+og(h),i,o,u,r,h)}else(u in Rt.keywords||t.allKeys&&!(u in Rt.skipKeywords))&&fo(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function og(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var mr=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var ig=M(),sg=Vi(),ag=gl(),cg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function lg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Gi(t):e?yl(t)<=e:!1}ve.inlineRef=lg;var ug=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Gi(t){for(let e in t){if(ug.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Gi)||typeof n=="object"&&Gi(n))return!0}return!1}function yl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!cg.has(n)&&(typeof t[n]=="object"&&(0,ig.eachItem)(t[n],r=>e+=yl(r)),e===1/0))return 1/0}return e}function _l(t,e="",n){n!==!1&&(e=En(e));let r=t.parse(e);return wl(t,r)}ve.getFullPath=_l;function wl(t,e){return t.serialize(e).split("#")[0]+"#"}ve._getFullPath=wl;var dg=/#\/?$/;function En(t){return t?t.replace(dg,""):""}ve.normalizeId=En;function fg(t,e,n){return n=En(n),t.resolve(e,n)}ve.resolveUrl=fg;var mg=/^[a-z_][-a-z0-9._]*$/i;function hg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=En(t[n]||e),i={"":o},s=_l(r,o,!1),a={},c=new Set;return ag(t,{allKeys:!0},(d,p,h,f)=>{if(f===void 0)return;let m=s+p,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[p]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=En(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let k=this.refs[S];return typeof k=="string"&&(k=this.refs[k]),typeof k=="object"?l(d,k.schema,S):S!==En(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!mg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,p,h){if(p!==void 0&&!sg(d,p))throw u(h)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ve.getSchemaRefs=hg});var gr=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getData=Pt.KeywordCxt=Pt.validateFunctionCode=void 0;var $l=Zc(),vl=fr(),Ki=Di(),mo=fr(),pg=sl(),pr=dl(),zi=ml(),b=A(),P=ct(),gg=mr(),lt=M(),hr=dr();function yg(t){if(Pl(t)&&(Tl(t),Rl(t))){vg(t);return}kl(t,()=>(0,$l.topBoolOrEmptySchema)(t))}Pt.validateFunctionCode=yg;function kl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${bl(n,o)}`),wg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${_g(o)}`,r.$async,()=>t.code(bl(n,o)).code(i))}function _g(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function wg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function vg(t){let{schema:e,opts:n,gen:r}=t;kl(t,()=>{n.$comment&&e.$comment&&xl(t),kg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&bg(t),Al(t),Tg(t)})}function bg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function bl(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function Sg(t,e){if(Pl(t)&&(Tl(t),Rl(t))){Eg(t,e);return}(0,$l.boolOrEmptySchema)(t,e)}function Rl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Pl(t){return typeof t.schema!="boolean"}function Eg(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&xl(t),Rg(t),Pg(t);let i=r.const("_errs",P.default.errors);Al(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Tl(t){(0,lt.checkUnknownRules)(t),$g(t)}function Al(t,e){if(t.opts.jtd)return Sl(t,[],!1,e);let n=(0,vl.getSchemaTypes)(t.schema),r=(0,vl.coerceAndCheckDataType)(t,n);Sl(t,n,!r,e)}function $g(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,lt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function kg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,lt.checkStrictMode)(t,"default is ignored in the schema root")}function Rg(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,gg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Pg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function xl({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Tg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Ag(t),e.return((0,b._)`${P.default.errors} === 0`))}function Ag({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function Sl(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,lt.schemaHasRulesButRef)(i,u))){o.block(()=>Il(t,"$ref",u.all.$ref.definition));return}c.jtd||xg(t,e),o.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,Ki.shouldUseGroup)(i,p)&&(p.type?(o.if((0,mo.checkDataType)(p.type,s,c.strictNumbers)),El(t,p),e.length===1&&e[0]===p.type&&n&&(o.else(),(0,mo.reportTypeError)(t)),o.endIf()):El(t,p),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function El(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,pg.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Ki.shouldUseRule)(r,i)&&Il(t,i.keyword,i.definition,e.type)})}function xg(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Cg(t,e),t.opts.allowUnionTypes||Ig(t,e),Og(t,t.dataTypes))}function Cg(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Cl(t.dataTypes,n)||Ji(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Mg(t,e)}}function Ig(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ji(t,"use allowUnionTypes to allow union type keyword")}function Og(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Ki.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Ng(e,s))&&Ji(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function Ng(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Cl(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Mg(t,e){let n=[];for(let r of t.dataTypes)Cl(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Ji(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,lt.checkStrictMode)(t,e,t.opts.strictTypes)}var ho=class{constructor(e,n,r){if((0,pr.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,lt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Ol(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,pr.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?hr.reportExtraError:hr.reportError)(this,this.def.error,n)}$dataError(){(0,hr.reportError)(this,this.def.$dataError||hr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,hr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,mo.checkDataTypes)(c,n,i.opts.strictNumbers,mo.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,zi.getSubschema)(this.it,e);(0,zi.extendSubschemaData)(r,this.it,e),(0,zi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return Sg(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=lt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=lt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Pt.KeywordCxt=ho;function Il(t,e,n,r){let o=new ho(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,pr.funcKeywordCode)(o,n):"macro"in n?(0,pr.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,pr.funcKeywordCode)(o,n)}var Lg=/^\/(?:[^~]|~0|~1)*$/,jg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ol(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Lg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=jg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,lt.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Pt.getData=Ol});var po=_(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var Yi=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Qi.default=Yi});var yr=_(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Xi=mr(),Zi=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Xi.resolveUrl)(e,n,r),this.missingSchema=(0,Xi.normalizeId)((0,Xi.getFullPath)(e,this.missingRef))}};es.default=Zi});var yo=_(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.resolveSchema=Ie.getCompilingSchema=Ie.resolveRef=Ie.compileSchema=Ie.SchemaEnv=void 0;var je=A(),Dg=po(),zt=ct(),De=mr(),Nl=M(),Fg=gr(),$n=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,De.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Ie.SchemaEnv=$n;function ns(t){let e=Ml.call(this,t);if(e)return e;let n=(0,De.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new je.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Dg.default,code:(0,je._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:zt.default.data,parentData:zt.default.parentData,parentDataProperty:zt.default.parentDataProperty,dataNames:[zt.default.data],dataPathArr:[je.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,je.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:je.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,je._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Fg.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(zt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let h=new Function(`${zt.default.self}`,`${zt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;h.evaluated={props:f instanceof je.Name?void 0:f,items:m instanceof je.Name?void 0:m,dynamicProps:f instanceof je.Name,dynamicItems:m instanceof je.Name},h.source&&(h.source.evaluated=(0,je.stringify)(h.evaluated))}return t.validate=h,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Ie.compileSchema=ns;function Bg(t,e,n){var r;n=(0,De.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Hg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new $n({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=qg.call(this,i)}Ie.resolveRef=Bg;function qg(t){return(0,De.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ns.call(this,t)}function Ml(t){for(let e of this._compilations)if(Ug(e,t))return e}Ie.getCompilingSchema=Ml;function Ug(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Hg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||go.call(this,t,e)}function go(t,e){let n=this.opts.uriResolver.parse(e),r=(0,De._getFullPath)(this.opts.uriResolver,n),o=(0,De.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return ts.call(this,n,t);let i=(0,De.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=go.call(this,t,s);return typeof a?.schema!="object"?void 0:ts.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||ns.call(this,s),i===(0,De.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,De.resolveUrl)(this.opts.uriResolver,o,l)),new $n({schema:a,schemaId:c,root:t,baseId:o})}return ts.call(this,n,s)}}Ie.resolveSchema=go;var Wg=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ts(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Nl.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!Wg.has(a)&&l&&(e=(0,De.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Nl.schemaHasRulesButRef)(n,this.RULES)){let a=(0,De.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=go.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new $n({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Ll=_((jk,Vg)=>{Vg.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 os=_((Dk,Bl)=>{"use strict";var Gg=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function rs(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var zg=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jl(t){return t.length=0,!0}function Kg(t,e,n){if(t.length){let r=rs(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Jg(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=Kg;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=jl}else{o.push(l);continue}}return o.length&&(a===jl?n.zone=o.join(""):s?r.push(o.join("")):r.push(rs(o))),n.address=r.join(""),n}function Fl(t){if(Yg(t,":")<2)return{host:t,isIPV6:!1};let e=Jg(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Yg(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function Qg(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function Xg(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function Zg(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Dl(n)){let r=Fl(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Bl.exports={nonSimpleDomain:zg,recomposeAuthority:Zg,normalizeComponentEncoding:Xg,removeDotSegments:Qg,isIPv4:Dl,isUUID:Gg,normalizeIPv6:Fl,stringArrayToHexStripped:rs}});var Vl=_((Fk,Wl)=>{"use strict";var{isUUID:ey}=os(),ty=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ny=["http","https","ws","wss","urn","urn:uuid"];function ry(t){return ny.indexOf(t)!==-1}function is(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function ql(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ul(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function oy(t){return t.secure=is(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function iy(t){if((t.port===(is(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function sy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(ty);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=ss(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ay(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=ss(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function cy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ey(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function ly(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Hl={scheme:"http",domainHost:!0,parse:ql,serialize:Ul},uy={scheme:"https",domainHost:Hl.domainHost,parse:ql,serialize:Ul},_o={scheme:"ws",domainHost:!0,parse:oy,serialize:iy},dy={scheme:"wss",domainHost:_o.domainHost,parse:_o.parse,serialize:_o.serialize},fy={scheme:"urn",parse:sy,serialize:ay,skipNormalize:!0},my={scheme:"urn:uuid",parse:cy,serialize:ly,skipNormalize:!0},wo={http:Hl,https:uy,ws:_o,wss:dy,urn:fy,"urn:uuid":my};Object.setPrototypeOf(wo,null);function ss(t){return t&&(wo[t]||wo[t.toLowerCase()])||void 0}Wl.exports={wsIsSecure:is,SCHEMES:wo,isValidSchemeName:ry,getSchemeHandler:ss}});var Kl=_((Bk,bo)=>{"use strict";var{normalizeIPv6:hy,removeDotSegments:_r,recomposeAuthority:py,normalizeComponentEncoding:vo,isIPv4:gy,nonSimpleDomain:yy}=os(),{SCHEMES:_y,getSchemeHandler:Gl}=Vl();function wy(t,e){return typeof t=="string"?t=Ye(ut(t,e),e):typeof t=="object"&&(t=ut(Ye(t,e),e)),t}function vy(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=zl(ut(t,r),ut(e,r),r,!0);return r.skipEscape=!0,Ye(o,r)}function zl(t,e,n,r){let o={};return r||(t=ut(Ye(t,n),n),e=ut(Ye(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=_r(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=_r(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=_r(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=_r(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function by(t,e,n){return typeof t=="string"?(t=unescape(t),t=Ye(vo(ut(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Ye(vo(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ye(vo(ut(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Ye(vo(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ye(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=Gl(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=py(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=_r(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var Sy=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ut(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(Sy);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(gy(r.host)===!1){let c=hy(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=Gl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&yy(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var as={SCHEMES:_y,normalize:wy,resolve:vy,resolveComponent:zl,equal:by,serialize:Ye,parse:ut};bo.exports=as;bo.exports.default=as;bo.exports.fastUri=as});var Yl=_(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var Jl=Kl();Jl.code='require("ajv/dist/runtime/uri").default';cs.default=Jl});var ou=_(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var Ey=gr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return Ey.KeywordCxt}});var kn=A();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return kn._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return kn.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return kn.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return kn.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return kn.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return kn.CodeGen}});var $y=po(),tu=yr(),ky=ji(),wr=yo(),Ry=A(),vr=mr(),So=fr(),us=M(),Ql=Ll(),Py=Yl(),nu=(t,e)=>new RegExp(t,e);nu.code="new RegExp";var Ty=["removeAdditional","useDefaults","coerceTypes"],Ay=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),xy={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."},Cy={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Xl=200;function Iy(t){var e,n,r,o,i,s,a,c,l,u,d,p,h,f,m,g,y,v,S,R,k,G,Q,oe,Ge;let rt=t.strict,Zn=(e=t.code)===null||e===void 0?void 0:e.optimize,ze=Zn===!0||Zn===void 0?1:Zn||0,te=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:nu,Ft=(o=t.uriResolver)!==null&&o!==void 0?o:Py.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:rt)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:rt)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:rt)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:rt)!==null&&p!==void 0?p:"log",strictRequired:(f=(h=t.strictRequired)!==null&&h!==void 0?h:rt)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:ze,regExp:te}:{optimize:ze,regExp:te},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Xl,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Xl,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(k=t.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(G=t.validateSchema)!==null&&G!==void 0?G:!0,validateFormats:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(oe=t.unicodeRegExp)!==null&&oe!==void 0?oe:!0,int32range:(Ge=t.int32range)!==null&&Ge!==void 0?Ge:!0,uriResolver:Ft}}var br=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Iy(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Ry.ValueScope({scope:{},prefixes:Ay,es5:n,lines:r}),this.logger=Dy(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,ky.getRules)(),Zl.call(this,xy,e,"NOT SUPPORTED"),Zl.call(this,Cy,e,"DEPRECATED","warn"),this._metaOpts=Ly.call(this),e.formats&&Ny.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&My.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Oy.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Ql;r==="id"&&(o={...Ql},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof tu.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,vr.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=eu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new wr.SchemaEnv({schema:{},schemaId:r});if(n=wr.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=eu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,vr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(By.call(this,r,n),!n)return(0,us.eachItem)(r,i=>ls.call(this,i)),this;Uy.call(this,n);let o={...n,type:(0,So.getJSONTypes)(n.type),schemaType:(0,So.getJSONTypes)(n.schemaType)};return(0,us.eachItem)(r,o.type.length===0?i=>ls.call(this,i,o):i=>o.type.forEach(s=>ls.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=ru(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,vr.normalizeId)(s||r);let l=vr.getSchemaRefs.call(this,e,r);return c=new wr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):wr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{wr.compileSchema.call(this,e)}finally{this.opts=n}}};br.ValidationError=$y.default;br.MissingRefError=tu.default;ie.default=br;function Zl(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function eu(t){return t=(0,vr.normalizeId)(t),this.schemas[t]||this.refs[t]}function Oy(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Ny(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function My(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Ly(){let t={...this.opts};for(let e of Ty)delete t[e];return t}var jy={log(){},warn(){},error(){}};function Dy(t){if(t===!1)return jy;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Fy=/^[a-z_$][a-z0-9_$:-]*$/i;function By(t,e){let{RULES:n}=this;if((0,us.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Fy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ls(t,e,n){var r;let o=e?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,So.getJSONTypes)(e.type),schemaType:(0,So.getJSONTypes)(e.schemaType)}};e.before?qy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function qy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Uy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=ru(e)),t.validateSchema=this.compile(e,!0))}var Hy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ru(t){return{anyOf:[t,Hy]}}});var iu=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var Wy={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ds.default=Wy});var lu=_(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.callRef=Kt.getValidate=void 0;var Vy=yr(),su=Ce(),be=A(),Rn=ct(),au=yo(),Eo=M(),Gy={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=au.resolveRef.call(c,l,o,n);if(u===void 0)throw new Vy.default(r.opts.uriResolver,o,n);if(u instanceof au.SchemaEnv)return p(u);return h(u);function d(){if(i===l)return $o(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return $o(t,(0,be._)`${f}.validate`,l,l.$async)}function p(f){let m=cu(t,f);$o(t,m,f,f.$async)}function h(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,be.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function cu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Kt.getValidate=cu;function $o(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Rn.default.this:be.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,su.callValidateCode)(t,e,l)}`),h(e),s||o.assign(f,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),p(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,su.callValidateCode)(t,e,l),()=>h(e),()=>p(e))}function p(f){let m=(0,be._)`${f}.errors`;o.assign(Rn.default.vErrors,(0,be._)`${Rn.default.vErrors} === null ? ${m} : ${Rn.default.vErrors}.concat(${m})`),o.assign(Rn.default.errors,(0,be._)`${Rn.default.vErrors}.length`)}function h(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=Eo.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,be._)`${f}.evaluated.props`);i.props=Eo.mergeEvaluated.props(o,y,i.props,be.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Eo.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,be._)`${f}.evaluated.items`);i.items=Eo.mergeEvaluated.items(o,y,i.items,be.Name)}}}Kt.callRef=$o;Kt.default=Gy});var uu=_(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var zy=iu(),Ky=lu(),Jy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zy.default,Ky.default];fs.default=Jy});var du=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var ko=A(),Tt=ko.operators,Ro={maximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},minimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},exclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},exclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},Yy={message:({keyword:t,schemaCode:e})=>(0,ko.str)`must be ${Ro[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ko._)`{comparison: ${Ro[t].okStr}, limit: ${e}}`},Qy={keyword:Object.keys(Ro),type:"number",schemaType:"number",$data:!0,error:Yy,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,ko._)`${n} ${Ro[e].fail} ${r} || isNaN(${n})`)}};ms.default=Qy});var fu=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Sr=A(),Xy={message:({schemaCode:t})=>(0,Sr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Sr._)`{multipleOf: ${t}}`},Zy={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Xy,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Sr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Sr._)`${s} !== parseInt(${s})`;t.fail$data((0,Sr._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};hs.default=Zy});var hu=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});function mu(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}ps.default=mu;mu.code='require("ajv/dist/runtime/ucs2length").default'});var pu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var Jt=A(),e_=M(),t_=hu(),n_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Jt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Jt._)`{limit: ${t}}`},r_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Jt.operators.GT:Jt.operators.LT,s=o.opts.unicode===!1?(0,Jt._)`${n}.length`:(0,Jt._)`${(0,e_.useFunc)(t.gen,t_.default)}(${n})`;t.fail$data((0,Jt._)`${s} ${i} ${r}`)}};gs.default=r_});var gu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var o_=Ce(),i_=M(),Pn=A(),s_={message:({schemaCode:t})=>(0,Pn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Pn._)`{pattern: ${t}}`},a_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:s_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,Pn._)`new RegExp`:(0,i_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Pn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Pn._)`!${u}`)}else{let c=(0,o_.usePattern)(t,o);t.fail$data((0,Pn._)`!${c}.test(${n})`)}}};ys.default=a_});var yu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var Er=A(),c_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Er.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Er._)`{limit: ${t}}`},l_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:c_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Er.operators.GT:Er.operators.LT;t.fail$data((0,Er._)`Object.keys(${n}).length ${o} ${r}`)}};_s.default=l_});var _u=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var $r=Ce(),kr=A(),u_=M(),d_={message:({params:{missingProperty:t}})=>(0,kr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,kr._)`{missingProperty: ${t}}`},f_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:d_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(h?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,u_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(kr.nil,d);else for(let h of n)(0,$r.checkReportMissingProp)(t,h)}function u(){let h=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>p(h,f)),t.ok(f)}else e.if((0,$r.checkMissingProp)(t,n,h)),(0,$r.reportMissingProp)(t,h),e.else()}function d(){e.forOf("prop",r,h=>{t.setParams({missingProperty:h}),e.if((0,$r.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function p(h,f){t.setParams({missingProperty:h}),e.forOf(h,r,()=>{e.assign(f,(0,$r.propertyInData)(e,o,h,a.ownProperties)),e.if((0,kr.not)(f),()=>{t.error(),e.break()})},kr.nil)}}};ws.default=f_});var wu=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var Rr=A(),m_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Rr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Rr._)`{limit: ${t}}`},h_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:m_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Rr.operators.GT:Rr.operators.LT;t.fail$data((0,Rr._)`${n}.length ${o} ${r}`)}};vs.default=h_});var Po=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var vu=Vi();vu.code='require("ajv/dist/runtime/equal").default';bs.default=vu});var bu=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ss=fr(),se=A(),p_=M(),g_=Po(),y_={message:({params:{i:t,j:e}})=>(0,se.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,se._)`{i: ${t}, j: ${e}}`},__={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:y_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,Ss.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,se._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,se._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,se._)`${f} > 1`,()=>(d()?p:h)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function p(f,m){let g=e.name("item"),y=(0,Ss.checkDataTypes)(l,g,a.opts.strictNumbers,Ss.DataType.Wrong),v=e.const("indices",(0,se._)`{}`);e.for((0,se._)`;${f}--;`,()=>{e.let(g,(0,se._)`${n}[${f}]`),e.if(y,(0,se._)`continue`),l.length>1&&e.if((0,se._)`typeof ${g} == "string"`,(0,se._)`${g} += "_"`),e.if((0,se._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,se._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,se._)`${v}[${g}] = ${f}`)})}function h(f,m){let g=(0,p_.useFunc)(e,g_.default),y=e.name("outer");e.label(y).for((0,se._)`;${f}--;`,()=>e.for((0,se._)`${m} = ${f}; ${m}--;`,()=>e.if((0,se._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Es.default=__});var Su=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var $s=A(),w_=M(),v_=Po(),b_={message:"must be equal to constant",params:({schemaCode:t})=>(0,$s._)`{allowedValue: ${t}}`},S_={keyword:"const",$data:!0,error:b_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,$s._)`!${(0,w_.useFunc)(e,v_.default)}(${n}, ${o})`):t.fail((0,$s._)`${i} !== ${n}`)}};ks.default=S_});var Eu=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Pr=A(),E_=M(),$_=Po(),k_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Pr._)`{allowedValues: ${t}}`},R_={keyword:"enum",schemaType:"array",$data:!0,error:k_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,E_.useFunc)(e,$_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",i);u=(0,Pr.or)(...o.map((f,m)=>p(h,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,h=>e.if((0,Pr._)`${l()}(${n}, ${h})`,()=>e.assign(u,!0).break()))}function p(h,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Pr._)`${l()}(${n}, ${h}[${f}])`:(0,Pr._)`${n} === ${m}`}}};Rs.default=R_});var $u=_(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var P_=du(),T_=fu(),A_=pu(),x_=gu(),C_=yu(),I_=_u(),O_=wu(),N_=bu(),M_=Su(),L_=Eu(),j_=[P_.default,T_.default,A_.default,x_.default,C_.default,I_.default,O_.default,N_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},M_.default,L_.default];Ps.default=j_});var As=_(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.validateAdditionalItems=void 0;var Yt=A(),Ts=M(),D_={message:({params:{len:t}})=>(0,Yt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Yt._)`{limit: ${t}}`},F_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:D_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Ts.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}ku(t,r)}};function ku(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Yt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Yt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Ts.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Yt._)`${a} <= ${e.length}`);n.if((0,Yt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:Ts.Type.Num},l),s.allErrors||n.if((0,Yt.not)(l),()=>n.break())})}}Tr.validateAdditionalItems=ku;Tr.default=F_});var xs=_(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.validateTuple=void 0;var Ru=A(),To=M(),B_=Ce(),q_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Pu(t,"additionalItems",e);n.items=!0,!(0,To.alwaysValidSchema)(n,e)&&t.ok((0,B_.validateArray)(t))}};function Pu(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=To.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Ru._)`${i}.length`);n.forEach((d,p)=>{(0,To.alwaysValidSchema)(a,d)||(r.if((0,Ru._)`${l} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},c)),t.ok(c))});function u(d){let{opts:p,errSchemaPath:h}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(p.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,To.checkStrictMode)(a,g,p.strictTuples)}}}Ar.validateTuple=Pu;Ar.default=q_});var Tu=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var U_=xs(),H_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,U_.validateTuple)(t,"items")};Cs.default=H_});var xu=_(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var Au=A(),W_=M(),V_=Ce(),G_=As(),z_={message:({params:{len:t}})=>(0,Au.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Au._)`{limit: ${t}}`},K_={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:z_,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,W_.alwaysValidSchema)(r,e)&&(o?(0,G_.validateAdditionalItems)(t,o):t.ok((0,V_.validateArray)(t)))}};Is.default=K_});var Cu=_(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var Oe=A(),Ao=M(),J_={message:({params:{min:t,max:e}})=>e===void 0?(0,Oe.str)`must contain at least ${t} valid item(s)`:(0,Oe.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Oe._)`{minContains: ${t}}`:(0,Oe._)`{minContains: ${t}, maxContains: ${e}}`},Y_={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:J_,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Oe._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Ao.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Ao.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ao.alwaysValidSchema)(i,n)){let m=(0,Oe._)`${u} >= ${s}`;a!==void 0&&(m=(0,Oe._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?h(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Oe._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let m=e.name("_valid"),g=e.let("count",0);h(m,()=>e.if(m,()=>f(g)))}function h(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Ao.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Oe._)`${m}++`),a===void 0?e.if((0,Oe._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Oe._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Oe._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Os.default=Y_});var Nu=_(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.validateSchemaDeps=Qe.validatePropertyDeps=Qe.error=void 0;var Ns=A(),Q_=M(),xr=Ce();Qe.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Ns.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Ns._)`{property: ${t},
7
+ || ${s} === "boolean" || ${o} === null`).assign(a,(0,T._)`[${o}]`)}}}function Nh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${n}]`,r))}function Ui(t,e,n,r=kn.Correct){let o=r===kn.Correct?T.operators.EQ:T.operators.NEQ,i;switch(t){case"null":return(0,T._)`${e} ${o} null`;case"array":i=(0,T._)`Array.isArray(${e})`;break;case"object":i=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,T._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,T.not)(i);function s(a=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,a,n?(0,T._)`isFinite(${e})`:T.nil)}}de.checkDataType=Ui;function Hi(t,e,n,r){if(t.length===1)return Ui(t[0],e,n,r);let o,i=(0,ol.toHash)(t);if(i.array&&i.object){let s=(0,T._)`typeof ${e} != "object"`;o=i.null?s:(0,T._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=T.nil;i.number&&delete i.integer;for(let s in i)o=(0,T.and)(o,Ui(s,e,n,r));return o}de.checkDataTypes=Hi;var Mh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function Gi(t){let e=Lh(t);(0,Ah.reportError)(e,Mh)}de.reportTypeError=Gi;function Lh(t){let{gen:e,data:n,schema:r}=t,o=(0,ol.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var cl=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.assignDefaults=void 0;var $n=A(),jh=M();function Dh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)al(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>al(t,i,o.default))}mo.assignDefaults=Dh;function al(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(o){(0,jh.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(n)}`)}});var Ie=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var H=A(),Wi=M(),kt=ut(),Fh=M();function Bh(t,e){let{gen:n,data:r,it:o}=t;n.if(zi(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,H._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Bh;function qh({gen:t,data:e,it:{opts:n}},r,o){return(0,H.or)(...r.map(i=>(0,H.and)(zi(t,e,i,n.ownProperties),(0,H._)`${o} = ${i}`)))}F.checkMissingProp=qh;function Uh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Uh;function ll(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,H._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=ll;function Vi(t,e,n){return(0,H._)`${ll(t)}.call(${e}, ${n})`}F.isOwnProperty=Vi;function Hh(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} !== undefined`;return r?(0,H._)`${o} && ${Vi(t,e,n)}`:o}F.propertyInData=Hh;function zi(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} === undefined`;return r?(0,H.or)(o,(0,H.not)(Vi(t,e,n))):o}F.noPropertyInData=zi;function ul(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ul;function Gh(t,e){return ul(e).filter(n=>!(0,Wi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Gh;function Wh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,H._)`${t}, ${e}, ${r}${o}`:e,d=[[kt.default.instancePath,(0,H.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let h=(0,H._)`${u}, ${n.object(...d)}`;return c!==H.nil?(0,H._)`${a}.call(${c}, ${h})`:(0,H._)`${a}(${h})`}F.callValidateCode=Wh;var Vh=(0,H._)`new RegExp`;function zh({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,H._)`${o.code==="new RegExp"?Vh:(0,Fh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=zh;function Kh(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,H._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:Wi.Type.Num},i),e.if((0,H.not)(i),a)})}}F.validateArray=Kh;function Jh(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Wi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,H._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,H.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Jh});var ml=_(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var ge=A(),zt=ut(),Yh=Ie(),Qh=pr();function Xh(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=fl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Je.macroKeywordCode=Xh;function Zh(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;tg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=fl(r,o,l),d=r.let("valid");t.block$data(d,h),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function h(){if(e.errors===!1)m(),e.modifying&&dl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&dl(t),g(()=>eg(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(d,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ge._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ge._)`${u}.errors`;return r.assign(y,null),m(ge.nil),y}function m(y=e.async?(0,ge._)`await `:ge.nil){let v=c.opts.passContext?zt.default.this:zt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ge._)`${y}${(0,Yh.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ge.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Je.funcKeywordCode=Zh;function dl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function eg(t,e){let{gen:n}=t;n.if((0,ge._)`Array.isArray(${e})`,()=>{n.assign(zt.default.vErrors,(0,ge._)`${zt.default.vErrors} === null ? ${e} : ${zt.default.vErrors}.concat(${e})`).assign(zt.default.errors,(0,ge._)`${zt.default.vErrors}.length`),(0,Qh.extendErrors)(t)},()=>t.error())}function tg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fl(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function ng(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Je.validSchemaType=ng;function rg({schema:t,opts:e,self:n,errSchemaPath:r},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=rg});var hl=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendSubschemaMode=$t.extendSubschemaData=$t.getSubschema=void 0;var Ye=A(),pl=M();function og(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}${(0,Ye.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pl.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}$t.getSubschema=og;function ig(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,h=a.let("data",(0,Ye._)`${e.data}${(0,Ye.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Ye.str)`${l}${(0,pl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ye._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ye.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}$t.extendSubschemaData=ig;function sg(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}$t.extendSubschemaMode=sg});var Ki=_((B$,gl)=>{"use strict";gl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var _l=_((q$,yl)=>{"use strict";var Rt=yl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};po(e,r,o,t,"",t)};Rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rt.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 po(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Rt.arrayKeywords)for(var h=0;h<d.length;h++)po(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in Rt.propsKeywords){if(d&&typeof d=="object")for(var p in d)po(t,e,n,d[p],o+"/"+u+"/"+ag(p),i,o,u,r,p)}else(u in Rt.keywords||t.allKeys&&!(u in Rt.skipKeywords))&&po(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function ag(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var cg=M(),lg=Ki(),ug=_l(),dg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function fg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ji(t):e?wl(t)<=e:!1}ve.inlineRef=fg;var mg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ji(t){for(let e in t){if(mg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ji)||typeof n=="object"&&Ji(n))return!0}return!1}function wl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!dg.has(n)&&(typeof t[n]=="object"&&(0,cg.eachItem)(t[n],r=>e+=wl(r)),e===1/0))return 1/0}return e}function vl(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return bl(t,r)}ve.getFullPath=vl;function bl(t,e){return t.serialize(e).split("#")[0]+"#"}ve._getFullPath=bl;var pg=/#\/?$/;function Rn(t){return t?t.replace(pg,""):""}ve.normalizeId=Rn;function hg(t,e,n){return n=Rn(n),t.resolve(e,n)}ve.resolveUrl=hg;var gg=/^[a-z_][-a-z0-9._]*$/i;function yg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=vl(r,o,!1),a={},c=new Set;return ug(t,{allKeys:!0},(d,h,p,f)=>{if(f===void 0)return;let m=s+h,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[h]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=Rn(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?l(d,$.schema,S):S!==Rn(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!gg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!lg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ve.getSchemaRefs=yg});var wr=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getData=Pt.KeywordCxt=Pt.validateFunctionCode=void 0;var Rl=tl(),Sl=hr(),Qi=qi(),ho=hr(),_g=cl(),_r=ml(),Yi=hl(),b=A(),P=ut(),wg=gr(),dt=M(),yr=pr();function vg(t){if(Al(t)&&(Cl(t),Tl(t))){Eg(t);return}Pl(t,()=>(0,Rl.topBoolOrEmptySchema)(t))}Pt.validateFunctionCode=vg;function Pl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${El(n,o)}`),Sg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${bg(o)}`,r.$async,()=>t.code(El(n,o)).code(i))}function bg(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function Sg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function Eg(t){let{schema:e,opts:n,gen:r}=t;Pl(t,()=>{n.$comment&&e.$comment&&Il(t),Tg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&kg(t),xl(t),xg(t)})}function kg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function El(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function $g(t,e){if(Al(t)&&(Cl(t),Tl(t))){Rg(t,e);return}(0,Rl.boolOrEmptySchema)(t,e)}function Tl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Al(t){return typeof t.schema!="boolean"}function Rg(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Il(t),Ag(t),Cg(t);let i=r.const("_errs",P.default.errors);xl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Cl(t){(0,dt.checkUnknownRules)(t),Pg(t)}function xl(t,e){if(t.opts.jtd)return kl(t,[],!1,e);let n=(0,Sl.getSchemaTypes)(t.schema),r=(0,Sl.coerceAndCheckDataType)(t,n);kl(t,n,!r,e)}function Pg(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,dt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Tg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,dt.checkStrictMode)(t,"default is ignored in the schema root")}function Ag(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Cg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Il({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function xg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Ig(t),e.return((0,b._)`${P.default.errors} === 0`))}function Ig({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function kl(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,dt.schemaHasRulesButRef)(i,u))){o.block(()=>Nl(t,"$ref",u.all.$ref.definition));return}c.jtd||Og(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Qi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,ho.checkDataType)(h.type,s,c.strictNumbers)),$l(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,ho.reportTypeError)(t)),o.endIf()):$l(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function $l(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,_g.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Qi.shouldUseRule)(r,i)&&Nl(t,i.keyword,i.definition,e.type)})}function Og(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ng(t,e),t.opts.allowUnionTypes||Mg(t,e),Lg(t,t.dataTypes))}function Ng(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ol(t.dataTypes,n)||Xi(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dg(t,e)}}function Mg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Xi(t,"use allowUnionTypes to allow union type keyword")}function Lg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Qi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>jg(e,s))&&Xi(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function jg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ol(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dg(t,e){let n=[];for(let r of t.dataTypes)Ol(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Xi(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,dt.checkStrictMode)(t,e,t.opts.strictTypes)}var go=class{constructor(e,n,r){if((0,_r.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,dt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Ml(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_r.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?yr.reportExtraError:yr.reportError)(this,this.def.error,n)}$dataError(){(0,yr.reportError)(this,this.def.$dataError||yr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,ho.checkDataTypes)(c,n,i.opts.strictNumbers,ho.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,Yi.getSubschema)(this.it,e);(0,Yi.extendSubschemaData)(r,this.it,e),(0,Yi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return $g(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=dt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=dt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Pt.KeywordCxt=go;function Nl(t,e,n,r){let o=new go(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,_r.funcKeywordCode)(o,n):"macro"in n?(0,_r.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,_r.funcKeywordCode)(o,n)}var Fg=/^\/(?:[^~]|~0|~1)*$/,Bg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ml(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Fg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=Bg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,dt.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Pt.getData=Ml});var yo=_(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Zi=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};es.default=Zi});var vr=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var ts=gr(),ns=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ts.resolveUrl)(e,n,r),this.missingSchema=(0,ts.normalizeId)((0,ts.getFullPath)(e,this.missingRef))}};rs.default=ns});var wo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var De=A(),qg=yo(),Kt=ut(),Fe=gr(),Ll=M(),Ug=wr(),Pn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Fe.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Oe.SchemaEnv=Pn;function is(t){let e=jl.call(this,t);if(e)return e;let n=(0,Fe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new De.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:qg.default,code:(0,De._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[De.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,De.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:De.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,De._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Ug.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Kt.default.self}`,`${Kt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;p.evaluated={props:f instanceof De.Name?void 0:f,items:m instanceof De.Name?void 0:m,dynamicProps:f instanceof De.Name,dynamicItems:m instanceof De.Name},p.source&&(p.source.evaluated=(0,De.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Oe.compileSchema=is;function Hg(t,e,n){var r;n=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Vg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new Pn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Gg.call(this,i)}Oe.resolveRef=Hg;function Gg(t){return(0,Fe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:is.call(this,t)}function jl(t){for(let e of this._compilations)if(Wg(e,t))return e}Oe.getCompilingSchema=jl;function Wg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Vg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_o.call(this,t,e)}function _o(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Fe._getFullPath)(this.opts.uriResolver,n),o=(0,Fe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return os.call(this,n,t);let i=(0,Fe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=_o.call(this,t,s);return typeof a?.schema!="object"?void 0:os.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||is.call(this,s),i===(0,Fe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new Pn({schema:a,schemaId:c,root:t,baseId:o})}return os.call(this,n,s)}}Oe.resolveSchema=_o;var zg=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function os(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Ll.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!zg.has(a)&&l&&(e=(0,Fe.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Ll.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=_o.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new Pn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Dl=_((z$,Kg)=>{Kg.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 as=_((K$,Ul)=>{"use strict";var Jg=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Bl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ss(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var Yg=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fl(t){return t.length=0,!0}function Qg(t,e,n){if(t.length){let r=ss(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Xg(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=Qg;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=Fl}else{o.push(l);continue}}return o.length&&(a===Fl?n.zone=o.join(""):s?r.push(o.join("")):r.push(ss(o))),n.address=r.join(""),n}function ql(t){if(Zg(t,":")<2)return{host:t,isIPV6:!1};let e=Xg(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Zg(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ey(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function ty(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ny(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Bl(n)){let r=ql(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Ul.exports={nonSimpleDomain:Yg,recomposeAuthority:ny,normalizeComponentEncoding:ty,removeDotSegments:ey,isIPv4:Bl,isUUID:Jg,normalizeIPv6:ql,stringArrayToHexStripped:ss}});var zl=_((J$,Vl)=>{"use strict";var{isUUID:ry}=as(),oy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,iy=["http","https","ws","wss","urn","urn:uuid"];function sy(t){return iy.indexOf(t)!==-1}function cs(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Hl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Gl(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ay(t){return t.secure=cs(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cy(t){if((t.port===(cs(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function ly(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(oy);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=ls(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uy(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=ls(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function dy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ry(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function fy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wl={scheme:"http",domainHost:!0,parse:Hl,serialize:Gl},my={scheme:"https",domainHost:Wl.domainHost,parse:Hl,serialize:Gl},vo={scheme:"ws",domainHost:!0,parse:ay,serialize:cy},py={scheme:"wss",domainHost:vo.domainHost,parse:vo.parse,serialize:vo.serialize},hy={scheme:"urn",parse:ly,serialize:uy,skipNormalize:!0},gy={scheme:"urn:uuid",parse:dy,serialize:fy,skipNormalize:!0},bo={http:Wl,https:my,ws:vo,wss:py,urn:hy,"urn:uuid":gy};Object.setPrototypeOf(bo,null);function ls(t){return t&&(bo[t]||bo[t.toLowerCase()])||void 0}Vl.exports={wsIsSecure:cs,SCHEMES:bo,isValidSchemeName:sy,getSchemeHandler:ls}});var Yl=_((Y$,Eo)=>{"use strict";var{normalizeIPv6:yy,removeDotSegments:br,recomposeAuthority:_y,normalizeComponentEncoding:So,isIPv4:wy,nonSimpleDomain:vy}=as(),{SCHEMES:by,getSchemeHandler:Kl}=zl();function Sy(t,e){return typeof t=="string"?t=Qe(ft(t,e),e):typeof t=="object"&&(t=ft(Qe(t,e),e)),t}function Ey(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Jl(ft(t,r),ft(e,r),r,!0);return r.skipEscape=!0,Qe(o,r)}function Jl(t,e,n,r){let o={};return r||(t=ft(Qe(t,n),n),e=ft(Qe(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=br(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ky(t,e,n){return typeof t=="string"?(t=unescape(t),t=Qe(So(ft(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Qe(So(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Qe(So(ft(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Qe(So(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Qe(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=Kl(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=_y(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=br(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var $y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ft(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match($y);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(wy(r.host)===!1){let c=yy(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=Kl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&vy(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var us={SCHEMES:by,normalize:Sy,resolve:Ey,resolveComponent:Jl,equal:ky,serialize:Qe,parse:ft};Eo.exports=us;Eo.exports.default=us;Eo.exports.fastUri=us});var Xl=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var Ql=Yl();Ql.code='require("ajv/dist/runtime/uri").default';ds.default=Ql});var su=_(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=void 0;var Ry=wr();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Ry.KeywordCxt}});var Tn=A();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Tn._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Tn.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Tn.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Tn.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Tn.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Tn.CodeGen}});var Py=yo(),ru=vr(),Ty=Bi(),Sr=wo(),Ay=A(),Er=gr(),ko=hr(),ms=M(),Zl=Dl(),Cy=Xl(),ou=(t,e)=>new RegExp(t,e);ou.code="new RegExp";var xy=["removeAdditional","useDefaults","coerceTypes"],Iy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Oy={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."},Ny={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},eu=200;function My(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,$,z,Q,ie,ze;let it=t.strict,nr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ke=nr===!0||nr===void 0?1:nr||0,ne=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ou,Bt=(o=t.uriResolver)!==null&&o!==void 0?o:Cy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:it)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:it)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:it)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:it)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:it)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Ke,regExp:ne}:{optimize:Ke,regExp:ne},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:eu,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:eu,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(ie=t.unicodeRegExp)!==null&&ie!==void 0?ie:!0,int32range:(ze=t.int32range)!==null&&ze!==void 0?ze:!0,uriResolver:Bt}}var kr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...My(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Ay.ValueScope({scope:{},prefixes:Iy,es5:n,lines:r}),this.logger=qy(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ty.getRules)(),tu.call(this,Oy,e,"NOT SUPPORTED"),tu.call(this,Ny,e,"DEPRECATED","warn"),this._metaOpts=Fy.call(this),e.formats&&jy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Dy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ly.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Zl;r==="id"&&(o={...Zl},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof ru.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Er.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=nu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Sr.SchemaEnv({schema:{},schemaId:r});if(n=Sr.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=nu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Er.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Hy.call(this,r,n),!n)return(0,ms.eachItem)(r,i=>fs.call(this,i)),this;Wy.call(this,n);let o={...n,type:(0,ko.getJSONTypes)(n.type),schemaType:(0,ko.getJSONTypes)(n.schemaType)};return(0,ms.eachItem)(r,o.type.length===0?i=>fs.call(this,i,o):i=>o.type.forEach(s=>fs.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=iu(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,Er.normalizeId)(s||r);let l=Er.getSchemaRefs.call(this,e,r);return c=new Sr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Sr.compileSchema.call(this,e)}finally{this.opts=n}}};kr.ValidationError=Py.default;kr.MissingRefError=ru.default;se.default=kr;function tu(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function nu(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ly(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function jy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Dy(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Fy(){let t={...this.opts};for(let e of xy)delete t[e];return t}var By={log(){},warn(){},error(){}};function qy(t){if(t===!1)return By;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Uy=/^[a-z_$][a-z0-9_$:-]*$/i;function Hy(t,e){let{RULES:n}=this;if((0,ms.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Uy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function fs(t,e,n){var r;let o=e?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ko.getJSONTypes)(e.type),schemaType:(0,ko.getJSONTypes)(e.schemaType)}};e.before?Gy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function Gy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Wy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=iu(e)),t.validateSchema=this.compile(e,!0))}var Vy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iu(t){return{anyOf:[t,Vy]}}});var au=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var zy={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ps.default=zy});var du=_(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.callRef=Jt.getValidate=void 0;var Ky=vr(),cu=Ie(),be=A(),An=ut(),lu=wo(),$o=M(),Jy={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=lu.resolveRef.call(c,l,o,n);if(u===void 0)throw new Ky.default(r.opts.uriResolver,o,n);if(u instanceof lu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Ro(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Ro(t,(0,be._)`${f}.validate`,l,l.$async)}function h(f){let m=uu(t,f);Ro(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,be.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function uu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Jt.getValidate=uu;function Ro(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?An.default.this:be.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,cu.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,cu.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,be._)`${f}.errors`;o.assign(An.default.vErrors,(0,be._)`${An.default.vErrors} === null ? ${m} : ${An.default.vErrors}.concat(${m})`),o.assign(An.default.errors,(0,be._)`${An.default.vErrors}.length`)}function p(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=$o.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,be._)`${f}.evaluated.props`);i.props=$o.mergeEvaluated.props(o,y,i.props,be.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=$o.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,be._)`${f}.evaluated.items`);i.items=$o.mergeEvaluated.items(o,y,i.items,be.Name)}}}Jt.callRef=Ro;Jt.default=Jy});var fu=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Yy=au(),Qy=du(),Xy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Yy.default,Qy.default];hs.default=Xy});var mu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var Po=A(),Tt=Po.operators,To={maximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},minimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},exclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},exclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},Zy={message:({keyword:t,schemaCode:e})=>(0,Po.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Po._)`{comparison: ${To[t].okStr}, limit: ${e}}`},e_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:Zy,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Po._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};gs.default=e_});var pu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var $r=A(),t_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},n_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:t_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,$r._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$r._)`${s} !== parseInt(${s})`;t.fail$data((0,$r._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};ys.default=n_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});function hu(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}_s.default=hu;hu.code='require("ajv/dist/runtime/ucs2length").default'});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var Yt=A(),r_=M(),o_=gu(),i_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Yt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Yt._)`{limit: ${t}}`},s_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Yt.operators.GT:Yt.operators.LT,s=o.opts.unicode===!1?(0,Yt._)`${n}.length`:(0,Yt._)`${(0,r_.useFunc)(t.gen,o_.default)}(${n})`;t.fail$data((0,Yt._)`${s} ${i} ${r}`)}};ws.default=s_});var _u=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var a_=Ie(),c_=M(),Cn=A(),l_={message:({schemaCode:t})=>(0,Cn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cn._)`{pattern: ${t}}`},u_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:l_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,Cn._)`new RegExp`:(0,c_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Cn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Cn._)`!${u}`)}else{let c=(0,a_.usePattern)(t,o);t.fail$data((0,Cn._)`!${c}.test(${n})`)}}};vs.default=u_});var wu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Rr=A(),d_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Rr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Rr._)`{limit: ${t}}`},f_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:d_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Rr.operators.GT:Rr.operators.LT;t.fail$data((0,Rr._)`Object.keys(${n}).length ${o} ${r}`)}};bs.default=f_});var vu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var Pr=Ie(),Tr=A(),m_=M(),p_={message:({params:{missingProperty:t}})=>(0,Tr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Tr._)`{missingProperty: ${t}}`},h_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:p_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(p?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,m_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Tr.nil,d);else for(let p of n)(0,Pr.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>h(p,f)),t.ok(f)}else e.if((0,Pr.checkMissingProp)(t,n,p)),(0,Pr.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Pr.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Pr.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Tr.not)(f),()=>{t.error(),e.break()})},Tr.nil)}}};Ss.default=h_});var bu=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ar=A(),g_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ar.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},y_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:g_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`${n}.length ${o} ${r}`)}};Es.default=y_});var Ao=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Su=Ki();Su.code='require("ajv/dist/runtime/equal").default';ks.default=Su});var Eu=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $s=hr(),ae=A(),__=M(),w_=Ao(),v_={message:({params:{i:t,j:e}})=>(0,ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ae._)`{i: ${t}, j: ${e}}`},b_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:v_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,$s.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,ae._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,ae._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,ae._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,$s.checkDataTypes)(l,g,a.opts.strictNumbers,$s.DataType.Wrong),v=e.const("indices",(0,ae._)`{}`);e.for((0,ae._)`;${f}--;`,()=>{e.let(g,(0,ae._)`${n}[${f}]`),e.if(y,(0,ae._)`continue`),l.length>1&&e.if((0,ae._)`typeof ${g} == "string"`,(0,ae._)`${g} += "_"`),e.if((0,ae._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,ae._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ae._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,__.useFunc)(e,w_.default),y=e.name("outer");e.label(y).for((0,ae._)`;${f}--;`,()=>e.for((0,ae._)`${m} = ${f}; ${m}--;`,()=>e.if((0,ae._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Rs.default=b_});var ku=_(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var Ps=A(),S_=M(),E_=Ao(),k_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ps._)`{allowedValue: ${t}}`},$_={keyword:"const",$data:!0,error:k_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ps._)`!${(0,S_.useFunc)(e,E_.default)}(${n}, ${o})`):t.fail((0,Ps._)`${i} !== ${n}`)}};Ts.default=$_});var $u=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Cr=A(),R_=M(),P_=Ao(),T_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Cr._)`{allowedValues: ${t}}`},A_={keyword:"enum",schemaType:"array",$data:!0,error:T_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,R_.useFunc)(e,P_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Cr.or)(...o.map((f,m)=>h(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Cr._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Cr._)`${l()}(${n}, ${p}[${f}])`:(0,Cr._)`${n} === ${m}`}}};As.default=A_});var Ru=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var C_=mu(),x_=pu(),I_=yu(),O_=_u(),N_=wu(),M_=vu(),L_=bu(),j_=Eu(),D_=ku(),F_=$u(),B_=[C_.default,x_.default,I_.default,O_.default,N_.default,M_.default,L_.default,j_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},D_.default,F_.default];Cs.default=B_});var Is=_(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateAdditionalItems=void 0;var Qt=A(),xs=M(),q_={message:({params:{len:t}})=>(0,Qt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qt._)`{limit: ${t}}`},U_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:q_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,xs.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Pu(t,r)}};function Pu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Qt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Qt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,xs.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Qt._)`${a} <= ${e.length}`);n.if((0,Qt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:xs.Type.Num},l),s.allErrors||n.if((0,Qt.not)(l),()=>n.break())})}}xr.validateAdditionalItems=Pu;xr.default=U_});var Os=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var Tu=A(),Co=M(),H_=Ie(),G_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Au(t,"additionalItems",e);n.items=!0,!(0,Co.alwaysValidSchema)(n,e)&&t.ok((0,H_.validateArray)(t))}};function Au(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Co.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Tu._)`${i}.length`);n.forEach((d,h)=>{(0,Co.alwaysValidSchema)(a,d)||(r.if((0,Tu._)`${l} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function u(d){let{opts:h,errSchemaPath:p}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(h.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Co.checkStrictMode)(a,g,h.strictTuples)}}}Ir.validateTuple=Au;Ir.default=G_});var Cu=_(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var W_=Os(),V_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,W_.validateTuple)(t,"items")};Ns.default=V_});var Iu=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var xu=A(),z_=M(),K_=Ie(),J_=Is(),Y_={message:({params:{len:t}})=>(0,xu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xu._)`{limit: ${t}}`},Q_={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Y_,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,z_.alwaysValidSchema)(r,e)&&(o?(0,J_.validateAdditionalItems)(t,o):t.ok((0,K_.validateArray)(t)))}};Ms.default=Q_});var Ou=_(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Ne=A(),xo=M(),X_={message:({params:{min:t,max:e}})=>e===void 0?(0,Ne.str)`must contain at least ${t} valid item(s)`:(0,Ne.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ne._)`{minContains: ${t}}`:(0,Ne._)`{minContains: ${t}, maxContains: ${e}}`},Z_={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:X_,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Ne._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,xo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,xo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xo.alwaysValidSchema)(i,n)){let m=(0,Ne._)`${u} >= ${s}`;a!==void 0&&(m=(0,Ne._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Ne._)`${o}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>f(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:xo.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Ne._)`${m}++`),a===void 0?e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Ne._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Ls.default=Z_});var Lu=_(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var js=A(),ew=M(),Or=Ie();Xe.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,js.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,js._)`{property: ${t},
8
8
  missingProperty: ${r},
9
9
  depsCount: ${e},
10
- deps: ${n}}`};var X_={keyword:"dependencies",type:"object",schemaType:"object",error:Qe.error,code(t){let[e,n]=Z_(t);Iu(t,e),Ou(t,n)}};function Z_({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Iu(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,xr.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,xr.checkReportMissingProp)(t,l)}):(n.if((0,Ns._)`${c} && (${(0,xr.checkMissingProp)(t,a,i)})`),(0,xr.reportMissingProp)(t,i),n.else())}}Qe.validatePropertyDeps=Iu;function Ou(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,Q_.alwaysValidSchema)(i,e[a])||(n.if((0,xr.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Qe.validateSchemaDeps=Ou;Qe.default=X_});var Lu=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var Mu=A(),ew=M(),tw={message:"property name must be valid",params:({params:t})=>(0,Mu._)`{propertyName: ${t.propertyName}}`},nw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:tw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,ew.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,Mu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Ms.default=nw});var js=_(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var xo=Ce(),Fe=A(),rw=ct(),Co=M(),ow={message:"must NOT have additional properties",params:({params:t})=>(0,Fe._)`{additionalProperty: ${t.additionalProperty}}`},iw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ow,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Co.alwaysValidSchema)(s,n))return;let l=(0,xo.allSchemaProperties)(r.properties),u=(0,xo.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Fe._)`${i} === ${rw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(p(g),()=>f(g))})}function p(g){let y;if(l.length>8){let v=(0,Co.schemaRefOrVal)(s,r.properties,"properties");y=(0,xo.isOwnProperty)(e,v,g)}else l.length?y=(0,Fe.or)(...l.map(v=>(0,Fe._)`${g} === ${v}`)):y=Fe.nil;return u.length&&(y=(0,Fe.or)(y,...u.map(v=>(0,Fe._)`${(0,xo.usePattern)(t,v)}.test(${g})`))),(0,Fe.not)(y)}function h(g){e.code((0,Fe._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Co.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Fe.not)(y),()=>{t.reset(),h(g)})):(m(g,y),a||e.if((0,Fe.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Co.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Ls.default=iw});var Fu=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var sw=gr(),ju=Ce(),Ds=M(),Du=js(),aw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Du.default.code(new sw.KeywordCxt(i,Du.default,"additionalProperties"));let s=(0,ju.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Ds.mergeEvaluated.props(e,(0,Ds.toHash)(s),i.props));let a=s.filter(d=>!(0,Ds.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,ju.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Fs.default=aw});var Hu=_(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var Bu=Ce(),Io=A(),qu=M(),Uu=M(),cw={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,Bu.allSchemaProperties)(n),c=a.filter(m=>(0,qu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof Io.Name)&&(i.props=(0,Uu.evaluatedPropsToName)(e,i.props));let{props:d}=i;p();function p(){for(let m of a)l&&h(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function h(m){for(let g in l)new RegExp(m).test(g)&&(0,qu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,Io._)`${(0,Bu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:Uu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,Io._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,Io.not)(u),()=>e.break())})})}}};Bs.default=cw});var Wu=_(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var lw=M(),uw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,lw.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};qs.default=uw});var Vu=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var dw=Ce(),fw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:dw.validateUnion,error:{message:"must match a schema in anyOf"}};Us.default=fw});var Gu=_(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var Oo=A(),mw=M(),hw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Oo._)`{passingSchemas: ${t.passing}}`},pw={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let p;(0,mw.alwaysValidSchema)(o,u)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Oo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Oo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Oo.Name)})})}}};Hs.default=pw});var zu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var gw=M(),yw={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,gw.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Ws.default=yw});var Yu=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var No=A(),Ju=M(),_w={message:({params:t})=>(0,No.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,No._)`{failingKeyword: ${t.ifClause}}`},ww={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:_w,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Ju.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Ku(r,"then"),i=Ku(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,No.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let p=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,No._)`${u}`):t.setParams({ifClause:u})}}}};function Ku(t,e){let n=t.schema[e];return n!==void 0&&!(0,Ju.alwaysValidSchema)(t,n)}Vs.default=ww});var Qu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var vw=M(),bw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,vw.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Gs.default=bw});var Xu=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var Sw=As(),Ew=Tu(),$w=xs(),kw=xu(),Rw=Cu(),Pw=Nu(),Tw=Lu(),Aw=js(),xw=Fu(),Cw=Hu(),Iw=Wu(),Ow=Vu(),Nw=Gu(),Mw=zu(),Lw=Yu(),jw=Qu();function Dw(t=!1){let e=[Iw.default,Ow.default,Nw.default,Mw.default,Lw.default,jw.default,Tw.default,Aw.default,Pw.default,xw.default,Cw.default];return t?e.push(Ew.default,kw.default):e.push(Sw.default,$w.default),e.push(Rw.default),e}zs.default=Dw});var Zu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Y=A(),Fw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Bw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Fw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?p():h();function p(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,k=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${k}`}}function h(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn(k());return}throw new Error(k());function k(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S(k){let G=k instanceof RegExp?(0,Y.regexpCode)(k):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,Q=n.scopeValue("formats",{key:i,ref:k,code:G});return typeof k=="object"&&!(k instanceof RegExp)?[k.type||"string",k.validate,(0,Y._)`${Q}.validate`]:["string",k,Q]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Ks.default=Bw});var ed=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var qw=Zu(),Uw=[qw.default];Js.default=Uw});var td=_(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.contentVocabulary=Tn.metadataVocabulary=void 0;Tn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Tn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rd=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var Hw=uu(),Ww=$u(),Vw=Xu(),Gw=ed(),nd=td(),zw=[Hw.default,Ww.default,(0,Vw.default)(),Gw.default,nd.metadataVocabulary,nd.contentVocabulary];Ys.default=zw});var id=_(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.DiscrError=void 0;var od;(function(t){t.Tag="tag",t.Mapping="mapping"})(od||(Mo.DiscrError=od={}))});var ad=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var An=A(),Qs=id(),sd=yo(),Kw=yr(),Jw=M(),Yw={message:({params:{discrError:t,tagName:e}})=>t===Qs.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,An._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},Qw={keyword:"discriminator",type:"object",schemaType:"object",error:Yw,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,An._)`${n}${(0,An.getProperty)(a)}`);e.if((0,An._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Qs.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let h=p();e.if(!1);for(let f in h)e.elseIf((0,An._)`${l} === ${f}`),e.assign(c,d(h[f]));e.else(),t.error(!1,{discrError:Qs.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(h){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},f);return t.mergeEvaluated(m,An.Name),f}function p(){var h;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let k=s[R];if(k?.$ref&&!(0,Jw.schemaHasRulesButRef)(k,i.self.RULES)){let Q=k.$ref;if(k=sd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Q),k instanceof sd.SchemaEnv&&(k=k.schema),k===void 0)throw new Kw.default(i.opts.uriResolver,i.baseId,Q)}let G=(h=k?.properties)===null||h===void 0?void 0:h[a];if(typeof G!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(k)),v(G,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,k){if(R.const)S(R.const,k);else if(R.enum)for(let G of R.enum)S(G,k);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,k){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=k}}}};Xs.default=Qw});var cd=_((TR,Xw)=>{Xw.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 jo=_((W,Zs)=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var Zw=ou(),ev=rd(),tv=ad(),ld=cd(),nv=["/properties"],Lo="http://json-schema.org/draft-07/schema",xn=class extends Zw.default{_addVocabularies(){super._addVocabularies(),ev.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(tv.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ld,nv):ld;this.addMetaSchema(e,Lo,!1),this.refs["http://json-schema.org/schema"]=Lo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lo)?Lo:void 0)}};W.Ajv=xn;Zs.exports=W=xn;Zs.exports.Ajv=xn;Object.defineProperty(W,"__esModule",{value:!0});W.default=xn;var rv=gr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return rv.KeywordCxt}});var Cn=A();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Cn._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Cn.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Cn.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Cn.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Cn.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Cn.CodeGen}});var ov=po();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return ov.default}});var iv=yr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return iv.default}})});var yd=_(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.formatNames=Ze.fastFormats=Ze.fullFormats=void 0;function Xe(t,e){return{validate:t,compare:e}}Ze.fullFormats={date:Xe(md,ra),time:Xe(ta(!0),oa),"date-time":Xe(ud(!0),pd),"iso-time":Xe(ta(),hd),"iso-date-time":Xe(ud(),gd),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:dv,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:_v,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:fv,int32:{type:"number",validate:pv},int64:{type:"number",validate:gv},float:{type:"number",validate:fd},double:{type:"number",validate:fd},password:!0,binary:!0};Ze.fastFormats={...Ze.fullFormats,date:Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ra),time:Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,oa),"date-time":Xe(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pd),"iso-time":Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,hd),"iso-date-time":Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gd),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};Ze.formatNames=Object.keys(Ze.fullFormats);function sv(t){return t%4===0&&(t%100!==0||t%400===0)}var av=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,cv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function md(t){let e=av.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&sv(n)?29:cv[r])}function ra(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ea=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ta(t){return function(n){let r=ea.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,p=o-l*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function oa(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function hd(t,e){if(!(t&&e))return;let n=ea.exec(t),r=ea.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var na=/t|\s/i;function ud(t){let e=ta(t);return function(r){let o=r.split(na);return o.length===2&&md(o[0])&&e(o[1])}}function pd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function gd(t,e){if(!(t&&e))return;let[n,r]=t.split(na),[o,i]=e.split(na),s=ra(n,o);if(s!==void 0)return s||oa(r,i)}var lv=/\/|:/,uv=/^(?:[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 dv(t){return lv.test(t)&&uv.test(t)}var dd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function fv(t){return dd.lastIndex=0,dd.test(t)}var mv=-(2**31),hv=2**31-1;function pv(t){return Number.isInteger(t)&&t<=hv&&t>=mv}function gv(t){return Number.isInteger(t)}function fd(){return!0}var yv=/[^\\]\\Z/;function _v(t){if(yv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _d=_(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.formatLimitDefinition=void 0;var wv=jo(),Be=A(),At=Be.operators,Do={formatMaximum:{okStr:"<=",ok:At.LTE,fail:At.GT},formatMinimum:{okStr:">=",ok:At.GTE,fail:At.LT},formatExclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},formatExclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},vv={message:({keyword:t,schemaCode:e})=>(0,Be.str)`should be ${Do[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Be._)`{comparison: ${Do[t].okStr}, limit: ${e}}`};In.formatLimitDefinition={keyword:Object.keys(Do),type:"string",schemaType:"string",$data:!0,error:vv,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new wv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let p=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),h=e.const("fmt",(0,Be._)`${p}[${c.schemaCode}]`);t.fail$data((0,Be.or)((0,Be._)`typeof ${h} != "object"`,(0,Be._)`${h} instanceof RegExp`,(0,Be._)`typeof ${h}.compare != "function"`,d(h)))}function u(){let p=c.schema,h=a.formats[p];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let f=e.scopeValue("formats",{key:p,ref:h,code:s.code.formats?(0,Be._)`${s.code.formats}${(0,Be.getProperty)(p)}`:void 0});t.fail$data(d(f))}function d(p){return(0,Be._)`${p}.compare(${n}, ${r}) ${Do[o].fail} 0`}},dependencies:["format"]};var bv=t=>(t.addKeyword(In.formatLimitDefinition),t);In.default=bv});var aa=_((Cr,bd)=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});var On=yd(),Sv=_d(),ia=A(),wd=new ia.Name("fullFormats"),Ev=new ia.Name("fastFormats"),sa=(t,e={keywords:!0})=>{if(Array.isArray(e))return vd(t,e,On.fullFormats,wd),t;let[n,r]=e.mode==="fast"?[On.fastFormats,Ev]:[On.fullFormats,wd],o=e.formats||On.formatNames;return vd(t,o,n,r),e.keywords&&(0,Sv.default)(t),t};sa.get=(t,e="full")=>{let r=(e==="fast"?On.fastFormats:On.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function vd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ia._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}bd.exports=Cr=sa;Object.defineProperty(Cr,"__esModule",{value:!0});Cr.default=sa});var ft=_((QR,xd)=>{"use strict";var Td=["nodebuffer","arraybuffer","fragments"],Ad=typeof Blob<"u";Ad&&Td.push("blob");xd.exports={BINARY_TYPES:Td,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ad,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ir=_((XR,Fo)=>{"use strict";var{EMPTY_BUFFER:Mv}=ft(),la=Buffer[Symbol.species];function Lv(t,e){if(t.length===0)return Mv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new la(n.buffer,n.byteOffset,r):n}function Cd(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function Id(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function jv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ua(t){if(ua.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new la(t):ArrayBuffer.isView(t)?e=new la(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ua.readOnly=!1),e}Fo.exports={concat:Lv,mask:Cd,toArrayBuffer:jv,toBuffer:ua,unmask:Id};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");Fo.exports.mask=function(e,n,r,o,i){i<48?Cd(e,n,r,o,i):t.mask(e,n,r,o,i)},Fo.exports.unmask=function(e,n){e.length<32?Id(e,n):t.unmask(e,n)}}catch{}});var Md=_((ZR,Nd)=>{"use strict";var Od=Symbol("kDone"),da=Symbol("kRun"),fa=class{constructor(e){this[Od]=()=>{this.pending--,this[da]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[da]()}[da](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Od])}}};Nd.exports=fa});var Dn=_((eP,Fd)=>{"use strict";var Or=Z("zlib"),Ld=Ir(),Dv=Md(),{kStatusCode:jd}=ft(),Fv=Buffer[Symbol.species],Bv=Buffer.from([0,0,255,255]),qo=Symbol("permessage-deflate"),mt=Symbol("total-length"),Ln=Symbol("callback"),xt=Symbol("buffers"),jn=Symbol("error"),Bo,ma=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Bo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Bo=new Dv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ln];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Bo.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Bo.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Or.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Or.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[qo]=this,this._inflate[mt]=0,this._inflate[xt]=[],this._inflate.on("error",Uv),this._inflate.on("data",Dd)}this._inflate[Ln]=r,this._inflate.write(e),n&&this._inflate.write(Bv),this._inflate.flush(()=>{let i=this._inflate[jn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Ld.concat(this._inflate[xt],this._inflate[mt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[mt]=0,this._inflate[xt]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Or.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Or.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[mt]=0,this._deflate[xt]=[],this._deflate.on("data",qv)}this._deflate[Ln]=r,this._deflate.write(e),this._deflate.flush(Or.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ld.concat(this._deflate[xt],this._deflate[mt]);n&&(i=new Fv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ln]=null,this._deflate[mt]=0,this._deflate[xt]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Fd.exports=ma;function qv(t){this[xt].push(t),this[mt]+=t.length}function Dd(t){if(this[mt]+=t.length,this[qo]._maxPayload<1||this[mt]<=this[qo]._maxPayload){this[xt].push(t);return}this[jn]=new RangeError("Max payload size exceeded"),this[jn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[jn][jd]=1009,this.removeListener("data",Dd),this.reset()}function Uv(t){if(this[qo]._inflate=null,this[jn]){this[Ln](this[jn]);return}t[jd]=1007,this[Ln](t)}});var Fn=_((tP,Uo)=>{"use strict";var{isUtf8:Bd}=Z("buffer"),{hasBlob:Hv}=ft(),Wv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Vv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ha(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Gv(t){return Hv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Uo.exports={isBlob:Gv,isValidStatusCode:Vv,isValidUTF8:ha,tokenChars:Wv};if(Bd)Uo.exports.isValidUTF8=function(t){return t.length<24?ha(t):Bd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Uo.exports.isValidUTF8=function(e){return e.length<32?ha(e):t(e)}}catch{}});var wa=_((nP,zd)=>{"use strict";var{Writable:zv}=Z("stream"),qd=Dn(),{BINARY_TYPES:Kv,EMPTY_BUFFER:Ud,kStatusCode:Jv,kWebSocket:Yv}=ft(),{concat:pa,toArrayBuffer:Qv,unmask:Xv}=Ir(),{isValidStatusCode:Zv,isValidUTF8:Hd}=Fn(),Ho=Buffer[Symbol.species],Ne=0,Wd=1,Vd=2,Gd=3,ga=4,ya=5,Wo=6,_a=class extends zv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Kv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Yv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,n,r){if(this._opcode===8&&this._state==Ne)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Ho(r.buffer,r.byteOffset+e,r.length-e),new Ho(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Ho(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case Wd:this.getPayloadLength16(e);break;case Vd:this.getPayloadLength64(e);break;case Gd:this.getMask();break;case ga:this.getData(e);break;case ya:case Wo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[qd.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Wd:this._payloadLength===127?this._state=Vd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Gd:this._state=ga}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ga}getData(e){let n=Ud;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Xv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=ya,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[qd.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Ne&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=pa(r,n):this._binaryType==="arraybuffer"?o=Qv(pa(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Ne):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!0),this._state=Ne,this.startLoop(e)}))}else{let o=pa(r,n);if(!this._skipUTF8Validation&&!Hd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ya||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Ne):(this._state=Wo,setImmediate(()=>{this.emit("message",o,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ud),this.end();else{let r=e.readUInt16BE(0);if(!Zv(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Ho(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Wo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Jv]=o,s}};zd.exports=_a});var Sa=_((oP,Yd)=>{"use strict";var{Duplex:rP}=Z("stream"),{randomFillSync:eb}=Z("crypto"),Kd=Dn(),{EMPTY_BUFFER:tb,kWebSocket:nb,NOOP:rb}=ft(),{isBlob:Bn,isValidStatusCode:ob}=Fn(),{mask:Jd,toBuffer:en}=Ir(),Me=Symbol("kByteLength"),ib=Buffer.alloc(4),Vo=8*1024,tn,qn=Vo,qe=0,sb=1,ab=2,va=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=qe,this.onerror=rb,this[nb]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||ib,n.generateMask?n.generateMask(r):(qn===Vo&&(tn===void 0&&(tn=Buffer.alloc(Vo)),eb(tn,0,Vo),qn=0),r[0]=tn[qn++],r[1]=tn[qn++],r[2]=tn[qn++],r[3]=tn[qn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Me]!==void 0?a=n[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(Jd(e,r,l,i,a),[l]):(Jd(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=tb;else{if(typeof e!="number"||!ob(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==qe?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Bn(e)?(o=e.size,i=!1):(e=en(e),o=e.length,i=en.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Bn(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==qe?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Bn(e)?(o=e.size,i=!1):(e=en(e),o=e.length,i=en.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Bn(e)?this._state!==qe?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==qe?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Kd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Bn(e)?(a=e.size,c=!1):(e=en(e),a=e.length,c=en.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Bn(e)?this._state!==qe?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==qe?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Me],this._state=ab,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ba,this,a,o);return}this._bufferedBytes-=r[Me];let s=en(i);n?this.dispatch(s,n,r,o):(this._state=qe,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(cb,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Kd.extensionName];this._bufferedBytes+=r[Me],this._state=sb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ba(this,c,o);return}this._bufferedBytes-=r[Me],this._state=qe,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===qe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Yd.exports=va;function ba(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function cb(t,e,n){ba(t,e,n),t.onerror(e)}});var sf=_((iP,of)=>{"use strict";var{kForOnEventAttribute:Nr,kListener:Ea}=ft(),Qd=Symbol("kCode"),Xd=Symbol("kData"),Zd=Symbol("kError"),ef=Symbol("kMessage"),tf=Symbol("kReason"),Un=Symbol("kTarget"),nf=Symbol("kType"),rf=Symbol("kWasClean"),ht=class{constructor(e){this[Un]=null,this[nf]=e}get target(){return this[Un]}get type(){return this[nf]}};Object.defineProperty(ht.prototype,"target",{enumerable:!0});Object.defineProperty(ht.prototype,"type",{enumerable:!0});var nn=class extends ht{constructor(e,n={}){super(e),this[Qd]=n.code===void 0?0:n.code,this[tf]=n.reason===void 0?"":n.reason,this[rf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Qd]}get reason(){return this[tf]}get wasClean(){return this[rf]}};Object.defineProperty(nn.prototype,"code",{enumerable:!0});Object.defineProperty(nn.prototype,"reason",{enumerable:!0});Object.defineProperty(nn.prototype,"wasClean",{enumerable:!0});var Hn=class extends ht{constructor(e,n={}){super(e),this[Zd]=n.error===void 0?null:n.error,this[ef]=n.message===void 0?"":n.message}get error(){return this[Zd]}get message(){return this[ef]}};Object.defineProperty(Hn.prototype,"error",{enumerable:!0});Object.defineProperty(Hn.prototype,"message",{enumerable:!0});var Mr=class extends ht{constructor(e,n={}){super(e),this[Xd]=n.data===void 0?null:n.data}get data(){return this[Xd]}};Object.defineProperty(Mr.prototype,"data",{enumerable:!0});var lb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[Nr]&&o[Ea]===e&&!o[Nr])return;let r;if(t==="message")r=function(i,s){let a=new Mr("message",{data:s?i:i.toString()});a[Un]=this,Go(e,this,a)};else if(t==="close")r=function(i,s){let a=new nn("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Un]=this,Go(e,this,a)};else if(t==="error")r=function(i){let s=new Hn("error",{error:i,message:i.message});s[Un]=this,Go(e,this,s)};else if(t==="open")r=function(){let i=new ht("open");i[Un]=this,Go(e,this,i)};else return;r[Nr]=!!n[Nr],r[Ea]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ea]===e&&!n[Nr]){this.removeListener(t,n);break}}};of.exports={CloseEvent:nn,ErrorEvent:Hn,Event:ht,EventTarget:lb,MessageEvent:Mr};function Go(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var zo=_((sP,af)=>{"use strict";var{tokenChars:Lr}=Fn();function et(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function ub(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Lr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);l===44?(et(e,h,n),n=Object.create(null)):s=h,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Lr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),et(n,t.slice(c,u),!0),l===44&&(et(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Lr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Lr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Lr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(c,u);r&&(h=h.replace(/\\/g,""),r=!1),et(n,a,h),l===44&&(et(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let p=t.slice(c,u);return s===void 0?et(e,p,n):(a===void 0?et(n,p,!0):r?et(n,a,p.replace(/\\/g,"")):et(n,a,p),et(e,s,n)),e}function db(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}af.exports={format:db,parse:ub}});var Qo=_((lP,wf)=>{"use strict";var fb=Z("events"),mb=Z("https"),hb=Z("http"),uf=Z("net"),pb=Z("tls"),{randomBytes:gb,createHash:yb}=Z("crypto"),{Duplex:aP,Readable:cP}=Z("stream"),{URL:$a}=Z("url"),Ct=Dn(),_b=wa(),wb=Sa(),{isBlob:vb}=Fn(),{BINARY_TYPES:cf,CLOSE_TIMEOUT:bb,EMPTY_BUFFER:Ko,GUID:Sb,kForOnEventAttribute:ka,kListener:Eb,kStatusCode:$b,kWebSocket:re,NOOP:df}=ft(),{EventTarget:{addEventListener:kb,removeEventListener:Rb}}=sf(),{format:Pb,parse:Tb}=zo(),{toBuffer:Ab}=Ir(),ff=Symbol("kAborted"),Ra=[8,13],pt=["CONNECTING","OPEN","CLOSING","CLOSED"],xb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends fb{constructor(e,n,r){super(),this._binaryType=cf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ko,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),mf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){cf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new _b({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new wb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[re]=this,i[re]=this,e[re]=this,o.on("conclude",Ob),o.on("drain",Nb),o.on("error",Mb),o.on("message",Lb),o.on("ping",jb),o.on("pong",Db),i.onerror=Fb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",gf),e.on("data",Yo),e.on("end",yf),e.on("error",_f),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ct.extensionName]&&this._extensions[Ct.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ke(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),pf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Pa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ko,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Pa(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ko,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Pa(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ct.extensionName]||(o.compress=!1),this._sender.send(e||Ko,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ke(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ka])return e[Eb];return null},set(e){for(let n of this.listeners(t))if(n[ka]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[ka]:!0})}})});V.prototype.addEventListener=kb;V.prototype.removeEventListener=Rb;wf.exports=V;function mf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:bb,protocolVersion:Ra[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Ra.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ra.join(", ")})`);let i;if(e instanceof $a)i=e;else try{i=new $a(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Jo(t,m);return}let l=s?443:80,u=gb(16).toString("base64"),d=s?mb.request:hb.request,p=new Set,h;if(o.createConnection=o.createConnection||(s?Ib:Cb),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(h=new Ct({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Pb({[Ct.extensionName]:h.offer()})),n.length){for(let m of n){if(typeof m!="string"||!xb.test(m)||p.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{ke(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[ff]||(f=t._req=null,Jo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){ke(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new $a(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Jo(t,R);return}mf(t,v,n,r)}else t.emit("unexpected-response",f,m)||ke(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==V.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){ke(t,g,"Invalid Upgrade header");return}let S=yb("sha1").update(u+Sb).digest("base64");if(m.headers["sec-websocket-accept"]!==S){ke(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],k;if(R!==void 0?p.size?p.has(R)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":p.size&&(k="Server sent no subprotocol"),k){ke(t,g,k);return}R&&(t._protocol=R);let G=m.headers["sec-websocket-extensions"];if(G!==void 0){if(!h){ke(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Q;try{Q=Tb(G)}catch{ke(t,g,"Invalid Sec-WebSocket-Extensions header");return}let oe=Object.keys(Q);if(oe.length!==1||oe[0]!==Ct.extensionName){ke(t,g,"Server indicated an extension that was not requested");return}try{h.accept(Q[Ct.extensionName])}catch{ke(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ct.extensionName]=h}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Jo(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Cb(t){return t.path=t.socketPath,uf.connect(t)}function Ib(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=uf.isIP(t.host)?"":t.host),pb.connect(t)}function ke(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ke),e.setHeader?(e[ff]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Jo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Pa(t,e,n){if(e){let r=vb(e)?e.size:Ab(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${pt[t.readyState]})`);process.nextTick(n,r)}}function Ob(t,e){let n=this[re];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[re]!==void 0&&(n._socket.removeListener("data",Yo),process.nextTick(hf,n._socket),t===1005?n.close():n.close(t,e))}function Nb(){let t=this[re];t.isPaused||t._socket.resume()}function Mb(t){let e=this[re];e._socket[re]!==void 0&&(e._socket.removeListener("data",Yo),process.nextTick(hf,e._socket),e.close(t[$b])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function lf(){this[re].emitClose()}function Lb(t,e){this[re].emit("message",t,e)}function jb(t){let e=this[re];e._autoPong&&e.pong(t,!this._isServer,df),e.emit("ping",t)}function Db(t){this[re].emit("pong",t)}function hf(t){t.resume()}function Fb(t){let e=this[re];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,pf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function pf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function gf(){let t=this[re];if(this.removeListener("close",gf),this.removeListener("data",Yo),this.removeListener("end",yf),t._readyState=V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[re]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",lf),t._receiver.on("finish",lf))}function Yo(t){this[re]._receiver.write(t)||this.pause()}function yf(){let t=this[re];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function _f(){let t=this[re];this.removeListener("error",_f),this.on("error",df),t&&(t._readyState=V.CLOSING,this.destroy())}});var Ef=_((dP,Sf)=>{"use strict";var uP=Qo(),{Duplex:Bb}=Z("stream");function vf(t){t.emit("close")}function qb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function bf(t){this.removeListener("error",bf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Ub(t,e){let n=!0,r=new Bb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(vf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(vf,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",qb),r.on("error",bf),r}Sf.exports=Ub});var Ta=_((fP,$f)=>{"use strict";var{tokenChars:Hb}=Fn();function Wb(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Hb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}$f.exports={parse:Wb}});var Cf=_((hP,xf)=>{"use strict";var Vb=Z("events"),Xo=Z("http"),{Duplex:mP}=Z("stream"),{createHash:Gb}=Z("crypto"),kf=zo(),rn=Dn(),zb=Ta(),Kb=Qo(),{CLOSE_TIMEOUT:Jb,GUID:Yb,kWebSocket:Qb}=ft(),Xb=/^[+/0-9A-Za-z]{22}==$/,Rf=0,Pf=1,Af=2,Aa=class extends Vb{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Jb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Kb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Xo.createServer((r,o)=>{let i=Xo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Zb(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Rf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Af){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(jr,this);return}if(e&&this.once("close",e),this._state!==Pf)if(this._state=Pf,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(jr,this):process.nextTick(jr,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{jr(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Tf);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){on(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){on(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Xb.test(i)){on(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){on(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Dr(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=zb.parse(c)}catch{on(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let p=new rn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=kf.parse(u);h[rn.extensionName]&&(p.accept(h[rn.extensionName]),d[rn.extensionName]=p)}catch{on(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,f,m,g)=>{if(!h)return Dr(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(p))return Dr(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[Qb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rf)return Dr(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gb("sha1").update(n+Yb).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[rn.extensionName]){let d=e[rn.extensionName].params,p=kf.format({[rn.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${p}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
10
+ deps: ${n}}`};var tw={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(t){let[e,n]=nw(t);Nu(t,e),Mu(t,n)}};function nw({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Nu(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Or.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,Or.checkReportMissingProp)(t,l)}):(n.if((0,js._)`${c} && (${(0,Or.checkMissingProp)(t,a,i)})`),(0,Or.reportMissingProp)(t,i),n.else())}}Xe.validatePropertyDeps=Nu;function Mu(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,ew.alwaysValidSchema)(i,e[a])||(n.if((0,Or.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Xe.validateSchemaDeps=Mu;Xe.default=tw});var Du=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var ju=A(),rw=M(),ow={message:"property name must be valid",params:({params:t})=>(0,ju._)`{propertyName: ${t.propertyName}}`},iw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ow,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,rw.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,ju.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Ds.default=iw});var Bs=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Io=Ie(),Be=A(),sw=ut(),Oo=M(),aw={message:"must NOT have additional properties",params:({params:t})=>(0,Be._)`{additionalProperty: ${t.additionalProperty}}`},cw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Oo.alwaysValidSchema)(s,n))return;let l=(0,Io.allSchemaProperties)(r.properties),u=(0,Io.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Be._)`${i} === ${sw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(l.length>8){let v=(0,Oo.schemaRefOrVal)(s,r.properties,"properties");y=(0,Io.isOwnProperty)(e,v,g)}else l.length?y=(0,Be.or)(...l.map(v=>(0,Be._)`${g} === ${v}`)):y=Be.nil;return u.length&&(y=(0,Be.or)(y,...u.map(v=>(0,Be._)`${(0,Io.usePattern)(t,v)}.test(${g})`))),(0,Be.not)(y)}function p(g){e.code((0,Be._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){p(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Oo.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Be.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Be.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Oo.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Fs.default=cw});var qu=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var lw=wr(),Fu=Ie(),qs=M(),Bu=Bs(),uw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Bu.default.code(new lw.KeywordCxt(i,Bu.default,"additionalProperties"));let s=(0,Fu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=qs.mergeEvaluated.props(e,(0,qs.toHash)(s),i.props));let a=s.filter(d=>!(0,qs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Fu.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Us.default=uw});var Wu=_(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var Uu=Ie(),No=A(),Hu=M(),Gu=M(),dw={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,Uu.allSchemaProperties)(n),c=a.filter(m=>(0,Hu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof No.Name)&&(i.props=(0,Gu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)l&&p(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,Hu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,No._)`${(0,Uu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:Gu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,No._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,No.not)(u),()=>e.break())})})}}};Hs.default=dw});var Vu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var fw=M(),mw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,fw.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Gs.default=mw});var zu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var pw=Ie(),hw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pw.validateUnion,error:{message:"must match a schema in anyOf"}};Ws.default=hw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Mo=A(),gw=M(),yw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},_w={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let h;(0,gw.alwaysValidSchema)(o,u)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Mo.Name)})})}}};Vs.default=_w});var Ju=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var ww=M(),vw={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,ww.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};zs.default=vw});var Xu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Lo=A(),Qu=M(),bw={message:({params:t})=>(0,Lo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lo._)`{failingKeyword: ${t.ifClause}}`},Sw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Qu.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Yu(r,"then"),i=Yu(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Lo.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,Lo._)`${u}`):t.setParams({ifClause:u})}}}};function Yu(t,e){let n=t.schema[e];return n!==void 0&&!(0,Qu.alwaysValidSchema)(t,n)}Ks.default=Sw});var Zu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Ew=M(),kw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Ew.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Js.default=kw});var ed=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var $w=Is(),Rw=Cu(),Pw=Os(),Tw=Iu(),Aw=Ou(),Cw=Lu(),xw=Du(),Iw=Bs(),Ow=qu(),Nw=Wu(),Mw=Vu(),Lw=zu(),jw=Ku(),Dw=Ju(),Fw=Xu(),Bw=Zu();function qw(t=!1){let e=[Mw.default,Lw.default,jw.default,Dw.default,Fw.default,Bw.default,xw.default,Iw.default,Cw.default,Ow.default,Nw.default];return t?e.push(Rw.default,Tw.default):e.push($w.default,Pw.default),e.push(Aw.default),e}Ys.default=qw});var td=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Y=A(),Uw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Hw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Uw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?h():p();function h(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,$=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S($){let z=$ instanceof RegExp?(0,Y.regexpCode)($):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,Q=n.scopeValue("formats",{key:i,ref:$,code:z});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Y._)`${Q}.validate`]:["string",$,Q]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Qs.default=Hw});var nd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Gw=td(),Ww=[Gw.default];Xs.default=Ww});var rd=_(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var id=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Vw=fu(),zw=Ru(),Kw=ed(),Jw=nd(),od=rd(),Yw=[Vw.default,zw.default,(0,Kw.default)(),Jw.default,od.metadataVocabulary,od.contentVocabulary];Zs.default=Yw});var ad=_(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.DiscrError=void 0;var sd;(function(t){t.Tag="tag",t.Mapping="mapping"})(sd||(jo.DiscrError=sd={}))});var ld=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var In=A(),ea=ad(),cd=wo(),Qw=vr(),Xw=M(),Zw={message:({params:{discrError:t,tagName:e}})=>t===ea.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,In._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},ev={keyword:"discriminator",type:"object",schemaType:"object",error:Zw,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,In._)`${n}${(0,In.getProperty)(a)}`);e.if((0,In._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:ea.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,In._)`${l} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:ea.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(m,In.Name),f}function h(){var p;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let $=s[R];if($?.$ref&&!(0,Xw.schemaHasRulesButRef)($,i.self.RULES)){let Q=$.$ref;if($=cd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Q),$ instanceof cd.SchemaEnv&&($=$.schema),$===void 0)throw new Qw.default(i.opts.uriResolver,i.baseId,Q)}let z=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(z,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,$){if(R.const)S(R.const,$);else if(R.enum)for(let z of R.enum)S(z,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,$){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=$}}}};ta.default=ev});var ud=_((DR,tv)=>{tv.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 Fo=_((G,na)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.MissingRefError=G.ValidationError=G.CodeGen=G.Name=G.nil=G.stringify=G.str=G._=G.KeywordCxt=G.Ajv=void 0;var nv=su(),rv=id(),ov=ld(),dd=ud(),iv=["/properties"],Do="http://json-schema.org/draft-07/schema",On=class extends nv.default{_addVocabularies(){super._addVocabularies(),rv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ov.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dd,iv):dd;this.addMetaSchema(e,Do,!1),this.refs["http://json-schema.org/schema"]=Do}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Do)?Do:void 0)}};G.Ajv=On;na.exports=G=On;na.exports.Ajv=On;Object.defineProperty(G,"__esModule",{value:!0});G.default=On;var sv=wr();Object.defineProperty(G,"KeywordCxt",{enumerable:!0,get:function(){return sv.KeywordCxt}});var Nn=A();Object.defineProperty(G,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(G,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(G,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(G,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(G,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(G,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var av=yo();Object.defineProperty(G,"ValidationError",{enumerable:!0,get:function(){return av.default}});var cv=vr();Object.defineProperty(G,"MissingRefError",{enumerable:!0,get:function(){return cv.default}})});var wd=_(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(t,e){return{validate:t,compare:e}}et.fullFormats={date:Ze(hd,sa),time:Ze(oa(!0),aa),"date-time":Ze(fd(!0),yd),"iso-time":Ze(oa(),gd),"iso-date-time":Ze(fd(),_d),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pv,"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:bv,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:hv,int32:{type:"number",validate:_v},int64:{type:"number",validate:wv},float:{type:"number",validate:pd},double:{type:"number",validate:pd},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sa),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aa),"date-time":Ze(/^\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,yd),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gd),"iso-date-time":Ze(/^\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,_d),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};et.formatNames=Object.keys(et.fullFormats);function lv(t){return t%4===0&&(t%100!==0||t%400===0)}var uv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hd(t){let e=uv.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&lv(n)?29:dv[r])}function sa(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ra=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function oa(t){return function(n){let r=ra.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,h=o-l*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function aa(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function gd(t,e){if(!(t&&e))return;let n=ra.exec(t),r=ra.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var ia=/t|\s/i;function fd(t){let e=oa(t);return function(r){let o=r.split(ia);return o.length===2&&hd(o[0])&&e(o[1])}}function yd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function _d(t,e){if(!(t&&e))return;let[n,r]=t.split(ia),[o,i]=e.split(ia),s=sa(n,o);if(s!==void 0)return s||aa(r,i)}var fv=/\/|:/,mv=/^(?:[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 pv(t){return fv.test(t)&&mv.test(t)}var md=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hv(t){return md.lastIndex=0,md.test(t)}var gv=-(2**31),yv=2**31-1;function _v(t){return Number.isInteger(t)&&t<=yv&&t>=gv}function wv(t){return Number.isInteger(t)}function pd(){return!0}var vv=/[^\\]\\Z/;function bv(t){if(vv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var vd=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.formatLimitDefinition=void 0;var Sv=Fo(),qe=A(),At=qe.operators,Bo={formatMaximum:{okStr:"<=",ok:At.LTE,fail:At.GT},formatMinimum:{okStr:">=",ok:At.GTE,fail:At.LT},formatExclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},formatExclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},Ev={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Bo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Bo[t].okStr}, limit: ${e}}`};Mn.formatLimitDefinition={keyword:Object.keys(Bo),type:"string",schemaType:"string",$data:!0,error:Ev,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Sv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let h=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,qe._)`${h}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${p} != "object"`,(0,qe._)`${p} instanceof RegExp`,(0,qe._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=c.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${h}" does not define "compare" function`);let f=e.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,qe._)`${s.code.formats}${(0,qe.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,qe._)`${h}.compare(${n}, ${r}) ${Bo[o].fail} 0`}},dependencies:["format"]};var kv=t=>(t.addKeyword(Mn.formatLimitDefinition),t);Mn.default=kv});var ua=_((Nr,Ed)=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});var Ln=wd(),$v=vd(),ca=A(),bd=new ca.Name("fullFormats"),Rv=new ca.Name("fastFormats"),la=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sd(t,e,Ln.fullFormats,bd),t;let[n,r]=e.mode==="fast"?[Ln.fastFormats,Rv]:[Ln.fullFormats,bd],o=e.formats||Ln.formatNames;return Sd(t,o,n,r),e.keywords&&(0,$v.default)(t),t};la.get=(t,e="full")=>{let r=(e==="fast"?Ln.fastFormats:Ln.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Sd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ca._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Ed.exports=Nr=la;Object.defineProperty(Nr,"__esModule",{value:!0});Nr.default=la});var pt=_((aP,Id)=>{"use strict";var Cd=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Cd.push("blob");Id.exports={BINARY_TYPES:Cd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Mr=_((cP,qo)=>{"use strict";var{EMPTY_BUFFER:Dv}=pt(),fa=Buffer[Symbol.species];function Fv(t,e){if(t.length===0)return Dv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new fa(n.buffer,n.byteOffset,r):n}function Od(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function Nd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Bv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ma(t){if(ma.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new fa(t):ArrayBuffer.isView(t)?e=new fa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ma.readOnly=!1),e}qo.exports={concat:Fv,mask:Od,toArrayBuffer:Bv,toBuffer:ma,unmask:Nd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Od(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?Nd(e,n):t.unmask(e,n)}}catch{}});var jd=_((lP,Ld)=>{"use strict";var Md=Symbol("kDone"),pa=Symbol("kRun"),ha=class{constructor(e){this[Md]=()=>{this.pending--,this[pa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pa]()}[pa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Md])}}};Ld.exports=ha});var qn=_((uP,qd)=>{"use strict";var Lr=Z("zlib"),Dd=Mr(),qv=jd(),{kStatusCode:Fd}=pt(),Uv=Buffer[Symbol.species],Hv=Buffer.from([0,0,255,255]),Ho=Symbol("permessage-deflate"),ht=Symbol("total-length"),Fn=Symbol("callback"),Ct=Symbol("buffers"),Bn=Symbol("error"),Uo,ga=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Uo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new qv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Fn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Uo.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Uo.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Lr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ho]=this,this._inflate[ht]=0,this._inflate[Ct]=[],this._inflate.on("error",Wv),this._inflate.on("data",Bd)}this._inflate[Fn]=r,this._inflate.write(e),n&&this._inflate.write(Hv),this._inflate.flush(()=>{let i=this._inflate[Bn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Dd.concat(this._inflate[Ct],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Lr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ht]=0,this._deflate[Ct]=[],this._deflate.on("data",Gv)}this._deflate[Fn]=r,this._deflate.write(e),this._deflate.flush(Lr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Dd.concat(this._deflate[Ct],this._deflate[ht]);n&&(i=new Uv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Fn]=null,this._deflate[ht]=0,this._deflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};qd.exports=ga;function Gv(t){this[Ct].push(t),this[ht]+=t.length}function Bd(t){if(this[ht]+=t.length,this[Ho]._maxPayload<1||this[ht]<=this[Ho]._maxPayload){this[Ct].push(t);return}this[Bn]=new RangeError("Max payload size exceeded"),this[Bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bn][Fd]=1009,this.removeListener("data",Bd),this.reset()}function Wv(t){if(this[Ho]._inflate=null,this[Bn]){this[Fn](this[Bn]);return}t[Fd]=1007,this[Fn](t)}});var Un=_((dP,Go)=>{"use strict";var{isUtf8:Ud}=Z("buffer"),{hasBlob:Vv}=pt(),zv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Kv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ya(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Jv(t){return Vv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:Jv,isValidStatusCode:Kv,isValidUTF8:ya,tokenChars:zv};if(Ud)Go.exports.isValidUTF8=function(t){return t.length<24?ya(t):Ud(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?ya(e):t(e)}}catch{}});var Sa=_((fP,Jd)=>{"use strict";var{Writable:Yv}=Z("stream"),Hd=qn(),{BINARY_TYPES:Qv,EMPTY_BUFFER:Gd,kStatusCode:Xv,kWebSocket:Zv}=pt(),{concat:_a,toArrayBuffer:eb,unmask:tb}=Mr(),{isValidStatusCode:nb,isValidUTF8:Wd}=Un(),Wo=Buffer[Symbol.species],Me=0,Vd=1,zd=2,Kd=3,wa=4,va=5,Vo=6,ba=class extends Yv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Qv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Zv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Me}_write(e,n,r){if(this._opcode===8&&this._state==Me)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e),new Wo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Me:this.getInfo(e);break;case Vd:this.getPayloadLength16(e);break;case zd:this.getPayloadLength64(e);break;case Kd:this.getMask();break;case wa:this.getData(e);break;case va:case Vo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Hd.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Vd:this._payloadLength===127?this._state=zd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Kd:this._state=wa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wa}getData(e){let n=Gd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&tb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=va,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hd.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Me&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Me;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=_a(r,n):this._binaryType==="arraybuffer"?o=eb(_a(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!0),this._state=Me,this.startLoop(e)}))}else{let o=_a(r,n);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===va||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!1),this._state=Me,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gd),this.end();else{let r=e.readUInt16BE(0);if(!nb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Me;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Me,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Xv]=o,s}};Jd.exports=ba});var $a=_((pP,Xd)=>{"use strict";var{Duplex:mP}=Z("stream"),{randomFillSync:rb}=Z("crypto"),Yd=qn(),{EMPTY_BUFFER:ob,kWebSocket:ib,NOOP:sb}=pt(),{isBlob:Hn,isValidStatusCode:ab}=Un(),{mask:Qd,toBuffer:tn}=Mr(),Le=Symbol("kByteLength"),cb=Buffer.alloc(4),zo=8*1024,nn,Gn=zo,Ue=0,lb=1,ub=2,Ea=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ue,this.onerror=sb,this[ib]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||cb,n.generateMask?n.generateMask(r):(Gn===zo&&(nn===void 0&&(nn=Buffer.alloc(zo)),rb(nn,0,zo),Gn=0),r[0]=nn[Gn++],r[1]=nn[Gn++],r[2]=nn[Gn++],r[3]=nn[Gn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Le]!==void 0?a=n[Le]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(Qd(e,r,l,i,a),[l]):(Qd(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=ob;else{if(typeof e!="number"||!ab(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Le]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ue?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Yd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Hn(e)?(a=e.size,c=!1):(e=tn(e),a=e.length,c=tn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Le]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ue?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Le],this._state=ub,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ka,this,a,o);return}this._bufferedBytes-=r[Le];let s=tn(i);n?this.dispatch(s,n,r,o):(this._state=Ue,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(db,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Yd.extensionName];this._bufferedBytes+=r[Le],this._state=lb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ka(this,c,o);return}this._bufferedBytes-=r[Le],this._state=Ue,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===Ue&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Le],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Xd.exports=Ea;function ka(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function db(t,e,n){ka(t,e,n),t.onerror(e)}});var cf=_((hP,af)=>{"use strict";var{kForOnEventAttribute:jr,kListener:Ra}=pt(),Zd=Symbol("kCode"),ef=Symbol("kData"),tf=Symbol("kError"),nf=Symbol("kMessage"),rf=Symbol("kReason"),Wn=Symbol("kTarget"),of=Symbol("kType"),sf=Symbol("kWasClean"),gt=class{constructor(e){this[Wn]=null,this[of]=e}get target(){return this[Wn]}get type(){return this[of]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var rn=class extends gt{constructor(e,n={}){super(e),this[Zd]=n.code===void 0?0:n.code,this[rf]=n.reason===void 0?"":n.reason,this[sf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Zd]}get reason(){return this[rf]}get wasClean(){return this[sf]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Vn=class extends gt{constructor(e,n={}){super(e),this[tf]=n.error===void 0?null:n.error,this[nf]=n.message===void 0?"":n.message}get error(){return this[tf]}get message(){return this[nf]}};Object.defineProperty(Vn.prototype,"error",{enumerable:!0});Object.defineProperty(Vn.prototype,"message",{enumerable:!0});var Dr=class extends gt{constructor(e,n={}){super(e),this[ef]=n.data===void 0?null:n.data}get data(){return this[ef]}};Object.defineProperty(Dr.prototype,"data",{enumerable:!0});var fb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[jr]&&o[Ra]===e&&!o[jr])return;let r;if(t==="message")r=function(i,s){let a=new Dr("message",{data:s?i:i.toString()});a[Wn]=this,Ko(e,this,a)};else if(t==="close")r=function(i,s){let a=new rn("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Wn]=this,Ko(e,this,a)};else if(t==="error")r=function(i){let s=new Vn("error",{error:i,message:i.message});s[Wn]=this,Ko(e,this,s)};else if(t==="open")r=function(){let i=new gt("open");i[Wn]=this,Ko(e,this,i)};else return;r[jr]=!!n[jr],r[Ra]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ra]===e&&!n[jr]){this.removeListener(t,n);break}}};af.exports={CloseEvent:rn,ErrorEvent:Vn,Event:gt,EventTarget:fb,MessageEvent:Dr};function Ko(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jo=_((gP,lf)=>{"use strict";var{tokenChars:Fr}=Un();function tt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function mb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);l===44?(tt(e,p,n),n=Object.create(null)):s=p,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),tt(n,t.slice(c,u),!0),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Fr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Fr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);r&&(p=p.replace(/\\/g,""),r=!1),tt(n,a,p),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let h=t.slice(c,u);return s===void 0?tt(e,h,n):(a===void 0?tt(n,h,!0):r?tt(n,a,h.replace(/\\/g,"")):tt(n,a,h),tt(e,s,n)),e}function pb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lf.exports={format:pb,parse:mb}});var Zo=_((wP,bf)=>{"use strict";var hb=Z("events"),gb=Z("https"),yb=Z("http"),ff=Z("net"),_b=Z("tls"),{randomBytes:wb,createHash:vb}=Z("crypto"),{Duplex:yP,Readable:_P}=Z("stream"),{URL:Pa}=Z("url"),xt=qn(),bb=Sa(),Sb=$a(),{isBlob:Eb}=Un(),{BINARY_TYPES:uf,CLOSE_TIMEOUT:kb,EMPTY_BUFFER:Yo,GUID:$b,kForOnEventAttribute:Ta,kListener:Rb,kStatusCode:Pb,kWebSocket:oe,NOOP:mf}=pt(),{EventTarget:{addEventListener:Tb,removeEventListener:Ab}}=cf(),{format:Cb,parse:xb}=Jo(),{toBuffer:Ib}=Mr(),pf=Symbol("kAborted"),Aa=[8,13],yt=["CONNECTING","OPEN","CLOSING","CLOSED"],Ob=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends hb{constructor(e,n,r){super(),this._binaryType=uf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),hf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new bb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Sb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[oe]=this,i[oe]=this,e[oe]=this,o.on("conclude",Lb),o.on("drain",jb),o.on("error",Db),o.on("message",Fb),o.on("ping",Bb),o.on("pong",qb),i.onerror=Ub,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",_f),e.on("data",Xo),e.on("end",wf),e.on("error",vf),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[xt.extensionName]&&this._extensions[xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xt.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ta])return e[Rb];return null},set(e){for(let n of this.listeners(t))if(n[Ta]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ta]:!0})}})});V.prototype.addEventListener=Tb;V.prototype.removeEventListener=Ab;bf.exports=V;function hf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kb,protocolVersion:Aa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Aa.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Aa.join(", ")})`);let i;if(e instanceof Pa)i=e;else try{i=new Pa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Qo(t,m);return}let l=s?443:80,u=wb(16).toString("base64"),d=s?gb.request:yb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?Mb:Nb),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new xt({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Cb({[xt.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Ob.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{$e(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[pf]||(f=t._req=null,Qo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){$e(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new Pa(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Qo(t,R);return}hf(t,v,n,r)}else t.emit("unexpected-response",f,m)||$e(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==V.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){$e(t,g,"Invalid Upgrade header");return}let S=vb("sha1").update(u+$b).digest("base64");if(m.headers["sec-websocket-accept"]!==S){$e(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],$;if(R!==void 0?h.size?h.has(R)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":h.size&&($="Server sent no subprotocol"),$){$e(t,g,$);return}R&&(t._protocol=R);let z=m.headers["sec-websocket-extensions"];if(z!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Q;try{Q=xb(z)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ie=Object.keys(Q);if(ie.length!==1||ie[0]!==xt.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(Q[xt.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xt.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Qo(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Nb(t){return t.path=t.socketPath,ff.connect(t)}function Mb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ff.isIP(t.host)?"":t.host),_b.connect(t)}function $e(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[pf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ca(t,e,n){if(e){let r=Eb(e)?e.size:Ib(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${yt[t.readyState]})`);process.nextTick(n,r)}}function Lb(t,e){let n=this[oe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[oe]!==void 0&&(n._socket.removeListener("data",Xo),process.nextTick(gf,n._socket),t===1005?n.close():n.close(t,e))}function jb(){let t=this[oe];t.isPaused||t._socket.resume()}function Db(t){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(gf,e._socket),e.close(t[Pb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function df(){this[oe].emitClose()}function Fb(t,e){this[oe].emit("message",t,e)}function Bb(t){let e=this[oe];e._autoPong&&e.pong(t,!this._isServer,mf),e.emit("ping",t)}function qb(t){this[oe].emit("pong",t)}function gf(t){t.resume()}function Ub(t){let e=this[oe];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,yf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function _f(){let t=this[oe];if(this.removeListener("close",_f),this.removeListener("data",Xo),this.removeListener("end",wf),t._readyState=V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[oe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",df),t._receiver.on("finish",df))}function Xo(t){this[oe]._receiver.write(t)||this.pause()}function wf(){let t=this[oe];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function vf(){let t=this[oe];this.removeListener("error",vf),this.on("error",mf),t&&(t._readyState=V.CLOSING,this.destroy())}});var $f=_((bP,kf)=>{"use strict";var vP=Zo(),{Duplex:Hb}=Z("stream");function Sf(t){t.emit("close")}function Gb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ef(t){this.removeListener("error",Ef),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wb(t,e){let n=!0,r=new Hb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(Sf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(Sf,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",Gb),r.on("error",Ef),r}kf.exports=Wb});var xa=_((SP,Rf)=>{"use strict";var{tokenChars:Vb}=Un();function zb(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Vb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Rf.exports={parse:zb}});var Of=_((kP,If)=>{"use strict";var Kb=Z("events"),ei=Z("http"),{Duplex:EP}=Z("stream"),{createHash:Jb}=Z("crypto"),Pf=Jo(),on=qn(),Yb=xa(),Qb=Zo(),{CLOSE_TIMEOUT:Xb,GUID:Zb,kWebSocket:eS}=pt(),tS=/^[+/0-9A-Za-z]{22}==$/,Tf=0,Af=1,xf=2,Ia=class extends Kb{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Xb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Qb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ei.createServer((r,o)=>{let i=ei.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=nS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Tf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===xf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Br,this);return}if(e&&this.once("close",e),this._state!==Af)if(this._state=Af,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Br,this):process.nextTick(Br,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Br(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Cf);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){sn(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!tS.test(i)){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qr(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Yb.parse(c)}catch{sn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new on({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Pf.parse(u);p[on.extensionName]&&(h.accept(p[on.extensionName]),d[on.extensionName]=h)}catch{sn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,f,m,g)=>{if(!p)return qr(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return qr(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[eS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Tf)return qr(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Jb("sha1").update(n+Zb).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[on.extensionName]){let d=e[on.extensionName].params,h=Pf.format({[on.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
11
11
  `).join(`\r
12
- `)),i.removeListener("error",Tf),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(jr,this)})),a(u,o)}};xf.exports=Aa;function Zb(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function jr(t){t._state=Af,t.emit("close")}function Tf(){this.destroy()}function Dr(t,e,n,r){n=n||Xo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Xo.STATUS_CODES[e]}\r
12
+ `)),i.removeListener("error",Cf),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Br,this)})),a(u,o)}};If.exports=Ia;function nS(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Br(t){t._state=xf,t.emit("close")}function Cf(){this.destroy()}function qr(t,e,n,r){n=n||ei.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ei.STATUS_CODES[e]}\r
13
13
  `+Object.keys(r).map(o=>`${o}: ${r[o]}`).join(`\r
14
14
  `)+`\r
15
15
  \r
16
- `+n)}function on(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,on),t.emit("wsClientError",s,n,e)}else Dr(n,r,o,i)}});var $c={"-v":"version","-h":"help"};function bh(t){return t.startsWith("--")?!0:$c[t]!==void 0}function kc(t,e){let n=[],r={},o=[],i=new Map;for(let c of e)i.set(c.name,c);let s=!1,a=0;for(;a<t.length;){let c=t[a];if(s){n.push(c),a+=1;continue}if(c==="--"){s=!0,a+=1;continue}if(c.startsWith("--")){let l=c.indexOf("="),u=l>=0?c.slice(2,l):c.slice(2),d=l>=0?c.slice(l+1):void 0,p=i.get(u);if(!p){o.push(`unknown flag: --${u}`),a+=1;continue}if(p.type==="boolean"){d===void 0||d==="true"?r[u]=!0:d==="false"?r[u]=!1:o.push(`flag --${u} expects no value (got "${d}")`),a+=1;continue}let h;if(d!==void 0)h=d,a+=1;else{let f=t[a+1];if(f===void 0||bh(f)){o.push(`flag --${u} requires a value`),a+=1;continue}h=f,a+=2}if(p.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(h)){o.push(`flag --${u} requires a number (got "${h}")`);continue}r[u]=Number(h);continue}r[u]=h;continue}if(c.startsWith("-")&&c.length>1){let l=$c[c];if(!l){o.push(`unknown flag: ${c}`),a+=1;continue}let u=i.get(l);if(!u||u.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[l]=!0,a+=1;continue}n.push(c),a+=1}for(let c of e)c.default!==void 0&&r[c.name]===void 0&&(r[c.name]=c.default);for(let c of e)c.required&&r[c.name]===void 0&&o.push(`missing required flag: --${c.name}`);return{positional:n,flags:r,errors:o}}import Tc from"node:path";import Ac from"node:fs";import Rc from"node:fs";import Sh from"node:os";import Pc from"node:path";var Eh=Pc.join(".aifight","runtime");function ne(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Pc.join(Sh.homedir(),Eh)}function ot(){let t=ne();if(Rc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Rc.chmodSync(t,448)}catch{}}var $e=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function $h(){return Tc.join(ne(),"token")}function kh(){return Tc.join(ne(),"port")}function xc(){let t=$h(),e;try{e=Ac.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new $e("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new $e("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new $e("token_corrupt",t,`token file at ${t} is empty`);return n}function Cc(){let t=kh(),e;try{e=Ac.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new $e("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new $e("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new $e("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new $e("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new $e("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var Rh=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function Ph(t){return typeof t=="string"&&Rh.has(t)}function Th(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let n=e;return Ph(n.code)&&typeof n.message=="string"}var me=class extends Error{name="ControlClientError";kind;serverCode;status;body;cause;constructor(e,n,r){super(n),this.kind=e,this.serverCode=r?.serverCode,this.status=r?.status??0,this.body=r?.body,this.cause=r?.cause}},Ah="127.0.0.1",xh=1e4;function Ic(t){let e=t.host??Ah,n=t.baseTimeoutMs??xh,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new me("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new me("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof $e?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof $e?s(g):g}}function l(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function u(f,m,g,y){let v={Authorization:`Bearer ${g}`},S;return m===void 0?S=void 0:(v["Content-Type"]="application/json",S=JSON.stringify(m)),{method:f,headers:v,body:S,signal:y}}async function d(f,m,g,y,v){let S=`http://${e}:${v}${m}`,R=new AbortController,k=setTimeout(()=>{R.abort()},n);try{let G;try{G=await r(S,u(f,g,y,R.signal))}catch(oe){throw l(oe)?new me("request_timeout",`request timed out after ${n}ms`,{cause:oe}):new me("daemon_unreachable",`AIFight Bridge not running: ${oe.message}`,{cause:oe})}let Q;try{Q=await G.text()}catch(oe){throw l(oe)?new me("request_timeout",`request timed out after ${n}ms`,{cause:oe}):new me("transport_unparseable",`failed to read response body (status ${G.status})`,{status:G.status,cause:oe})}if(Q.length===0)return{status:G.status,parsedBody:void 0,parseFailed:!1};try{return{status:G.status,parsedBody:JSON.parse(Q),parseFailed:!1}}catch{return{status:G.status,parsedBody:Q,parseFailed:!0}}}finally{clearTimeout(k)}}function p(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new me("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!Th(f.parsedBody))throw new me("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new me("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function h(f,m,g){let y=a(),v=await d(f,m,g,y.token,y.port);if(v.status!==401)return p(v);let S=c();if(!S.changed)throw new me("auth_failed","token mismatch \u2014 daemon rejected the cached credentials and the token / port files have not been rotated",{status:401});t.onLog&&t.onLog({code:"rebootstrap",message:"rebootstrap reason=401"});let R=await d(f,m,g,S.token,S.port);if(R.status===401)throw new me("auth_failed","token mismatch \u2014 daemon still rejected after reread + retry",{status:401});return p(R)}return{get(f){return h("GET",f,void 0)},post(f,m){return h("POST",f,m)},delete(f){return h("DELETE",f,void 0)}}}function Oc(t,e={}){return Ic({tokenSource:xc,portSource:Cc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var he=["texas_holdem","liars_dice","coup"];function it(t){return he.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},z=class extends Error{name="CommandError";code;exitCode;hint;constructor(e,n,r={}){super(n),this.code=e,this.exitCode=r.exitCode??1,r.hint!==void 0&&(this.hint=r.hint)}};function J(t,e,n,r){let o=t.positional.length;if(o<e)throw new O(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new O(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function Zr(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
- `}import to from"node:fs";import tr from"node:path";import{fileURLToPath as Ch}from"node:url";var Nc=["./schemas","../../../protocol/schema","../../protocol/schema"],eo=null;function nr(t=Ih()){if(eo)return eo;for(let e of Nc){let n=tr.resolve(t,e);if(Mc(n)&&Mc(tr.join(n,"messages")))return eo=n,eo}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Nc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function Ih(){return tr.dirname(Ch(import.meta.url))}function Mc(t){try{return to.statSync(t).isDirectory()}catch{return!1}}var Oh={welcome:"messages/server_welcome.schema.json",queue_joined:"messages/server_queue_joined.schema.json",queue_left:"messages/server_queue_left.schema.json",match_confirm_request:"messages/server_match_confirm_request.schema.json",match_cancelled:"messages/server_match_cancelled.schema.json",game_start:"messages/server_game_start.schema.json",readiness_check:"messages/server_readiness_check.schema.json",action_request:"messages/server_action_request.schema.json",event:"messages/server_event.schema.json",game_state:"messages/server_game_state.schema.json",game_over:"messages/server_game_over.schema.json",error:"messages/server_error.schema.json",join_queue:"messages/client_join_queue.schema.json",leave_queue:"messages/client_leave_queue.schema.json",match_confirm:"messages/client_match_confirm.schema.json",action:"messages/client_action.schema.json",runtime_status:"messages/client_runtime_status.schema.json"};function hi(){return Object.keys(Oh)}function Bt(){let t=nr(),e=new Map;return jc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=to.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function jc(t,e){for(let n of to.readdirSync(t,{withFileTypes:!0})){let r=tr.join(t,n.name);n.isDirectory()?jc(r,e):n.isFile()&&e(r)}}var Lc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function pi(t){let e=Lc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Lc).join(", ")}`);let n=nr(),r=tr.join(n,e),o=to.readFileSync(r,"utf8");return JSON.parse(o)}var Sd=Ae(jo(),1),Ed=Ae(aa(),1);var Nn=class extends Error{},dt=class extends Nn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Qt=class extends Nn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},Xt=class extends Nn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var $v=3e4,Zt="/api/agents/register",kv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Mn=null;function Rv(){if(Mn)return Mn;let t=new Sd.default({strict:!1,allErrors:!0});(0,Ed.default)(t);let e=Bt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(kv);if(n)return Mn=n,Mn;let r=pi("register_response");return Mn=t.compile(r),Mn}async function ca(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??$v,r=t.baseUrl.replace(/\/+$/,"")+Zt,o=AbortSignal.timeout(n),i=t.signal?AbortSignal.any([o,t.signal]):o,s;try{s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.request),signal:i})}catch(h){if(o.aborted)throw new dt(`POST ${Zt} timed out after ${n}ms`,h);if(t.signal?.aborted)throw new dt(`POST ${Zt} aborted by caller`,h);let f=h instanceof Error?h.message:String(h);throw new dt(`POST ${Zt} failed: ${f}`,h)}let a=await s.text(),c,l=null;if(a.length>0)try{c=JSON.parse(a)}catch(h){l=h instanceof Error?h:new Error(String(h))}if(s.status!==201){let h=c&&typeof c=="object"&&c!==null&&"error"in c?c:a;throw new Qt(s.status,h,`POST ${Zt} returned HTTP ${s.status}`)}if(l!==null)throw new Xt([],`POST ${Zt} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new Xt([],`POST ${Zt} returned 201 with non-object body`);let u=Rv();if(!u(c)){let h=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new Xt(h,"register_response schema validation failed")}let p=c;return{response:p,apiKey:p.agent.api_key,claimToken:p.claim_token,agentId:p.agent.id,claimUrl:p.claim_url}}import DR from"better-sqlite3";var $d=`-- runtime/src/store/schema.sql
16
+ `+n)}function sn(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,sn),t.emit("wsClientError",s,n,e)}else qr(n,r,o,i)}});var Rc={"-v":"version","-h":"help"};function kp(t){return t.startsWith("--")?!0:Rc[t]!==void 0}function Pc(t,e){let n=[],r={},o=[],i=new Map;for(let c of e)i.set(c.name,c);let s=!1,a=0;for(;a<t.length;){let c=t[a];if(s){n.push(c),a+=1;continue}if(c==="--"){s=!0,a+=1;continue}if(c.startsWith("--")){let l=c.indexOf("="),u=l>=0?c.slice(2,l):c.slice(2),d=l>=0?c.slice(l+1):void 0,h=i.get(u);if(!h){o.push(`unknown flag: --${u}`),a+=1;continue}if(h.type==="boolean"){d===void 0||d==="true"?r[u]=!0:d==="false"?r[u]=!1:o.push(`flag --${u} expects no value (got "${d}")`),a+=1;continue}let p;if(d!==void 0)p=d,a+=1;else{let f=t[a+1];if(f===void 0||kp(f)){o.push(`flag --${u} requires a value`),a+=1;continue}p=f,a+=2}if(h.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(p)){o.push(`flag --${u} requires a number (got "${p}")`);continue}r[u]=Number(p);continue}r[u]=p;continue}if(c.startsWith("-")&&c.length>1){let l=Rc[c];if(!l){o.push(`unknown flag: ${c}`),a+=1;continue}let u=i.get(l);if(!u||u.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[l]=!0,a+=1;continue}n.push(c),a+=1}for(let c of e)c.default!==void 0&&r[c.name]===void 0&&(r[c.name]=c.default);for(let c of e)c.required&&r[c.name]===void 0&&o.push(`missing required flag: --${c.name}`);return{positional:n,flags:r,errors:o}}import Cc from"node:path";import xc from"node:fs";import Tc from"node:fs";import $p from"node:os";import Ac from"node:path";var Rp=Ac.join(".aifight","runtime");function re(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Ac.join($p.homedir(),Rp)}function st(){let t=re();if(Tc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Tc.chmodSync(t,448)}catch{}}var ke=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function Pp(){return Cc.join(re(),"token")}function Tp(){return Cc.join(re(),"port")}function Ic(){let t=Pp(),e;try{e=xc.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new ke("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new ke("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new ke("token_corrupt",t,`token file at ${t} is empty`);return n}function Oc(){let t=Tp(),e;try{e=xc.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new ke("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new ke("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new ke("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new ke("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new ke("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var Ap=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function Cp(t){return typeof t=="string"&&Ap.has(t)}function xp(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let n=e;return Cp(n.code)&&typeof n.message=="string"}var me=class extends Error{name="ControlClientError";kind;serverCode;status;body;cause;constructor(e,n,r){super(n),this.kind=e,this.serverCode=r?.serverCode,this.status=r?.status??0,this.body=r?.body,this.cause=r?.cause}},Ip="127.0.0.1",Op=1e4;function Nc(t){let e=t.host??Ip,n=t.baseTimeoutMs??Op,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new me("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new me("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof ke?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof ke?s(g):g}}function l(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function u(f,m,g,y){let v={Authorization:`Bearer ${g}`},S;return m===void 0?S=void 0:(v["Content-Type"]="application/json",S=JSON.stringify(m)),{method:f,headers:v,body:S,signal:y}}async function d(f,m,g,y,v){let S=`http://${e}:${v}${m}`,R=new AbortController,$=setTimeout(()=>{R.abort()},n);try{let z;try{z=await r(S,u(f,g,y,R.signal))}catch(ie){throw l(ie)?new me("request_timeout",`request timed out after ${n}ms`,{cause:ie}):new me("daemon_unreachable",`AIFight Bridge not running: ${ie.message}`,{cause:ie})}let Q;try{Q=await z.text()}catch(ie){throw l(ie)?new me("request_timeout",`request timed out after ${n}ms`,{cause:ie}):new me("transport_unparseable",`failed to read response body (status ${z.status})`,{status:z.status,cause:ie})}if(Q.length===0)return{status:z.status,parsedBody:void 0,parseFailed:!1};try{return{status:z.status,parsedBody:JSON.parse(Q),parseFailed:!1}}catch{return{status:z.status,parsedBody:Q,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new me("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!xp(f.parsedBody))throw new me("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new me("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function p(f,m,g){let y=a(),v=await d(f,m,g,y.token,y.port);if(v.status!==401)return h(v);let S=c();if(!S.changed)throw new me("auth_failed","token mismatch \u2014 daemon rejected the cached credentials and the token / port files have not been rotated",{status:401});t.onLog&&t.onLog({code:"rebootstrap",message:"rebootstrap reason=401"});let R=await d(f,m,g,S.token,S.port);if(R.status===401)throw new me("auth_failed","token mismatch \u2014 daemon still rejected after reread + retry",{status:401});return h(R)}return{get(f){return p("GET",f,void 0)},post(f,m){return p("POST",f,m)},delete(f){return p("DELETE",f,void 0)}}}function Mc(t,e={}){return Nc({tokenSource:Ic,portSource:Oc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var pe=["texas_holdem","liars_dice","coup"];function at(t){return pe.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},W=class extends Error{name="CommandError";code;exitCode;hint;constructor(e,n,r={}){super(n),this.code=e,this.exitCode=r.exitCode??1,r.hint!==void 0&&(this.hint=r.hint)}};function J(t,e,n,r){let o=t.positional.length;if(o<e)throw new O(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new O(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function to(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
17
+ `}import ro from"node:fs";import or from"node:path";import{fileURLToPath as Np}from"node:url";var Lc=["./schemas","../../../protocol/schema","../../protocol/schema"],no=null;function ir(t=Mp()){if(no)return no;for(let e of Lc){let n=or.resolve(t,e);if(jc(n)&&jc(or.join(n,"messages")))return no=n,no}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Lc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function Mp(){return or.dirname(Np(import.meta.url))}function jc(t){try{return ro.statSync(t).isDirectory()}catch{return!1}}var Lp={welcome:"messages/server_welcome.schema.json",queue_joined:"messages/server_queue_joined.schema.json",queue_left:"messages/server_queue_left.schema.json",match_confirm_request:"messages/server_match_confirm_request.schema.json",match_cancelled:"messages/server_match_cancelled.schema.json",game_start:"messages/server_game_start.schema.json",readiness_check:"messages/server_readiness_check.schema.json",action_request:"messages/server_action_request.schema.json",event:"messages/server_event.schema.json",game_state:"messages/server_game_state.schema.json",game_over:"messages/server_game_over.schema.json",error:"messages/server_error.schema.json",join_queue:"messages/client_join_queue.schema.json",leave_queue:"messages/client_leave_queue.schema.json",match_confirm:"messages/client_match_confirm.schema.json",action:"messages/client_action.schema.json",runtime_status:"messages/client_runtime_status.schema.json"};function yi(){return Object.keys(Lp)}function qt(){let t=ir(),e=new Map;return Fc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=ro.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function Fc(t,e){for(let n of ro.readdirSync(t,{withFileTypes:!0})){let r=or.join(t,n.name);n.isDirectory()?Fc(r,e):n.isFile()&&e(r)}}var Dc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function _i(t){let e=Dc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Dc).join(", ")}`);let n=ir(),r=or.join(n,e),o=ro.readFileSync(r,"utf8");return JSON.parse(o)}var kd=Ce(Fo(),1),$d=Ce(ua(),1);var jn=class extends Error{},mt=class extends jn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Xt=class extends jn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},Zt=class extends jn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Pv=3e4,en="/api/agents/register",Tv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Dn=null;function Av(){if(Dn)return Dn;let t=new kd.default({strict:!1,allErrors:!0});(0,$d.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Tv);if(n)return Dn=n,Dn;let r=_i("register_response");return Dn=t.compile(r),Dn}async function da(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Pv,r=t.baseUrl.replace(/\/+$/,"")+en,o=AbortSignal.timeout(n),i=t.signal?AbortSignal.any([o,t.signal]):o,s;try{s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.request),signal:i})}catch(p){if(o.aborted)throw new mt(`POST ${en} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new mt(`POST ${en} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new mt(`POST ${en} failed: ${f}`,p)}let a=await s.text(),c,l=null;if(a.length>0)try{c=JSON.parse(a)}catch(p){l=p instanceof Error?p:new Error(String(p))}if(s.status!==201){let p=c&&typeof c=="object"&&c!==null&&"error"in c?c:a;throw new Xt(s.status,p,`POST ${en} returned HTTP ${s.status}`)}if(l!==null)throw new Zt([],`POST ${en} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new Zt([],`POST ${en} returned 201 with non-object body`);let u=Av();if(!u(c)){let p=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new Zt(p,"register_response schema validation failed")}let h=c;return{response:h,apiKey:h.agent.api_key,claimToken:h.claim_token,agentId:h.agent.id,claimUrl:h.claim_url}}import KR from"better-sqlite3";var Rd=`-- runtime/src/store/schema.sql
18
18
  -- AUTO-APPLIED by src/store/sqlite.ts as the v1 migration step.
19
19
  -- DO NOT edit this file by hand \u2014 this is v1's BYTE SOURCE (bundled
20
20
  -- into SCHEMA_SQL_V1 by bundle-schema.mjs). M1-05 appended a v2
@@ -49,7 +49,7 @@ CREATE TABLE IF NOT EXISTS agents (
49
49
  );
50
50
 
51
51
  CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
52
- `;var kd=[{version:1,up:t=>{t.exec($d)}},{version:2,up:t=>{let e=t.prepare("SELECT COUNT(*) AS n FROM agents").get().n;if(e>0)throw new Error(`M1-05 migration refuses to upgrade a populated agents table (${e} rows). These rows were written in schema v1 with TEXT plaintext columns and cannot be silently reinterpreted as encrypted BLOBs. Remediation: back up the DB file, then DELETE FROM agents, then re-open to trigger migration. For a real re-encrypt migration, open a new TED.`);t.exec(`
52
+ `;var Pd=[{version:1,up:t=>{t.exec(Rd)}},{version:2,up:t=>{let e=t.prepare("SELECT COUNT(*) AS n FROM agents").get().n;if(e>0)throw new Error(`M1-05 migration refuses to upgrade a populated agents table (${e} rows). These rows were written in schema v1 with TEXT plaintext columns and cannot be silently reinterpreted as encrypted BLOBs. Remediation: back up the DB file, then DELETE FROM agents, then re-open to trigger migration. For a real re-encrypt migration, open a new TED.`);t.exec(`
53
53
  CREATE TABLE agents_new (
54
54
  id TEXT NOT NULL PRIMARY KEY,
55
55
  name TEXT NOT NULL UNIQUE,
@@ -64,174 +64,195 @@ CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
64
64
  ALTER TABLE agents_new RENAME TO agents;
65
65
  DROP INDEX IF EXISTS idx_agents_name;
66
66
  CREATE INDEX idx_agents_name ON agents(name);
67
- `)}}],UR=kd[kd.length-1].version;import{Entry as VR}from"@napi-rs/keyring";var Rd="AIFIGHT_KEYCHAIN_V1:",Pd="AIFIGHT_CRYPTO_V1:";var KR=Buffer.byteLength(Rd,"ascii"),JR=Buffer.byteLength(Pd,"ascii");var eS=Ae(Ef(),1),tS=Ae(zo(),1),nS=Ae(Dn(),1),rS=Ae(wa(),1),oS=Ae(Sa(),1),iS=Ae(Ta(),1),xa=Ae(Qo(),1),sS=Ae(Cf(),1);var fe=class extends Error{},It=class extends fe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Ot=class extends fe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},sn=class extends fe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Nt=class extends fe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},an=class extends fe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},cn=class extends fe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends fe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},tt=class extends fe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},gt=class extends fe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},yt=class extends fe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var If=Ae(jo(),1),Of=Ae(aa(),1);var Ia=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Oa=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Nf="https://aifight.ai/protocol/v1/messages/";function aS(t){return`${Nf}client_${t}.schema.json`}function cS(t){return`${Nf}server_${t}.schema.json`}var Ca=null;function Mf(){if(Ca)return Ca;let t=new If.default({strict:!1,allErrors:!0});(0,Of.default)(t);for(let[e,n]of Bt())t.getSchema(e)||t.addSchema(n,e);return Ca=t,t}function Lf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function jf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Df(t){if(!jf(t))throw new tt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new tt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Oa.has(e))throw new tt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Ia.has(e))throw new tt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Ia].join(", ")})`);let n=Mf(),r=aS(e),o=n.getSchema(r);if(!o)throw new tt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new tt(e,Lf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function Na(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!jf(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!Oa.has(r))throw Ia.has(r)?new gt(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new gt(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Oa].join(", ")})`);let o=Mf(),i=cS(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,Lf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var lS=1e4,uS=25e3;function Ff(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var Ma=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??uS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=Na(n)}catch(o){if(o instanceof Re||o instanceof gt)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#p(r)}#p(e){let n=[...this.#a];for(let r of n)this.#h(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#h(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#h(()=>r(e))}#h(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new cn(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Df(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function La(t){let e=t.welcomeTimeoutMs??lS;return t.signal?.aborted?Promise.reject(new yt(`createWSClient aborted before start: ${Ff(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new xa.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new It(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new yt(`createWSClient aborted during handshake: ${Ff(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new It(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let p="";d.setEncoding("utf8"),d.on("data",h=>{p+=h}),d.on("end",()=>{let h=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Ot(h,p,`HTTP upgrade rejected: ${h} ${f}`.trim())))}),d.on("error",h=>{let f=d.statusCode??0;l(()=>r(new Ot(f,p,`HTTP upgrade response read failed: ${h.message}`,h)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new sn(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),p;try{p=Na(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof gt?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Nt(S,R))});return}if(p.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Nt([],`expected first frame to be 'welcome', got '${p.type}'`))});return}let h=p,f=h.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new an(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Ma(o,h,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var Wn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},dS=1e3,fS=2,mS=3e4,hS="full",pS=5*60*1e3,gS=15*60*1e3,yS=new Set([1001,1006,1011,1012]);function _S(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function wS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function vS(t){return t.code>=4e3&&t.code<5e3?!1:yS.has(t.code)}function bS(t){if(t instanceof yt||t instanceof Nt||t instanceof an)return!1;if(t instanceof It||t instanceof sn)return!0;if(t instanceof Ot){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function SS(t){return t>=gS?"error":t>=pS?"warning":"info"}var ja=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#p=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new cn(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#p&&this.#p("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await La({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!vS(l)){let u=new Wn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof fe&&(e=a),!bS(a)){let c=a instanceof fe?a:void 0,l=a instanceof yt?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=_S(this.#u,this.#e.initialBackoffMs??dS,this.#e.backoffFactor??fS,this.#e.maxBackoffMs??mS),o=wS(r,this.#e.jitter??hS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#h(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new Wn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#h(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#p=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#p=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?SS(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new Wn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function Da(t){let e=new ja(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var ES=["check","call","fold","raise","allin"];function Fa(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of ES){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function qa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=$S(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=kS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function $S(t){let e=RS(t);if(!e)return;let n=Ba(e,"min_quantity"),r=Ba(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Ba(e,"max_quantity")}}function kS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function RS(t){return t!==null&&typeof t=="object"?t:void 0}function Ba(t,e){let n=t[e];return typeof n=="number"?n:void 0}var PS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],TS=["pass","challenge"],AS=["pass","block"],xS=["lose_card"],CS=["return_cards"];function Ua(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return Fr(n,PS);case"challenge_action":case"challenge_block":return Fr(n,TS);case"block":return Fr(n,AS);case"lose_influence":return Fr(n,xS);case"exchange_return":return Fr(n,CS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Fr(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var IS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Wa(t,e,n=500){let r=t.trim(),o=MS(r),i;try{i=JSON.parse(o)}catch{return ln("json_parse",r,n)}if(!Zo(i))return ln("missing_fields",r,n);let s=i.action;if(typeof s!="string")return ln("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Zo(c))return ln("missing_fields",r,n);let l=Zo(c)?c:void 0;if(!OS.has(s))return ln("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return ln("action_not_legal",r,n);if(s==="raise"){let d=NS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:ln("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var OS=new Set(["fold","check","call","raise","allin"]);function NS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=Zo(t.data)?t.data:void 0,o=Ha(r,"amount"),i=Ha(r,"min")??o,s=Ha(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function MS(t){let e=t.match(IS);return e?e[1].trim():t}function Zo(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ha(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ln(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var LS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ga(t,e,n=500){let r=t.trim(),o=FS(r),i;try{i=JSON.parse(o)}catch{return un("json_parse",r,n)}if(!ei(i))return un("missing_fields",r,n);let s=i.action;if(typeof s!="string")return un("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ei(c))return un("missing_fields",r,n);let l=ei(c)?c:void 0;if(!jS.has(s))return un("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return un("action_not_legal",r,n);if(s==="bid"){let d=DS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:un("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var jS=new Set(["bid","challenge"]);function DS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ei(t.data)?t.data:void 0,i=Va(o,"min_quantity"),s=Va(o,"min_face"),a=Va(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function FS(t){let e=t.match(LS);return e?e[1].trim():t}function ei(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Va(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function un(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var BS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,qS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function za(t,e,n=500){let r=t.trim(),o=HS(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!Vn(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Vn(c))return dn("missing_fields",r,n);let l=Vn(c)?c:void 0;if(!qS.has(s))return dn("unknown_action_type",r,n);let u=e.filter(p=>p.type===s);if(u.length===0)return dn("action_not_legal",r,n);let d=US(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}function US(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Bf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Bf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>WS(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=VS(o.data,"return_indices");return i!==void 0&&GS(i,r)})}default:return e[0]}}function HS(t){let e=t.match(BS);return e?e[1].trim():t}function Vn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Bf(t,e){if(!Vn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function WS(t,e){if(!Vn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function VS(t,e){if(!Vn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function GS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var Se="0.1.0-alpha.1",zf="v1.0.0";function Kf(){let t=nr(),e=Bt(),n=hi();return{ok:!0,runtimeVersion:Se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Ka(t,e){return J(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:Se})+`
67
+ `)}}],XR=Pd[Pd.length-1].version;import{Entry as tP}from"@napi-rs/keyring";var Td="AIFIGHT_KEYCHAIN_V1:",Ad="AIFIGHT_CRYPTO_V1:";var oP=Buffer.byteLength(Td,"ascii"),iP=Buffer.byteLength(Ad,"ascii");var rS=Ce($f(),1),oS=Ce(Jo(),1),iS=Ce(qn(),1),sS=Ce(Sa(),1),aS=Ce($a(),1),cS=Ce(xa(),1),Oa=Ce(Zo(),1),lS=Ce(Of(),1);var fe=class extends Error{},It=class extends fe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Ot=class extends fe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},an=class extends fe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Nt=class extends fe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},cn=class extends fe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},ln=class extends fe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends fe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},nt=class extends fe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},_t=class extends fe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},wt=class extends fe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var Nf=Ce(Fo(),1),Mf=Ce(ua(),1);var Ma=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),La=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Lf="https://aifight.ai/protocol/v1/messages/";function uS(t){return`${Lf}client_${t}.schema.json`}function dS(t){return`${Lf}server_${t}.schema.json`}var Na=null;function jf(){if(Na)return Na;let t=new Nf.default({strict:!1,allErrors:!0});(0,Mf.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Na=t,t}function Df(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function Ff(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Bf(t){if(!Ff(t))throw new nt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new nt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(La.has(e))throw new nt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Ma.has(e))throw new nt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Ma].join(", ")})`);let n=jf(),r=uS(e),o=n.getSchema(r);if(!o)throw new nt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new nt(e,Df(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function ja(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!Ff(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!La.has(r))throw Ma.has(r)?new _t(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new _t(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...La].join(", ")})`);let o=jf(),i=dS(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,Df(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var fS=1e4,mS=25e3;function qf(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var Da=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??mS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=ja(n)}catch(o){if(o instanceof Re||o instanceof _t)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#h(r)}#h(e){let n=[...this.#a];for(let r of n)this.#p(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#p(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#p(()=>r(e))}#p(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new ln(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Bf(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function Fa(t){let e=t.welcomeTimeoutMs??fS;return t.signal?.aborted?Promise.reject(new wt(`createWSClient aborted before start: ${qf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new Oa.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new It(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new wt(`createWSClient aborted during handshake: ${qf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new It(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Ot(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Ot(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new an(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),h;try{h=ja(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof _t?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Nt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Nt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new cn(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Da(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var zn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},pS=1e3,hS=2,gS=3e4,yS="full",_S=5*60*1e3,wS=15*60*1e3,vS=new Set([1001,1006,1011,1012]);function bS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function SS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function ES(t){return t.code>=4e3&&t.code<5e3?!1:vS.has(t.code)}function kS(t){if(t instanceof wt||t instanceof Nt||t instanceof cn)return!1;if(t instanceof It||t instanceof an)return!0;if(t instanceof Ot){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function $S(t){return t>=wS?"error":t>=_S?"warning":"info"}var Ba=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#h=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new ln(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#h&&this.#h("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await Fa({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!ES(l)){let u=new zn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof fe&&(e=a),!kS(a)){let c=a instanceof fe?a:void 0,l=a instanceof wt?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=bS(this.#u,this.#e.initialBackoffMs??pS,this.#e.backoffFactor??hS,this.#e.maxBackoffMs??gS),o=SS(r,this.#e.jitter??yS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#p(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new zn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#p(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#h=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#h=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?$S(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new zn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function qa(t){let e=new Ba(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var RS=["check","call","fold","raise","allin"];function Ua(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of RS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Ga(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=PS(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=TS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function PS(t){let e=AS(t);if(!e)return;let n=Ha(e,"min_quantity"),r=Ha(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Ha(e,"max_quantity")}}function TS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function AS(t){return t!==null&&typeof t=="object"?t:void 0}function Ha(t,e){let n=t[e];return typeof n=="number"?n:void 0}var CS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],xS=["pass","challenge"],IS=["pass","block"],OS=["lose_card"],NS=["return_cards"];function Wa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return Ur(n,CS);case"challenge_action":case"challenge_block":return Ur(n,xS);case"block":return Ur(n,IS);case"lose_influence":return Ur(n,OS);case"exchange_return":return Ur(n,NS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Ur(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var MS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function za(t,e,n=500){let r=t.trim(),o=DS(r),i;try{i=JSON.parse(o)}catch{return un("json_parse",r,n)}if(!ti(i))return un("missing_fields",r,n);let s=i.action;if(typeof s!="string")return un("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ti(c))return un("missing_fields",r,n);let l=ti(c)?c:void 0;if(!LS.has(s))return un("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return un("action_not_legal",r,n);if(s==="raise"){let d=jS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:un("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var LS=new Set(["fold","check","call","raise","allin"]);function jS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ti(t.data)?t.data:void 0,o=Va(r,"amount"),i=Va(r,"min")??o,s=Va(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function DS(t){let e=t.match(MS);return e?e[1].trim():t}function ti(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Va(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function un(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var FS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=US(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!ni(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ni(c))return dn("missing_fields",r,n);let l=ni(c)?c:void 0;if(!BS.has(s))return dn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return dn("action_not_legal",r,n);if(s==="bid"){let d=qS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var BS=new Set(["bid","challenge"]);function qS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ni(t.data)?t.data:void 0,i=Ka(o,"min_quantity"),s=Ka(o,"min_face"),a=Ka(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function US(t){let e=t.match(FS);return e?e[1].trim():t}function ni(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ka(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var HS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,GS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Ya(t,e,n=500){let r=t.trim(),o=VS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!Kn(i))return fn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return fn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return fn("missing_fields",r,n);let l=Kn(c)?c:void 0;if(!GS.has(s))return fn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return fn("action_not_legal",r,n);let d=WS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}function WS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>zS(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=KS(o.data,"return_indices");return i!==void 0&&JS(i,r)})}default:return e[0]}}function VS(t){let e=t.match(HS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function zS(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function KS(t,e){if(!Kn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function JS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var Se="0.1.0-alpha.3",Jf="v1.0.0";function Yf(){let t=ir(),e=qt(),n=yi();return{ok:!0,runtimeVersion:Se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Qa(t,e){return J(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:Se})+`
68
68
  `):e.stdout(`${Se}
69
- `),0}import Br from"node:fs";import JS from"node:path";var Ue=class extends Error{name="RuntimeLocalUrlError"};function ti(t){switch(t){case"openclaw":return"http://127.0.0.1:18789";case"hermes":return"http://127.0.0.1:8642";case"mock":return"mock://local"}}function qr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new Ue("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Ue("runtime URL must use http:// or https://");if(!ZS(r.hostname))throw new Ue("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new Ue("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new Ue("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Gn(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function Ya(){return JS.join(ne(),"bridge.json")}function Jf(){Br.rmSync(Ya(),{force:!0})}function fn(t){ot();let e=Ya(),n=`${e}.tmp`;if(Br.writeFileSync(n,JSON.stringify(t,null,2)+`
70
- `,{mode:384}),Br.renameSync(n,e),process.platform!=="win32")try{Br.chmodSync(e,384)}catch{}}function ae(){let t=Ya(),e;try{e=Br.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new Error("bridge is not configured; run `aifight register` for a new agent or `aifight connect <PAIRING_CODE>` for an existing agent"):r}let n=JSON.parse(e);if(!QS(n))throw new Error("bridge config is invalid; run connect again");return n}function Mt(t){return{...t,apiKey:Ja(t.apiKey),...t.claimUrl!==void 0?{claimUrl:YS(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:Ja(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:Ja(t.runtimeLocalToken)}:{}}}function Ja(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function YS(t){try{let e=new URL(t),n=e.pathname.split("/"),r=n.at(-1);return r&&r.length>0&&(n[n.length-1]="<redacted>",e.pathname=n.join("/")),e.toString()}catch{return"<redacted>"}}function QS(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.baseUrl=="string"&&typeof e.wsUrl=="string"&&typeof e.agentId=="string"&&typeof e.agentName=="string"&&(e.suggestedName===void 0||typeof e.suggestedName=="string")&&typeof e.apiKey=="string"&&(e.claimUrl===void 0||typeof e.claimUrl=="string")&&(e.claimToken===void 0||typeof e.claimToken=="string")&&(e.runtimeType==="openclaw"||e.runtimeType==="hermes"||e.runtimeType==="mock")&&typeof e.runtimeLocalUrl=="string"&&XS(e.runtimeLocalUrl,e.runtimeType)&&typeof e.updatedAt=="string"&&(e.runtimeLocalToken===void 0||typeof e.runtimeLocalToken=="string")&&(e.runtimeModel===void 0||typeof e.runtimeModel=="string")&&(e.autoDailyLimit===void 0||typeof e.autoDailyLimit=="number"&&Number.isInteger(e.autoDailyLimit)&&e.autoDailyLimit>=0)&&(e.autoGames===void 0||Array.isArray(e.autoGames)&&e.autoGames.every(n=>typeof n=="string"))}function XS(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return qr(t,e),!0}catch{return!1}}function ZS(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var e0="npm install -g @aifight/aifight@alpha";async function Lt(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${n0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return Qa(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=r0(s);return a===null?Qa(t.currentVersion,"version check returned invalid policy"):t0(t.currentVersion,a)}catch(i){let s=i?.name;return Qa(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function t0(t,e){let n=Yf(t,e.minimumSupportedVersion);if(n!==null&&n<0)return{status:"unsupported",currentVersion:t,policy:e,message:`Bridge ${t} is below the minimum supported version ${e.minimumSupportedVersion}. Update before joining matches.`};let r=Yf(t,e.recommendedVersion);return r!==null&&r<0?{status:"update_recommended",currentVersion:t,policy:e,message:`Bridge ${t} works, but ${e.recommendedVersion} is recommended.`}:n===null||r===null?{status:"unknown",currentVersion:t,policy:e,message:"Bridge version could not be compared with the platform policy."}:{status:"current",currentVersion:t,policy:e,message:`Bridge ${t} is current enough for AIFight.`}}function Qa(t,e){return{status:"unknown",currentVersion:t,message:e}}function n0(t){return t.replace(/\/+$/,"")}function r0(t){if(!t||typeof t!="object")return null;let e=t,n=e.minimum_supported_version,r=e.recommended_version,o=e.latest_version;return typeof n!="string"||typeof r!="string"||typeof o!="string"?null:{minimumSupportedVersion:n,recommendedVersion:r,latestVersion:o,updateCommand:typeof e.update_command=="string"&&e.update_command.trim()!==""?e.update_command:e0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function Yf(t,e){let n=Qf(t),r=Qf(e);if(n===null||r===null)return null;for(let o of["major","minor","patch"])if(n[o]!==r[o])return n[o]>r[o]?1:-1;return o0(n.prerelease,r.prerelease)}function Qf(t){let e=t.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return e===null?null:{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]===void 0?[]:e[4].split(".")}}function o0(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;let n=Math.max(t.length,e.length);for(let r=0;r<n;r++){let o=t[r],i=e[r];if(o===void 0)return-1;if(i===void 0)return 1;if(o===i)continue;let s=/^\d+$/.test(o)?Number.parseInt(o,10):null,a=/^\d+$/.test(i)?Number.parseInt(i,10):null;return s!==null&&a!==null?s>a?1:-1:s!==null?-1:a!==null||o>i?1:-1}return 0}var i0=1500;async function Xf(t,e){J(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Kf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
69
+ `),0}import Hr from"node:fs";import XS from"node:path";var He=class extends Error{name="RuntimeLocalUrlError"};function Jn(t){switch(t){case"openclaw":return"http://127.0.0.1:18789";case"hermes":return"http://127.0.0.1:8642";case"mock":return"mock://local"}}function Gr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new He("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new He("runtime URL must use http:// or https://");if(!n0(r.hostname))throw new He("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new He("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new He("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Mt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function Za(){return XS.join(re(),"bridge.json")}function Qf(){Hr.rmSync(Za(),{force:!0})}function mn(t){st();let e=Za(),n=`${e}.tmp`;if(Hr.writeFileSync(n,JSON.stringify(t,null,2)+`
70
+ `,{mode:384}),Hr.renameSync(n,e),process.platform!=="win32")try{Hr.chmodSync(e,384)}catch{}}function ce(){let t=Za(),e;try{e=Hr.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new Error("bridge is not configured; run `aifight register` for a new agent or `aifight connect <PAIRING_CODE>` for an existing agent"):r}let n=JSON.parse(e);if(!e0(n))throw new Error("bridge config is invalid; run connect again");return n}function Lt(t){return{...t,apiKey:Xa(t.apiKey),...t.claimUrl!==void 0?{claimUrl:ZS(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:Xa(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:Xa(t.runtimeLocalToken)}:{}}}function Xa(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function ZS(t){try{let e=new URL(t),n=e.pathname.split("/"),r=n.at(-1);return r&&r.length>0&&(n[n.length-1]="<redacted>",e.pathname=n.join("/")),e.toString()}catch{return"<redacted>"}}function e0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.baseUrl=="string"&&typeof e.wsUrl=="string"&&typeof e.agentId=="string"&&typeof e.agentName=="string"&&(e.suggestedName===void 0||typeof e.suggestedName=="string")&&typeof e.apiKey=="string"&&(e.claimUrl===void 0||typeof e.claimUrl=="string")&&(e.claimToken===void 0||typeof e.claimToken=="string")&&(e.runtimeType==="openclaw"||e.runtimeType==="hermes"||e.runtimeType==="mock")&&typeof e.runtimeLocalUrl=="string"&&t0(e.runtimeLocalUrl,e.runtimeType)&&typeof e.updatedAt=="string"&&(e.runtimeLocalToken===void 0||typeof e.runtimeLocalToken=="string")&&(e.runtimeModel===void 0||typeof e.runtimeModel=="string")&&(e.autoDailyLimit===void 0||typeof e.autoDailyLimit=="number"&&Number.isInteger(e.autoDailyLimit)&&e.autoDailyLimit>=0)&&(e.autoGames===void 0||Array.isArray(e.autoGames)&&e.autoGames.every(n=>typeof n=="string"))}function t0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Gr(t,e),!0}catch{return!1}}function n0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var r0="npm install -g @aifight/aifight@alpha";async function jt(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${i0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return ec(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=s0(s);return a===null?ec(t.currentVersion,"version check returned invalid policy"):o0(t.currentVersion,a)}catch(i){let s=i?.name;return ec(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function o0(t,e){let n=Xf(t,e.minimumSupportedVersion);if(n!==null&&n<0)return{status:"unsupported",currentVersion:t,policy:e,message:`Bridge ${t} is below the minimum supported version ${e.minimumSupportedVersion}. Update before joining matches.`};let r=Xf(t,e.recommendedVersion);return r!==null&&r<0?{status:"update_recommended",currentVersion:t,policy:e,message:`Bridge ${t} works, but ${e.recommendedVersion} is recommended.`}:n===null||r===null?{status:"unknown",currentVersion:t,policy:e,message:"Bridge version could not be compared with the platform policy."}:{status:"current",currentVersion:t,policy:e,message:`Bridge ${t} is current enough for AIFight.`}}function ec(t,e){return{status:"unknown",currentVersion:t,message:e}}function i0(t){return t.replace(/\/+$/,"")}function s0(t){if(!t||typeof t!="object")return null;let e=t,n=e.minimum_supported_version,r=e.recommended_version,o=e.latest_version;return typeof n!="string"||typeof r!="string"||typeof o!="string"?null:{minimumSupportedVersion:n,recommendedVersion:r,latestVersion:o,updateCommand:typeof e.update_command=="string"&&e.update_command.trim()!==""?e.update_command:r0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function Xf(t,e){let n=Zf(t),r=Zf(e);if(n===null||r===null)return null;for(let o of["major","minor","patch"])if(n[o]!==r[o])return n[o]>r[o]?1:-1;return a0(n.prerelease,r.prerelease)}function Zf(t){let e=t.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return e===null?null:{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]===void 0?[]:e[4].split(".")}}function a0(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;let n=Math.max(t.length,e.length);for(let r=0;r<n;r++){let o=t[r],i=e[r];if(o===void 0)return-1;if(i===void 0)return 1;if(o===i)continue;let s=/^\d+$/.test(o)?Number.parseInt(o,10):null,a=/^\d+$/.test(i)?Number.parseInt(i,10):null;return s!==null&&a!==null?s>a?1:-1:s!==null?-1:a!==null||o>i?1:-1}return 0}var c0=1500;async function em(t,e){J(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Yf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
71
71
  `):e.stderr(`aifight doctor FAILED: ${i.message}
72
- `),1}let r=await s0(n.runtimeVersion,e.fetchImpl??globalThis.fetch);if(t.jsonMode)return e.stdout(JSON.stringify({runtimeVersion:n.runtimeVersion,messageTypeCount:n.messageTypeCount,schemaCount:n.schemaCount,schemasRoot:n.schemasRoot,node:process.versions.node,platform:`${process.platform}-${process.arch}`,bridge:r})+`
72
+ `),1}let r=await l0(n.runtimeVersion,e.fetchImpl??globalThis.fetch);if(t.jsonMode)return e.stdout(JSON.stringify({runtimeVersion:n.runtimeVersion,messageTypeCount:n.messageTypeCount,schemaCount:n.schemaCount,schemasRoot:n.schemasRoot,node:process.versions.node,platform:`${process.platform}-${process.arch}`,bridge:r})+`
73
73
  `),0;let o=[];return o.push("aifight doctor:"),o.push(` version : ${n.runtimeVersion}`),o.push(` node : ${process.versions.node}`),o.push(` platform : ${process.platform}-${process.arch}`),o.push(` bridge config : ${r.config}`),r.runtime!==void 0&&o.push(` runtime probe : ${r.runtime.status}${r.runtime.detail?` (${r.runtime.detail})`:""}`),r.update!==void 0&&(o.push(` version policy : ${r.update.message}`),(r.update.status==="update_recommended"||r.update.status==="unsupported")&&o.push(` update command : ${r.update.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}`)),o.push(""),e.stdout(o.join(`
74
- `)),0}async function s0(t,e){try{let n=ae(),r=await Lt({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Mt(n),runtime:await a0(n,e),update:r}}catch(n){let r=n.message;return r.includes("bridge is not configured")?{config:"not configured"}:{config:`invalid (${r})`}}}async function a0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??Gn(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),i0);try{let s=await e(`${n}/v1/responses`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",...t.runtimeLocalToken?{Authorization:`Bearer ${t.runtimeLocalToken}`}:{}},body:JSON.stringify({model:r,input:'AIFight doctor health check. Return only JSON: {"action":"pass"}'})}),a=c0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${l0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function c0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function l0(t,e){return t==="openclaw"?e===404?"enable OpenClaw responses endpoint: openclaw config set gateway.http.endpoints.responses.enabled true --strict-json, then let Gateway restart or run openclaw gateway restart --safe":e===401||e===403?"check the local OpenClaw Gateway token passed with --runtime-token":"check OpenClaw Gateway logs and local model/provider config":t==="hermes"?e===401||e===403?"check Hermes API_SERVER_KEY and the local --runtime-token value":e===404?"confirm Hermes API Server is enabled in ~/.hermes/.env and restart Hermes; it does not hot-reload API_SERVER_*":"check Hermes API Server logs and local model/provider config":"check local runtime config"}import H0 from"node:os";import{randomBytes as W0}from"node:crypto";import{execFile as u0}from"node:child_process";import Pe from"node:fs";import Xa from"node:os";import _t from"node:path";import{promisify as d0}from"node:util";var jt="aifight.service",ni="ai.aifight.service",ce=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},f0=d0(u0),He=async(t,e)=>{try{let{stdout:n,stderr:r}=await f0(t,[...e],{timeout:5e3,maxBuffer:131072});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}}catch(n){throw n}};async function Za(t={}){let e=await Jn(t),n=t.execFile??He;m0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",nt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",nt(t),e.unitPath]);let o=await ec(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=mn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",jt]),e.platform==="linux-systemd-user"){let o=await g0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await y0(e,t),new ce("service_install_failed",`failed to install ${jt}: ${zn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function ri(t={}){let e=await Jn(t),n=t.execFile??He;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",nt(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=mn(e.platform);return await n("systemctl",[...r,"disable","--now",jt]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function nm(t={}){let e=await Jn(t),n=t.execFile??He;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",nt(t),e.unitPath]).catch(()=>{}),await ec(t),e):(await n("systemctl",[...mn(e.platform),"start",jt]),e)}async function rm(t={}){let e=await Jn(t),n=t.execFile??He;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",nt(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...mn(e.platform),"stop",jt]),e)}async function om(t={}){let e=await Jn(t),n=t.execFile??He;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",nt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",nt(t),e.unitPath]),await ec(t),e):(await n("systemctl",[...mn(e.platform),"restart",jt]),e)}async function Kn(t={}){let e=await Jn(t),n=t.execFile??He;if(!Pe.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${nt(t)}/${ni}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:zn(o)}}try{let i=(await n("systemctl",[...mn(e.platform),"is-active",jt])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:zn(o)}}}async function Jn(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??Xa.homedir(),o=t.runtimeHome??ne(),i=await _0(t),s=w0(t);if(e==="linux")return await Zf("systemctl",["--version"],t),n===0?{platform:"linux-systemd-system",unitPath:t.systemdSystemUnitPath??"/etc/systemd/system/aifight.service",nodeExec:s,aifightExec:i,runtimeHome:o}:{platform:"linux-systemd-user",unitPath:t.systemdUserUnitPath??_t.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await Zf("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??_t.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new ce("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function m0(t){Pe.mkdirSync(_t.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?p0(t):h0(t);b0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function h0(t){let e=t.platform==="linux-systemd-system"?"multi-user.target":"default.target";return["# Auto-generated by AIFight. Re-run `aifight service install` to refresh.","","[Unit]","Description=AIFight Agent Service","Documentation=https://aifight.ai/skill.md","Wants=network-online.target","After=network-online.target","","[Service]","Type=simple",`ExecStart=${em(t.nodeExec)} ${em(t.aifightExec)} run`,tm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),tm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
- `)}function p0(t){let e=_t.dirname(t.unitPath).includes("LaunchAgents")?_t.join(Xa.homedir(),"Library","Logs","aifight"):_t.join(_t.dirname(t.unitPath),"logs");return Pe.mkdirSync(e,{recursive:!0}),['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${ni}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Ur(t.nodeExec)}</string>`,` <string>${Ur(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Ur(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Ur(_t.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Ur(_t.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
- `)}function mn(t){return t==="linux-systemd-user"?["--user"]:[]}function nt(t){return`gui/${t.uid??process.getuid?.()??0}`}async function ec(t){let e=t.execFile??He,n=`${nt(t)}/${ni}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${ni} is loaded: ${zn(r)}`}catch{throw r}}}async function g0(t){let e=t.username??Xa.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??He;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${zn(r)}`}}}async function y0(t,e){let n=e.execFile??He;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",nt(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=mn(t.platform);await n("systemctl",[...r,"disable","--now",jt]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function _0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Hr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!v0(n))try{return Hr(n)}catch{}let r=t.execFile??He;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
- `)[0];if(i)return Hr(i)}catch{}throw new ce("service_exec_unresolved","could not resolve a stable `aifight` executable for the background service","Install with `npm install -g @aifight/aifight@alpha`, then run `aifight service install` again.")}function w0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Hr(e);try{return Hr(process.execPath)}catch{throw new ce("service_exec_unresolved","could not resolve a stable Node.js executable for the background service","Install Node.js >=20.19 and rerun `aifight service install`.")}}function Hr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function v0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function Zf(t,e,n){let r=n.execFile??He;try{await r(t,e)}catch(o){throw new ce("service_manager_unavailable",`${t} is not available or not usable on this system: ${zn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function em(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function tm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function b0(t,e,n){let r=`${t}.${process.pid}.tmp`;Pe.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Pe.chmodSync(r,n),Pe.renameSync(r,t)}function zn(t){let e=t,n=typeof e.stderr=="string"&&e.stderr.trim()!==""?e.stderr:e.message;return String(n).trim().split(`
78
- `)[0]??"unknown error"}function Ur(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var tc=["usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
79
- `);async function im(t,e){J(t,1,1,tc);let n=t.positional[0],r=S0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",tc);try{switch(n){case"install":{ae();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await Za(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
74
+ `)),0}async function l0(t,e){try{let n=ce(),r=await jt({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Lt(n),runtime:await u0(n,e),update:r}}catch(n){let r=n.message;return r.includes("bridge is not configured")?{config:"not configured"}:{config:`invalid (${r})`}}}async function u0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??Mt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),c0);try{let s=await e(`${n}/v1/responses`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",...t.runtimeLocalToken?{Authorization:`Bearer ${t.runtimeLocalToken}`}:{}},body:JSON.stringify({model:r,input:'AIFight doctor health check. Return only JSON: {"action":"pass"}'})}),a=d0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${f0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function d0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function f0(t,e){return t==="openclaw"?e===404?"enable OpenClaw responses endpoint: openclaw config set gateway.http.endpoints.responses.enabled true --strict-json, then let Gateway restart or run openclaw gateway restart --safe":e===401||e===403?"check the local OpenClaw Gateway token passed with --runtime-token":"check OpenClaw Gateway logs and local model/provider config":t==="hermes"?e===401||e===403?"check Hermes API_SERVER_KEY and the local --runtime-token value":e===404?"confirm Hermes API Server is enabled in ~/.hermes/.env and restart Hermes; it does not hot-reload API_SERVER_*":"check Hermes API Server logs and local model/provider config":"check local runtime config"}import K0 from"node:os";import{randomBytes as J0}from"node:crypto";import{execFile as m0}from"node:child_process";import Pe from"node:fs";import tc from"node:os";import vt from"node:path";import{promisify as p0}from"node:util";var Dt="aifight.service",ri="ai.aifight.service",te=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},h0=p0(m0),Ge=async(t,e)=>{try{let{stdout:n,stderr:r}=await h0(t,[...e],{timeout:5e3,maxBuffer:131072});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}}catch(n){throw n}};async function nc(t={}){let e=await Qn(t),n=t.execFile??Ge;g0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]);let o=await oc(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=hn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",Dt]),e.platform==="linux-systemd-user"){let o=await w0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await v0(e,t),new te("service_install_failed",`failed to install ${Dt}: ${Yn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function oi(t={}){let e=await Qn(t),n=t.execFile??Ge;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=hn(e.platform);return await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function om(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",rt(t),e.unitPath]).catch(()=>{}),await oc(t),e):(await n("systemctl",[...hn(e.platform),"start",Dt]),e)}async function im(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...hn(e.platform),"stop",Dt]),e)}async function rc(t={}){let e=await Qn(t),n=t.execFile??Ge;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",rt(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",rt(t),e.unitPath]),await oc(t),e):(await n("systemctl",[...hn(e.platform),"restart",Dt]),e)}async function pn(t={}){let e=await Qn(t),n=t.execFile??Ge;if(!Pe.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${rt(t)}/${ri}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}try{let i=(await n("systemctl",[...hn(e.platform),"is-active",Dt])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}}async function Qn(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??tc.homedir(),o=t.runtimeHome??re(),i=await b0(t),s=S0(t);if(e==="linux")return await tm("systemctl",["--version"],t),n===0?{platform:"linux-systemd-system",unitPath:t.systemdSystemUnitPath??"/etc/systemd/system/aifight.service",nodeExec:s,aifightExec:i,runtimeHome:o}:{platform:"linux-systemd-user",unitPath:t.systemdUserUnitPath??vt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await tm("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??vt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new te("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function g0(t){Pe.mkdirSync(vt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?_0(t):y0(t);k0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function y0(t){let e=t.platform==="linux-systemd-system"?"multi-user.target":"default.target";return["# Auto-generated by AIFight. Re-run `aifight service install` to refresh.","","[Unit]","Description=AIFight Agent Service","Documentation=https://aifight.ai/skill.md","Wants=network-online.target","After=network-online.target","","[Service]","Type=simple",`ExecStart=${nm(t.nodeExec)} ${nm(t.aifightExec)} run`,rm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),rm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
75
+ `)}function _0(t){let e=vt.dirname(t.unitPath).includes("LaunchAgents")?vt.join(tc.homedir(),"Library","Logs","aifight"):vt.join(vt.dirname(t.unitPath),"logs");return Pe.mkdirSync(e,{recursive:!0}),['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${ri}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Wr(t.nodeExec)}</string>`,` <string>${Wr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Wr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Wr(vt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Wr(vt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
76
+ `)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function rt(t){return`gui/${t.uid??process.getuid?.()??0}`}async function oc(t){let e=t.execFile??Ge,n=`${rt(t)}/${ri}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${ri} is loaded: ${Yn(r)}`}catch{throw r}}}async function w0(t){let e=t.username??tc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ge;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${Yn(r)}`}}}async function v0(t,e){let n=e.execFile??Ge;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",rt(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=hn(t.platform);await n("systemctl",[...r,"disable","--now",Dt]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function b0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Vr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!E0(n))try{return Vr(n)}catch{}let r=t.execFile??Ge;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
77
+ `)[0];if(i)return Vr(i)}catch{}throw new te("service_exec_unresolved","could not resolve a stable `aifight` executable for the background service","Install with `npm install -g @aifight/aifight@alpha`, then run `aifight service install` again.")}function S0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Vr(e);try{return Vr(process.execPath)}catch{throw new te("service_exec_unresolved","could not resolve a stable Node.js executable for the background service","Install Node.js >=20.19 and rerun `aifight service install`.")}}function Vr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function E0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function tm(t,e,n){let r=n.execFile??Ge;try{await r(t,e)}catch(o){throw new te("service_manager_unavailable",`${t} is not available or not usable on this system: ${Yn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function nm(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function rm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function k0(t,e,n){let r=`${t}.${process.pid}.tmp`;Pe.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Pe.chmodSync(r,n),Pe.renameSync(r,t)}function Yn(t){let e=t,n=typeof e.stderr=="string"&&e.stderr.trim()!==""?e.stderr:e.message;return String(n).trim().split(`
78
+ `)[0]??"unknown error"}function Wr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var ic=["usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
79
+ `);async function am(t,e){J(t,1,1,ic);let n=t.positional[0],r=$0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",ic);try{switch(n){case"install":{ce();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await nc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
80
80
  `):(e.stdout(`aifight.service installed and started (${i.platform}).
81
81
  `),e.stdout(`unit: ${i.unitPath}
82
82
  `),i.warning&&e.stderr(`warning: ${i.warning}
83
- `)),0}case"status":{let o=await Kn(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
83
+ `)),0}case"status":{let o=await pn(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
84
84
  `):o.installed?(e.stdout(`aifight.service: ${o.running?"running":"stopped"} (${o.detail})
85
85
  `),e.stdout(`unit: ${o.unitPath}
86
86
  `)):(e.stdout(`aifight.service: not installed
87
87
  `),e.stdout(`run: aifight service install
88
- `)),0}case"start":{let o=await nm(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
- `),0}case"stop":{let o=await rm(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
90
- `),0}case"restart":{let o=await om(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
91
- `),0}case"uninstall":{let o=await ri(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
92
- `),0}default:throw new O(`unknown service command '${n}'`,tc)}}catch(o){if(o instanceof O)throw o;if(o instanceof ce)return t.jsonMode?e.stderr(JSON.stringify({error:{code:o.code,message:o.message,...o.hint?{hint:o.hint}:{}}})+`
88
+ `)),0}case"start":{let o=await om(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
89
+ `),0}case"stop":{let o=await im(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
90
+ `),0}case"restart":{let o=await rc(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
91
+ `),0}case"uninstall":{let o=await oi(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
92
+ `),0}default:throw new O(`unknown service command '${n}'`,ic)}}catch(o){if(o instanceof O)throw o;if(o instanceof te)return t.jsonMode?e.stderr(JSON.stringify({error:{code:o.code,message:o.message,...o.hint?{hint:o.hint}:{}}})+`
93
93
  `):(e.stderr(`aifight: ${o.message}
94
94
  `),o.hint&&e.stderr(`${o.hint}
95
95
  `)),o.code==="service_platform_unsupported"||o.code==="service_manager_unavailable"?2:1;let i=o instanceof Error?o.message:String(o);return t.jsonMode?e.stderr(JSON.stringify({error:{code:"service_command_failed",message:i}})+`
96
96
  `):e.stderr(`aifight: service command failed: ${i}
97
- `),1}}function S0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function sm(t){if(!process.stdin.isTTY)return"unavailable";if(t.stdout(["AIFight needs a long-running local Bridge before your Agent can play scheduled matches and challenges.","","I can install a local background service named aifight.service.","It runs `aifight run` after reboot and keeps the outbound Bridge online for normal use.","","This does not expose your machine to the public internet.","AIFight Bridge only opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","","If you do not install it now, finish setup later with `aifight service install` or manage `aifight run` yourself.",""].join(`
98
- `)),!await E0(t,"Install and start aifight.service now? [Y/n] "))return"declined";try{let n=await Za(t.bridgeService);return t.stdout(`aifight.service installed and started (${n.platform}).
99
- `),t.stdout(`unit: ${n.unitPath}
100
- `),n.warning&&t.stderr(`warning: ${n.warning}
101
- `),"installed"}catch(n){let r=(n instanceof ce,n.message),o=n instanceof ce?n.hint:void 0;return t.stderr(`aifight.service could not be installed: ${r}
102
- `),o&&t.stderr(`${o}
103
- `),"unavailable"}}async function E0(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{randomBytes as O0}from"node:crypto";import Qn from"node:fs";import N0 from"node:os";import um from"node:path";import{execFile as $0}from"node:child_process";import am from"node:fs";import cm from"node:path";var k0=3e4;function wt(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(cm.delimiter))if(r)for(let o of n){let i=cm.join(r,`${t}${o}`);try{return am.accessSync(i,am.constants.X_OK),i}catch{}}}async function vt(t,e){let n=wt(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};$0(n,e,{timeout:k0},(a,c,l)=>{let u=a?.code;i({code:typeof u=="number"?u:a?1:0,stdout:String(c??""),stderr:String(l??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function hn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
97
+ `),1}}function $0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function cm(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await R0(t);if(n?.installed&&n.running===!0){if(t.stdout(["aifight.service is already running.","AIFight just saved bridge credentials, so the service must reload them before the Dashboard can show the new Agent online.",""].join(`
98
+ `)),!(e.approvedLocalSetup===!0?!0:await sm(t,"Restart aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting aifight.service now.
99
+ `);try{let i=await rc(t.bridgeService);return t.stdout(`aifight.service restarted (${i.platform}).
100
+ `),t.stdout(`unit: ${i.unitPath}
101
+ `),"installed"}catch(i){let s=(i instanceof te,i.message),a=i instanceof te?i.hint:void 0;return t.stderr(`aifight.service could not be restarted: ${s}
102
+ `),a&&t.stderr(`${a}
103
+ `),"unavailable"}}if(t.stdout(["AIFight needs a long-running local Bridge before your Agent can play scheduled matches and challenges.","","I can install a local background service named aifight.service.","It runs `aifight run` after reboot and keeps the outbound Bridge online for normal use.","","This does not expose your machine to the public internet.","AIFight Bridge only opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","","If you do not install it now, finish setup later with `aifight service install` or manage `aifight run` yourself.",""].join(`
104
+ `)),!(e.approvedLocalSetup===!0?!0:await sm(t,"Install and start aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; installing aifight.service now.
105
+ `);try{let o=await nc(t.bridgeService);return t.stdout(`aifight.service installed and started (${o.platform}).
106
+ `),t.stdout(`unit: ${o.unitPath}
107
+ `),o.warning&&t.stderr(`warning: ${o.warning}
108
+ `),"installed"}catch(o){let i=(o instanceof te,o.message),s=o instanceof te?o.hint:void 0;return t.stderr(`aifight.service could not be installed: ${i}
109
+ `),s&&t.stderr(`${s}
110
+ `),"unavailable"}}async function R0(t){try{return await pn(t.bridgeService)}catch{return}}async function sm(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{execFile as P0}from"node:child_process";import lm from"node:fs";import um from"node:path";var T0=3e4;function Te(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(um.delimiter))if(r)for(let o of n){let i=um.join(r,`${t}${o}`);try{return lm.accessSync(i,lm.constants.X_OK),i}catch{}}}async function ot(t,e){let n=Te(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};P0(n,e,{timeout:T0},(a,c,l)=>{let u=a?.code;i({code:typeof u=="number"?u:a?1:0,stdout:String(c??""),stderr:String(l??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function gn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
104
111
  `),n.stderr.trim()&&t.stderr(`${e}: ${n.stderr.trim()}
105
- `)}async function nc(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}async function Wr(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}async function Yn(t,e,n){let r=await R0(e),o=e==="openclaw"?"OpenClaw Gateway":"Hermes Gateway";if(r===void 0)return t.stdout([`${o} needs a restart for this change to apply.`,"I could not safely detect how it is managed, so I will not restart it automatically.",`Manual restart options: ${x0(e)}`,""].join(`
106
- `)),!1;if(t.stdout([`${o} needs a restart for this change to apply.`,`Detected restart method: ${r.label}.`,`Reason: ${n}`,"Restarting may interrupt any current OpenClaw/Hermes tasks using this Gateway.",r.note??"",`Command I would run: ${r.manualCommand}`,""].filter(a=>a!=="").join(`
112
+ `)}async function ii(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}async function zr(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}async function Xn(t,e,n,r={}){let o=await A0(e),i=e==="openclaw"?"OpenClaw Gateway":"Hermes Gateway";if(o===void 0)return t.stdout([`${i} needs a restart for this change to apply.`,"I could not safely detect how it is managed, so I will not restart it automatically.",`Manual restart options: ${O0(e)}`,""].join(`
113
+ `)),!1;if(t.stdout([`${i} needs a restart for this change to apply.`,`Detected restart method: ${o.label}.`,`Reason: ${n}`,"Restarting may interrupt any current OpenClaw/Hermes tasks using this Gateway.",o.note??"",`Command I would run: ${o.manualCommand}`,""].filter(c=>c!=="").join(`
107
114
  `)+`
108
- `),!await Wr(t,"Restart now? [y/N] "))return t.stdout(`Skipped restart. Run when ready: ${r.manualCommand}
115
+ `),!(r.approvedLocalSetup===!0?!0:await zr(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
109
116
 
110
- `),!1;let s=await vt(r.command,r.args);return hn(t,r.manualCommand,s),e==="hermes"&&A0(s)?(t.stdout("Hermes reported that no restartable service is available. Start it manually with `hermes gateway run` when ready.\n\n"),!1):s.code!==0?(t.stderr(`Restart command did not complete successfully. Run manually when ready: ${r.manualCommand}
117
+ `),!1;r.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting now.
118
+ `);let a=await ot(o.command,o.args);return gn(t,o.manualCommand,a),e==="hermes"&&I0(a)?(t.stdout("Hermes reported that no restartable service is available. Start it manually with `hermes gateway run` when ready.\n\n"),!1):a.code!==0?(t.stderr(`Restart command did not complete successfully. Run manually when ready: ${o.manualCommand}
111
119
 
112
- `),!1):(t.stdout(`${o} restart requested.
120
+ `),!1):(t.stdout(`${i} restart requested.
113
121
 
114
- `),!0)}async function R0(t){let e=await P0(t);if(e)return e;if(t==="openclaw"&&wt("openclaw"))return{label:"OpenClaw CLI",command:"openclaw",args:["gateway","restart","--safe"],manualCommand:"openclaw gateway restart --safe",note:"This uses OpenClaw's own safe restart command instead of killing a process."};if(t==="hermes"&&wt("hermes"))return{label:"Hermes CLI",command:"hermes",args:["gateway","restart"],manualCommand:"hermes gateway restart",note:"If Hermes is running in a foreground terminal, stop that process and run `hermes gateway run` when ready."}}async function P0(t){if(process.platform!=="linux"||!wt("systemctl"))return;let e=t==="openclaw"?["openclaw-gateway.service","openclaw.gateway.service","openclaw.service"]:["hermes-gateway.service","hermes.gateway.service","hermes.service"];for(let n of[[],["--user"]])for(let r of e){let o=await vt("systemctl",[...n,"is-active",r]);if(T0(o)){let i=n.length>0?`${n.join(" ")} `:"";return{label:`systemd ${i}${r}`.trim(),command:"systemctl",args:[...n,"restart",r],manualCommand:`systemctl ${i}restart ${r}`}}}}function T0(t){return t.code===0&&t.stdout.trim()==="active"}function A0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
115
- ${t.stderr}`)}function x0(t){return t==="openclaw"?"`openclaw gateway restart --safe`, or restart your own OpenClaw service manager":"`hermes gateway restart`, or restart the terminal running `hermes gateway run`"}import Vr from"node:fs";import C0 from"node:path";function rc(){return C0.join(ne(),"runtime-setup.json")}function oc(){try{let t=Vr.readFileSync(rc(),"utf8"),e=JSON.parse(t);return I0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function ic(t){ot();let e=oc(),n={version:1,updatedAt:new Date().toISOString(),...e?.openclaw?{openclaw:e.openclaw}:{},...e?.hermes?{hermes:e.hermes}:{},...t.openclaw?{openclaw:t.openclaw}:{},...t.hermes?{hermes:t.hermes}:{}},r=rc(),o=`${r}.tmp`;if(Vr.writeFileSync(o,JSON.stringify(n,null,2)+`
116
- `,{mode:384}),Vr.renameSync(o,r),process.platform!=="win32")try{Vr.chmodSync(r,384)}catch{}}function lm(){Vr.rmSync(rc(),{force:!0})}function I0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var cc="gateway.http.endpoints.responses.enabled",fm=4e3,M0=6e3,mm=1e4;async function hm(t){if(t.jsonMode||!process.stdin.isTTY)return{};switch(t.runtimeType){case"openclaw":return await L0(t),{};case"hermes":return j0(t);case"mock":return{}}}async function L0(t){let e=await sc(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable"){t.env.stdout(`OpenClaw local /v1/responses is reachable (${e.detail}).
122
+ `),!0)}async function A0(t){let e=await C0(t);if(e)return e;if(t==="openclaw"&&Te("openclaw"))return{label:"OpenClaw CLI",command:"openclaw",args:["gateway","restart","--safe"],manualCommand:"openclaw gateway restart --safe",note:"This uses OpenClaw's own safe restart command instead of killing a process."};if(t==="hermes"&&Te("hermes"))return{label:"Hermes CLI",command:"hermes",args:["gateway","restart"],manualCommand:"hermes gateway restart",note:"If Hermes is running in a foreground terminal, stop that process and run `hermes gateway run` when ready."}}async function C0(t){if(process.platform!=="linux"||!Te("systemctl"))return;let e=t==="openclaw"?["openclaw-gateway.service","openclaw.gateway.service","openclaw.service"]:["hermes-gateway.service","hermes.gateway.service","hermes.service"];for(let n of[[],["--user"]])for(let r of e){let o=await ot("systemctl",[...n,"is-active",r]);if(x0(o)){let i=n.length>0?`${n.join(" ")} `:"";return{label:`systemd ${i}${r}`.trim(),command:"systemctl",args:[...n,"restart",r],manualCommand:`systemctl ${i}restart ${r}`}}}}function x0(t){return t.code===0&&t.stdout.trim()==="active"}function I0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
123
+ ${t.stderr}`)}function O0(t){return t==="openclaw"?"`openclaw gateway restart --safe`, or restart your own OpenClaw service manager":"`hermes gateway restart`, or restart the terminal running `hermes gateway run`"}import{randomBytes as L0}from"node:crypto";import Zn from"node:fs";import j0 from"node:os";import fm from"node:path";import Kr from"node:fs";import N0 from"node:path";function sc(){return N0.join(re(),"runtime-setup.json")}function ac(){try{let t=Kr.readFileSync(sc(),"utf8"),e=JSON.parse(t);return M0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function cc(t){st();let e=ac(),n={version:1,updatedAt:new Date().toISOString(),...e?.openclaw?{openclaw:e.openclaw}:{},...e?.hermes?{hermes:e.hermes}:{},...t.openclaw?{openclaw:t.openclaw}:{},...t.hermes?{hermes:t.hermes}:{}},r=sc(),o=`${r}.tmp`;if(Kr.writeFileSync(o,JSON.stringify(n,null,2)+`
124
+ `,{mode:384}),Kr.renameSync(o,r),process.platform!=="win32")try{Kr.chmodSync(r,384)}catch{}}function dm(){Kr.rmSync(sc(),{force:!0})}function M0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var uc="gateway.http.endpoints.responses.enabled",mm=4e3,D0=6e3,pm=1e4;async function hm(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return F0(t);case"hermes":return B0(t);case"mock":return{}}}async function F0(t){let e=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`OpenClaw local /v1/responses is reachable (${e.detail}).
117
125
 
118
- `);return}if(e.status==="auth_failed"){t.env.stdout([`OpenClaw local /v1/responses is enabled but returned an auth error (${e.detail}).`,"If your Gateway requires a local token, rerun register with:"," aifight register --runtime-token <OPENCLAW_GATEWAY_TOKEN>",""].join(`
119
- `));return}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost.","Your model/provider keys stay inside OpenClaw.","","I can run:",` openclaw config set ${cc} true --strict-json`," openclaw config validate",""].join(`
120
- `)),!wt("openclaw")){t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
126
+ `),{};if(e.status==="auth_failed"){if(t.runtimeLocalToken!==void 0)return t.env.stdout(`OpenClaw local /v1/responses rejected the provided runtime token (${e.detail}).
121
127
 
122
- `);return}if(!await nc(t.env,"Allow this local OpenClaw config change now? [Y/n] ")){t.env.stdout(`Skipped OpenClaw config change. You can run the command above later.
128
+ `),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."};if(t.env.stdout([`OpenClaw local /v1/responses is enabled but requires a local Gateway token (${e.detail}).`,"AIFight can store that token only in the local bridge credentials so the bridge can call localhost.","The token is not uploaded to AIFight and will not be printed.",""].join(`
129
+ `)),!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow AIFight to read and store the local OpenClaw Gateway token now? [Y/n] ")))return{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; reading the local OpenClaw Gateway token now.
130
+ `);let u=await W0();if(u.length===0)return t.env.stdout("Could not find an OpenClaw Gateway token from OPENCLAW_GATEWAY_TOKEN or `openclaw config get gateway.auth.token`.\n\n"),{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};for(let d of u){let h=await er(t.env,t.runtimeLocalUrl,d,t.runtimeModel);if(h.status==="ready"||h.status==="endpoint_reachable")return t.env.stdout(`OpenClaw accepted a local Gateway token (${h.detail}).
123
131
 
124
- `);return}let r=await U0(),o=await vt("openclaw",["config","set",cc,"true","--strict-json"]);if(hn(t.env,"openclaw config set",o),o.code!==0){t.env.stderr(`OpenClaw config update failed. Continue only after enabling /v1/responses manually.
132
+ `),{runtimeLocalToken:d}}return t.env.stdout(`OpenClaw did not accept any discovered local Gateway token.
125
133
 
126
- `);return}let i=await vt("openclaw",["config","validate"]);hn(t.env,"openclaw config validate",i),ic({openclaw:{responsesEnabledByAIFight:r!==!0,updatedAt:new Date().toISOString()}}),t.env.stdout(`OpenClaw config updated. Gateway may need a restart before the endpoint is available.
127
- `),await lc(M0);let s=await sc(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(s.status==="ready"||s.status==="endpoint_reachable"){t.env.stdout(`OpenClaw endpoint check: ${s.detail}
134
+ `),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."}}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost / 127.0.0.1.","Your model/provider keys stay inside OpenClaw.","If Gateway is already running, it may need a safe restart for this change to apply.","","I can run:",` openclaw config set ${uc} true --strict-json`," openclaw config validate",""].join(`
135
+ `)),!Te("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
128
136
 
129
- `);return}if(t.env.stdout(`OpenClaw endpoint is still not ready (${s.detail}).
130
- `),!await Yn(t.env,"openclaw","OpenClaw /v1/responses was enabled for AIFight.")){t.env.stdout(`OpenClaw endpoint will be available after you restart Gateway when ready.
137
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow this local OpenClaw config change now? [Y/n] ")))return t.env.stdout(`Skipped OpenClaw config change. You can run the command above later.
131
138
 
132
- `);return}t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
133
- `),await lc(mm);let c=await sc(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
139
+ `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; applying OpenClaw config now.
140
+ `);let r=await z0(),o=await ot("openclaw",["config","set",uc,"true","--strict-json"]);if(gn(t.env,"openclaw config set",o),o.code!==0)return t.env.stderr(`OpenClaw config update failed. Continue only after enabling /v1/responses manually.
134
141
 
135
- `)}async function j0(t){let e=await dm(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`Hermes local API Server is reachable (${e.detail}).
142
+ `),{};let i=await ot("openclaw",["config","validate"]);gn(t.env,"openclaw config validate",i),cc({openclaw:{responsesEnabledByAIFight:r!==!0,updatedAt:new Date().toISOString()}}),t.env.stdout(`OpenClaw config updated. Gateway may need a restart before the endpoint is available.
143
+ `),await dc(D0);let s=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(s.status==="ready"||s.status==="endpoint_reachable")return t.env.stdout(`OpenClaw endpoint check: ${s.detail}
136
144
 
137
- `),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost.","Your Hermes provider keys, tools, and strategy prompts stay local.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${gm(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
138
- `)),!wt("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
145
+ `),{};if(t.env.stdout(`OpenClaw endpoint is still not ready (${s.detail}).
146
+ `),!await Xn(t.env,"openclaw","OpenClaw /v1/responses was enabled for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`OpenClaw endpoint will be available after you restart Gateway when ready.
139
147
 
140
- `),{};if(!await nc(t.env,"Allow this local Hermes .env update now? [Y/n] "))return t.env.stdout(`Skipped Hermes .env update. You can add the API_SERVER_* values later.
148
+ `),{};t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
149
+ `),await dc(pm);let c=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);return t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
141
150
 
142
- `),{};let r=D0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(ic({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
151
+ `),{}}async function B0(t){let e=await si(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`Hermes local API Server is reachable (${e.detail}).
152
+
153
+ `),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost / 127.0.0.1.","Your Hermes provider keys, tools, and strategy prompts stay local.","Hermes may need a Gateway restart for API_SERVER_* changes to apply.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${ym(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
154
+ `)),!Te("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
155
+
156
+ `),{};if(!(t.approvedLocalSetup===!0?!0:await ii(t.env,"Allow this local Hermes .env update now? [Y/n] ")))return t.env.stdout(`Skipped Hermes .env update. You can add the API_SERVER_* values later.
157
+
158
+ `),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; updating Hermes .env now.
159
+ `);let r=q0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(cc({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
143
160
  `),t.env.stdout(`Hermes does not hot-reload API_SERVER_* settings.
144
- `),!await Yn(t.env,"hermes","Hermes API Server settings were updated for AIFight."))return t.env.stdout(`Hermes API Server will be available after you start or restart Gateway when ready.
161
+ `),!await Xn(t.env,"hermes","Hermes API Server settings were updated for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`Hermes API Server will be available after you start or restart Gateway when ready.
145
162
 
146
163
  `),{runtimeLocalToken:o};t.env.stdout(`Waiting 10 seconds before checking Hermes /v1/responses again...
147
- `),await lc(mm);let s=await dm(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
164
+ `),await dc(pm);let s=await si(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
148
165
 
149
- `),{runtimeLocalToken:o}}async function sc(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),fm);try{let a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let c=await o(`${e.replace(/\/+$/,"")}/v1/responses`,{method:"POST",headers:a,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'}),signal:i.signal});return c.status===404?{status:"disabled",detail:"OpenClaw /v1/responses returned HTTP 404"}:c.status===401||c.status===403?{status:"auth_failed",detail:`OpenClaw /v1/responses returned HTTP ${c.status}`}:c.ok?{status:"ready",detail:`OpenClaw /v1/responses HTTP ${c.status}`}:{status:"endpoint_reachable",detail:`OpenClaw /v1/responses HTTP ${c.status}`}}catch(a){let c=a instanceof Error&&a.name==="AbortError"?"OpenClaw /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config":`OpenClaw /v1/responses is not reachable (${a instanceof Error?a.message:String(a)})`;return{status:a instanceof Error&&a.name==="AbortError"?"endpoint_reachable":"unreachable",detail:c}}finally{clearTimeout(s)}}async function dm(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await ac(o,`${i}/health`,{});if(!s.ok)return{status:"unreachable",detail:`Hermes /health HTTP ${s.status}`};let a={};n&&(a.Authorization=`Bearer ${n}`);let c=await ac(o,`${i}/v1/models`,{headers:a});if(c.status===401||c.status===403)return{status:"auth_failed",detail:`Hermes /v1/models HTTP ${c.status}; check API_SERVER_KEY and --runtime-token`};if(!c.ok)return{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}`};let l={"Content-Type":"application/json",...a},u;try{u=await ac(o,`${i}/v1/responses`,{method:"POST",headers:l,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'})})}catch(d){return d instanceof Error&&d.name==="AbortError"?{status:"endpoint_reachable",detail:"Hermes /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config"}:{status:"unreachable",detail:`Hermes /v1/responses is not reachable (${d instanceof Error?d.message:String(d)})`}}return u.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:u.status===401||u.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${u.status}; check API_SERVER_KEY and --runtime-token`}:u.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function ac(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),fm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function D0(t){let e=process.env.HERMES_HOME??um.join(N0.homedir(),".hermes");Qn.mkdirSync(e,{recursive:!0,mode:448});let n=um.join(e,".env"),r=Qn.existsSync(n)?Qn.readFileSync(n,"utf8"):"";if(r!==""){let l=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");Qn.copyFileSync(n,`${n}.aifight-backup-${l}`)}let o=pm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${O0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:B0(t.runtimeLocalUrl),API_SERVER_PORT:String(gm(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=q0(r,Object.keys(s)),c=F0(r,s);if(Qn.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{Qn.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function F0(t,e){let n=new Set(Object.keys(e)),r=new Set,i=t.split(/\r?\n/).map(s=>{let a=s.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!a)return s;let c=a[3];return n.has(c)?(r.add(c),`${c}=${e[c]}`):s});if(i.length>0&&i[i.length-1]!==""&&i.push(""),[...n].some(s=>!r.has(s))){i.push("# AIFight local API Server settings");for(let s of Object.keys(e))r.has(s)||i.push(`${s}=${e[s]}`)}return i.join(`
166
+ `),{runtimeLocalToken:o}}async function er(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),mm);try{let a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let c=await o(`${e.replace(/\/+$/,"")}/v1/responses`,{method:"POST",headers:a,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'}),signal:i.signal});return c.status===404?{status:"disabled",detail:"OpenClaw /v1/responses returned HTTP 404"}:c.status===401||c.status===403?{status:"auth_failed",detail:`OpenClaw /v1/responses returned HTTP ${c.status}`}:c.ok?{status:"ready",detail:`OpenClaw /v1/responses HTTP ${c.status}`}:{status:"endpoint_reachable",detail:`OpenClaw /v1/responses HTTP ${c.status}`}}catch(a){let c=a instanceof Error&&a.name==="AbortError"?"OpenClaw /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config":`OpenClaw /v1/responses is not reachable (${a instanceof Error?a.message:String(a)})`;return{status:a instanceof Error&&a.name==="AbortError"?"endpoint_reachable":"unreachable",detail:c}}finally{clearTimeout(s)}}async function si(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await lc(o,`${i}/health`,{});if(!s.ok)return{status:"unreachable",detail:`Hermes /health HTTP ${s.status}`};let a={};n&&(a.Authorization=`Bearer ${n}`);let c=await lc(o,`${i}/v1/models`,{headers:a});if(c.status===401||c.status===403)return{status:"auth_failed",detail:`Hermes /v1/models HTTP ${c.status}; check API_SERVER_KEY and --runtime-token`};if(!c.ok)return{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}`};let l={"Content-Type":"application/json",...a},u;try{u=await lc(o,`${i}/v1/responses`,{method:"POST",headers:l,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'})})}catch(d){return d instanceof Error&&d.name==="AbortError"?{status:"endpoint_reachable",detail:"Hermes /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config"}:{status:"unreachable",detail:`Hermes /v1/responses is not reachable (${d instanceof Error?d.message:String(d)})`}}return u.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:u.status===401||u.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${u.status}; check API_SERVER_KEY and --runtime-token`}:u.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function lc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),mm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function q0(t){let e=process.env.HERMES_HOME??fm.join(j0.homedir(),".hermes");Zn.mkdirSync(e,{recursive:!0,mode:448});let n=fm.join(e,".env"),r=Zn.existsSync(n)?Zn.readFileSync(n,"utf8"):"";if(r!==""){let l=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");Zn.copyFileSync(n,`${n}.aifight-backup-${l}`)}let o=gm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${L0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:H0(t.runtimeLocalUrl),API_SERVER_PORT:String(ym(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=G0(r,Object.keys(s)),c=U0(r,s);if(Zn.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{Zn.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function U0(t,e){let n=new Set(Object.keys(e)),r=new Set,i=t.split(/\r?\n/).map(s=>{let a=s.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!a)return s;let c=a[3];return n.has(c)?(r.add(c),`${c}=${e[c]}`):s});if(i.length>0&&i[i.length-1]!==""&&i.push(""),[...n].some(s=>!r.has(s))){i.push("# AIFight local API Server settings");for(let s of Object.keys(e))r.has(s)||i.push(`${s}=${e[s]}`)}return i.join(`
150
167
  `).replace(/\n*$/,`
151
- `)}function pm(t,e){for(let n of t.split(/\r?\n/)){if(n.trimStart().startsWith("#"))continue;let r=n.match(new RegExp(`^\\s*${e}\\s*=\\s*(.*)\\s*$`));if(!r)continue;return r[1].trim().replace(/^['"]|['"]$/g,"")}}function B0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function gm(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function q0(t,e){let n={};for(let r of e){let o=pm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function U0(){let t=await vt("openclaw",["config","get",cc]);if(t.code!==0)return;let e=t.stdout.trim().toLowerCase();if(e==="true"||e.endsWith(" true"))return!0;if(e==="false"||e.endsWith(" false"))return!1}function lc(t){return new Promise(e=>setTimeout(e,t))}var V0="https://aifight.ai",ym=2,zr=["usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," Creates a private bootstrap AIFight identity, saves local match credentials, and offers aifight.service."," In human interactive mode, asks which local runtime to use when none is specified."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Claim the agent and choose its official Dashboard name before it can play matches or challenges."].join(`
152
- `);async function _m(t,e){J(t,0,1,zr);let n=await z0(t,e),r=J0(t,n),o=Y0(process.env.AIFIGHT_BASE_URL??V0),i=Gr(t.flags,"runtime-model")??Gn(n),s=X0(Gr(t.flags,"runtime-url")??ti(n),n),a=Gr(t.flags,"runtime-token");try{let c=await hm({env:e,runtimeType:n,runtimeLocalUrl:s,runtimeLocalToken:a,runtimeModel:i,jsonMode:t.jsonMode});a=a??c.runtimeLocalToken;let l=await ca({baseUrl:o,request:{name:r,model:i,description:`AIFight Bridge agent (${n})`},fetchImpl:e.fetchImpl}),u={version:1,baseUrl:o,wsUrl:Q0(o),agentId:l.agentId,agentName:l.response.agent.name,suggestedName:l.response.agent.suggested_name??r,apiKey:l.apiKey,claimUrl:l.claimUrl,claimToken:l.claimToken,runtimeType:n,runtimeLocalUrl:s,...a!==void 0?{runtimeLocalToken:a}:{},runtimeModel:i,autoDailyLimit:ym,updatedAt:new Date().toISOString()};return fn(u),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:l.claimUrl,config:Mt(u)})+`
168
+ `)}function gm(t,e){for(let n of t.split(/\r?\n/)){if(n.trimStart().startsWith("#"))continue;let r=n.match(new RegExp(`^\\s*${e}\\s*=\\s*(.*)\\s*$`));if(!r)continue;return r[1].trim().replace(/^['"]|['"]$/g,"")}}function H0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function ym(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function G0(t,e){let n={};for(let r of e){let o=gm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function W0(){let t=[],e=o=>{o&&!t.includes(o)&&t.push(o)},n=process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e(n),!Te("openclaw"))return t;let r=await ot("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(V0(r.stdout)),t}function V0(t){let e=t.trim();if(e===""||e.toLowerCase()==="null"||e.toLowerCase()==="undefined")return;try{let i=JSON.parse(e);if(typeof i=="string"&&i.trim()!=="")return i.trim();if(i&&typeof i=="object"){let s=i.value??i.token??i["gateway.auth.token"];if(typeof s=="string"&&s.trim()!=="")return s.trim()}}catch{}let n=e.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);if(!n)return;let o=(n.match(/(?:gateway\.auth\.token|token)\s*[:=]\s*(.+)$/i)?.[1]??n).trim().replace(/^['"]|['"]$/g,"");return o.length>0?o:void 0}async function z0(){let t=await ot("openclaw",["config","get",uc]);if(t.code!==0)return;let e=t.stdout.trim().toLowerCase();if(e==="true"||e.endsWith(" true"))return!0;if(e==="false"||e.endsWith(" false"))return!1}function dc(t){return new Promise(e=>setTimeout(e,t))}var Y0="https://aifight.ai",_m=2,Q0="approved-local-setup",yn=["usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Creates a private bootstrap AIFight identity, saves local match credentials, and offers aifight.service."," In human interactive mode, asks which local runtime to use when none is specified."," --approved-local-setup is for Agent-assisted setup after the human already approved local runtime/service changes."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Claim the agent and choose its official Dashboard name before it can play matches or challenges."].join(`
169
+ `);async function vm(t,e){J(t,0,1,yn);let n=t.flags[Q0]===!0;if(t.jsonMode&&n)throw new O("--approved-local-setup cannot be combined with --json",yn);let r=await X0(t,e,n),o=tE(t,r),i=nE(process.env.AIFIGHT_BASE_URL??Y0),s=Jr(t.flags,"runtime-model")??Mt(r),a=oE(Jr(t.flags,"runtime-url")??Jn(r),r),c=Jr(t.flags,"runtime-token");try{let l=await hm({env:e,runtimeType:r,runtimeLocalUrl:a,runtimeLocalToken:c,runtimeModel:s,jsonMode:t.jsonMode,approvedLocalSetup:n});if(l.blockedReason!==void 0)throw new W("runtime_setup_incomplete",l.blockedReason);c=c??l.runtimeLocalToken;let u=await da({baseUrl:i,request:{name:o,model:s,description:`AIFight Bridge agent (${r})`},fetchImpl:e.fetchImpl}),d={version:1,baseUrl:i,wsUrl:rE(i),agentId:u.agentId,agentName:u.response.agent.name,suggestedName:u.response.agent.suggested_name??o,apiKey:u.apiKey,claimUrl:u.claimUrl,claimToken:u.claimToken,runtimeType:r,runtimeLocalUrl:a,...c!==void 0?{runtimeLocalToken:c}:{},runtimeModel:s,autoDailyLimit:_m,updatedAt:new Date().toISOString()};return mn(d),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:u.claimUrl,config:Lt(d)})+`
153
170
  `),0):(e.stdout(`AIFight Agent registered.
154
171
 
155
- `),e.stdout(`Bootstrap ID: ${u.agentName}
156
- `),e.stdout(`Suggested name: ${u.suggestedName??r}
172
+ `),e.stdout(`Bootstrap ID: ${d.agentName}
173
+ `),e.stdout(`Suggested name: ${d.suggestedName??o}
157
174
  `),e.stdout(`Status: unclaimed, official name pending
158
- `),e.stdout(`Runtime: ${G0(u.runtimeType)} at ${u.runtimeLocalUrl}
159
- `),e.stdout(`Automatic ranked matches: ${ym} per day
175
+ `),e.stdout(`Runtime: ${bm(d.runtimeType)} at ${d.runtimeLocalUrl}
176
+ `),e.stdout(`Automatic ranked matches: ${_m} per day
160
177
  `),e.stdout(`Local credentials saved on this machine.
161
178
 
162
179
  `),e.stdout(`Claim URL:
163
- `),e.stdout(`${l.claimUrl}
180
+ `),e.stdout(`${u.claimUrl}
164
181
 
165
182
  `),e.stdout(`Claim this agent, then confirm its official public name in Dashboard before starting matches, challenges, or Grand Prix events. Claiming also enables dashboard management, profile settings, and recovery.
166
183
 
167
- `),await sm(e)==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
184
+ `),await cm(e,{approvedLocalSetup:n})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
168
185
 
169
186
  `),e.stdout(`Normal use requires a long-running local Bridge.
170
187
  `),e.stdout(`Finish setup with:
171
188
  `),e.stdout(` aifight service install
172
189
 
173
190
  `),e.stdout(`Advanced alternatives:
174
- `),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(c){if(c instanceof Qt){let l=typeof c.body=="object"?c.body.error:void 0;throw new z("registration_failed",l??`registration failed with HTTP ${c.status}`)}throw c instanceof dt?new z("registration_failed",c.message):c}}function G0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function z0(t,e){let n=t.positional[0],r=Gr(t.flags,"runtime"),o=process.env.AIFIGHT_RUNTIME_TYPE,i=r??n??o;if(r!==void 0&&n!==void 0&&r!==n)throw new O("runtime argument and --runtime disagree",zr);if(i==="openclaw"||i==="hermes")return i;if(i===void 0)return!t.jsonMode&&process.stdin.isTTY?K0(e):"openclaw";throw new O(`runtime must be openclaw or hermes (got '${i}')`,zr)}async function K0(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
175
- `)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,zr)}function J0(t,e){let n=Gr(t.flags,"name");if(n!==void 0)return n;let r=H0.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${W0(3).toString("hex")}`.slice(0,50)}function Y0(t){return t.replace(/\/+$/,"")}function Q0(t){let e=new URL(t);if(e.protocol==="https:")e.protocol="wss:";else if(e.protocol==="http:")e.protocol="ws:";else throw new Error(`unsupported AIFight base URL protocol: ${e.protocol}`);return e.pathname="/api/ws",e.search="",e.hash="",e.toString()}function Gr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function X0(t,e){try{return qr(t,e)}catch(n){throw n instanceof Ue?new O(n.message,zr):n}}var Z0="https://aifight.ai";async function wm(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=eE(t.baseUrl??process.env.AIFIGHT_BASE_URL??Z0),o=await(t.fetchImpl??globalThis.fetch)(`${n}/api/bridge/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_code:e})});if(!o.ok){let l=await tE(o);throw new Error(l)}let i=await o.json(),s=nE(i),a=s.agent.runtime_type,c=t.now??(()=>new Date);return{version:1,baseUrl:n,wsUrl:s.ws_url,agentId:s.agent.id,agentName:s.agent.name,apiKey:s.agent.api_key,runtimeType:a,runtimeLocalUrl:ti(a),runtimeModel:Gn(a),updatedAt:c().toISOString()}}function eE(t){return t.replace(/\/+$/,"")}async function tE(t){let e=await t.json().catch(()=>{});if(e&&typeof e=="object"){let n=e.error;if(typeof n=="string"&&n.length>0)return n}return`pairing failed with HTTP ${t.status}`}function nE(t){if(!t||typeof t!="object")throw new Error("pairing response was not an object");let e=t,n=e.agent;if(!n||typeof n!="object")throw new Error("pairing response missing agent");let r=n;if(typeof r.id!="string"||typeof r.name!="string"||typeof r.api_key!="string"||r.runtime_type!=="openclaw"&&r.runtime_type!=="hermes"&&r.runtime_type!=="mock"||typeof e.ws_url!="string")throw new Error("pairing response had invalid fields");return{agent:{id:r.id,name:r.name,api_key:r.api_key,runtime_type:r.runtime_type},ws_url:e.ws_url,...typeof e.message=="string"?{message:e.message}:{}}}var bm=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."].join(`
176
- `);async function Sm(t,e){J(t,1,1,bm);let n=t.positional[0],r;try{r=await wm({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new z("pairing_failed",u)}let o={...r,...vm(t.flags,"runtime-token","runtimeLocalToken"),...vm(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=rE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return fn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Mt(c)})+`
191
+ `),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(l){if(l instanceof Xt){let u=typeof l.body=="object"?l.body.error:void 0;throw new W("registration_failed",u??`registration failed with HTTP ${l.status}`)}throw l instanceof mt?new W("registration_failed",l.message):l}}function bm(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function X0(t,e,n){let r=t.positional[0],o=Jr(t.flags,"runtime"),i=process.env.AIFIGHT_RUNTIME_TYPE,s=o??r??i;if(o!==void 0&&r!==void 0&&o!==r)throw new O("runtime argument and --runtime disagree",yn);if(s==="openclaw"||s==="hermes")return s;if(s===void 0){if(n){let a=await Z0(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${bm(a.runtimeType)} (${a.detail}).
192
+
193
+ `),a.runtimeType;throw new O(["Could not safely auto-detect whether this machine is running OpenClaw or Hermes.",a.detail,"Rerun with an explicit runtime:"," aifight register openclaw --approved-local-setup"," aifight register hermes --approved-local-setup"].join(`
194
+ `),yn)}return!t.jsonMode&&process.stdin.isTTY?eE(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,yn)}async function Z0(t){let[e,n]=await Promise.all([er(t,Jn("openclaw"),void 0,Mt("openclaw")),si(t,Jn("hermes"),void 0,Mt("hermes"))]),r=wm(e),o=wm(n);if(r>o)return{runtimeType:"openclaw",detail:e.detail};if(o>r)return{runtimeType:"hermes",detail:n.detail};if(r>0&&o>0)return{detail:`OpenClaw and Hermes both looked reachable: ${e.detail}; ${n.detail}`};let i=Te("openclaw")!==void 0,s=Te("hermes")!==void 0;if(i&&!s)return{runtimeType:"openclaw",detail:"OpenClaw CLI found on PATH; Hermes CLI not found"};if(s&&!i)return{runtimeType:"hermes",detail:"Hermes CLI found on PATH; OpenClaw CLI not found"};let a=i&&s?"both OpenClaw and Hermes CLIs are installed":"neither OpenClaw nor Hermes CLI was found on PATH";return{detail:`OpenClaw probe: ${e.detail}; Hermes probe: ${n.detail}; ${a}.`}}function wm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function eE(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
195
+ `)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,yn)}function tE(t,e){let n=Jr(t.flags,"name");if(n!==void 0)return n;let r=K0.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${J0(3).toString("hex")}`.slice(0,50)}function nE(t){return t.replace(/\/+$/,"")}function rE(t){let e=new URL(t);if(e.protocol==="https:")e.protocol="wss:";else if(e.protocol==="http:")e.protocol="ws:";else throw new Error(`unsupported AIFight base URL protocol: ${e.protocol}`);return e.pathname="/api/ws",e.search="",e.hash="",e.toString()}function Jr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function oE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof He?new O(n.message,yn):n}}var iE="https://aifight.ai";async function Sm(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=sE(t.baseUrl??process.env.AIFIGHT_BASE_URL??iE),o=await(t.fetchImpl??globalThis.fetch)(`${n}/api/bridge/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_code:e})});if(!o.ok){let l=await aE(o);throw new Error(l)}let i=await o.json(),s=cE(i),a=s.agent.runtime_type,c=t.now??(()=>new Date);return{version:1,baseUrl:n,wsUrl:s.ws_url,agentId:s.agent.id,agentName:s.agent.name,apiKey:s.agent.api_key,runtimeType:a,runtimeLocalUrl:Jn(a),runtimeModel:Mt(a),updatedAt:c().toISOString()}}function sE(t){return t.replace(/\/+$/,"")}async function aE(t){let e=await t.json().catch(()=>{});if(e&&typeof e=="object"){let n=e.error;if(typeof n=="string"&&n.length>0)return n}return`pairing failed with HTTP ${t.status}`}function cE(t){if(!t||typeof t!="object")throw new Error("pairing response was not an object");let e=t,n=e.agent;if(!n||typeof n!="object")throw new Error("pairing response missing agent");let r=n;if(typeof r.id!="string"||typeof r.name!="string"||typeof r.api_key!="string"||r.runtime_type!=="openclaw"&&r.runtime_type!=="hermes"&&r.runtime_type!=="mock"||typeof e.ws_url!="string")throw new Error("pairing response had invalid fields");return{agent:{id:r.id,name:r.name,api_key:r.api_key,runtime_type:r.runtime_type},ws_url:e.ws_url,...typeof e.message=="string"?{message:e.message}:{}}}var km=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."].join(`
196
+ `);async function $m(t,e){J(t,1,1,km);let n=t.positional[0],r;try{r=await Sm({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new W("pairing_failed",u)}let o={...r,...Em(t.flags,"runtime-token","runtimeLocalToken"),...Em(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=lE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return mn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Lt(c)})+`
177
197
  `),0):(e.stdout(`Bridge configured for ${c.agentName} (${c.runtimeType}).
178
198
  `),e.stdout(`Runtime local URL: ${c.runtimeLocalUrl}
179
199
  `),c.runtimeLocalToken&&e.stdout(`Runtime local token: configured locally (redacted)
180
200
  `),e.stdout(`Next: aifight service install
181
- `),0)}function vm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function rE(t,e){try{return qr(t,e)}catch(n){throw n instanceof Ue?new O(n.message,bm):n}}var uc=20,oi=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${uc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${he.join(", ")}`].join(`
182
- `);async function km(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,oi)}let n=oE(),r=iE(t.positional,n),o=await Lt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
201
+ `),0)}function Em(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function lE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof He?new O(n.message,km):n}}var fc=20,ai=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${fc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${pe.join(", ")}`].join(`
202
+ `);async function Tm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,ai)}let n=uE(),r=dE(t.positional,n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
183
203
  `),e.stderr(`Update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
184
204
  `),1;o.status==="update_recommended"&&(e.stdout(`[warn] bridge.update: ${o.message}
185
205
  `),e.stdout(`[warn] update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
186
- `));try{await Oc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof me?new z(sE(i),aE(i),{hint:await cE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
187
- `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${lE(r.game)} ${i} for ${n.agentName}.
206
+ `));try{await Mc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof me?new W(fE(i),mE(i),{hint:await pE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
207
+ `);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${hE(r.game)} ${i} for ${n.agentName}.
188
208
  `),e.stdout(`The running Bridge will keep your Agent online and handle the match when AIFight pairs it.
189
- `)}return 0}function oE(){try{return ae()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new z("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function iE(t,e){if(t.length===0)return{game:$m(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Em(n);if(i!==null)return{game:$m(e.autoGames),count:i};if(it(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,oi)}let r=t[1];if(!it(n))throw new O(`unsupported game '${n}'`,oi);let o=Em(r);if(o===null)throw new O(`N must be an integer between 1 and ${uc}`,oi);return{game:n,count:o}}function Em(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>uc?null:e}function $m(t){let e=(t??he).filter(it),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}function sE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function aE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function cE(t){try{let e=await Kn(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof ce))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function lE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Dt from"node:path";import ee from"node:fs";import uE from"node:crypto";var ye=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Pm(){return Dt.join(ne(),"token")}function Tm(){return Dt.join(ne(),"port")}function fc(){return Dt.join(ne(),"pid")}function dE(){return Dt.join(ne(),"lock")}var Rm=0,fE=/^[0-9a-f]{64}$/;function mc(t,e,n){let r=Dt.dirname(t),o=Dt.basename(t);Rm+=1;let i=Dt.join(r,`${o}.${process.pid}.${Rm}.tmp`),s;try{if(s=ee.openSync(i,"w",n),ee.writeSync(s,e),ee.closeSync(s),s=void 0,process.platform!=="win32")try{ee.chmodSync(i,n)}catch{}ee.renameSync(i,t)}catch(a){if(s!==void 0)try{ee.closeSync(s)}catch{}try{ee.unlinkSync(i)}catch{}throw new ye("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Am(){return uE.randomBytes(32).toString("hex")}function xm(t){let e=Pm();if(!fE.test(t))throw new ye("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);mc(e,t,384)}function Cm(t){let e=Tm();if(!Number.isInteger(t)||t<1||t>65535)throw new ye("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);mc(e,String(t),420)}function Im(t){let e=fc();if(!Number.isInteger(t)||t<1)throw new ye("write_failed",e,`pid must be a positive integer but received ${t}`);mc(e,String(t),420)}function hc(t){for(let e of[Pm(),Tm(),fc()])try{ee.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Om(){let t=ne(),e;try{e=ee.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ee.unlinkSync(Dt.join(t,n))}catch{}}var dc=new Set;function mE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function hE(t){let e;try{e=ee.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function Nm(t){let e=dE(),n=fc(),r=t?.processIsAlive??mE;if(dc.has(e))throw new ye("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=ee.openSync(e,ee.constants.O_WRONLY|ee.constants.O_CREAT|ee.constants.O_EXCL,384);if(ee.closeSync(i),process.platform!=="win32")try{ee.chmodSync(e,384)}catch{}return dc.add(e),pE(e)}catch(i){if(i.code!=="EEXIST")throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=hE(n);if(a.kind==="missing")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new ye("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ee.unlinkSync(e)}catch{}try{ee.unlinkSync(n)}catch{}}throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function pE(t){let e=!1;return{release(){if(!e){e=!0,dc.delete(t);try{ee.unlinkSync(t)}catch{}}}}}import*as Bm from"node:http";import{Buffer as yc}from"node:buffer";import*as qm from"node:crypto";var pn=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Um="0.1.0-alpha.1",Mm=`aifight-runtime/${Um}`,gE="127.0.0.1",yE=0,_E=1048576,wE=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Hm(t){return t.split("/").filter(e=>e.length>0)}function Te(t){let e=Hm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function vE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function Lm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=yc.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function jm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function pc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function Dm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function Fm(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function bE(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function Wm(t){let e=t.host??gE,n=t.port??yE,r=t.bodyLimitBytes??_E,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Te("/v1/health"),handler:p},{method:"GET",pattern:Te("/v1/agents"),handler:y},{method:"GET",pattern:Te("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Te("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Te("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Te("/v1/agents/:name/schedule"),handler:k},{method:"POST",pattern:Te("/v1/agents/:name/schedule"),handler:G},{method:"POST",pattern:Te("/v1/agents/:name/schedule/pause"),handler:Q},{method:"POST",pattern:Te("/v1/agents/:name/schedule/resume"),handler:oe},{method:"POST",pattern:Te("/v1/shutdown"),handler:rt},{method:"POST",pattern:Te("/v1/agents"),handler:h("M1-18")},{method:"DELETE",pattern:Te("/v1/agents/:name"),handler:h("M1-18")},{method:"POST",pattern:Te("/v1/agents/:name/setup"),handler:h("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let x=E.slice(7),$=t.tokenSource();if($===null)return{ok:!1,reason:"token_unset"};let j=yc.from(x,"utf8"),X=yc.from($,"utf8");return j.length!==X.length?{ok:!1,reason:"token_mismatch"}:qm.timingSafeEqual(j,X)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,x){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",Mm),w.statusCode=E,w.end(JSON.stringify(x)))}function d(w,E,x,$,j){u(w,E,j===void 0?{error:{code:x,message:$}}:{error:{code:x,message:$,details:j}})}function p(w){u(w.res,200,{status:"ok",version:Um,uptimeMs:o.now()-i})}function h(w){return E=>{let x=E.url.pathname;throw new B(501,"not_implemented",`${x} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",Mm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Fm);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,x;try{x=t.router.getAgent({name:E})}catch(j){throw pc(j)?new B(404,"not_found",`agent '${E}' not found`):j}let $=x.snapshot();u(w.res,200,{agent:Fm($)})}async function S(w){let E=w.params.name,x=await Lm(w.req,r);jm(x,["game"],"/v1/agents/:name/join");let $=x;if(typeof $.game!="string"||$.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if($.mode!==void 0&&typeof $.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if($.one_shot!==void 0&&typeof $.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if($.oneShot!==void 0&&typeof $.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=$.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let X=$.one_shot??$.oneShot;try{t.router.joinQueue({name:E},$.game,$.mode,{...X!==void 0?{oneShot:X}:{},...typeof j=="number"?{count:j}:{}})}catch(K){throw pc(K)?new B(404,"not_found",`agent '${E}' not found`):K}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(x){throw pc(x)?new B(404,"not_found",`agent '${E}' not found`):x}g(w.res)}function k(w){let E=w.params.name,x=f(E),$=m(E),j=bE(x.snapshot());u(w.res,200,{schedule:$,snapshot:j})}async function G(w){let E=w.params.name,x=f(E),$=await Lm(w.req,r),j;if($===null)j=null;else{jm($,["enabled","timezone","days"],"/v1/agents/:name/schedule");let X=$;if(typeof X.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof X.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof X.days!="object"||X.days===null||Array.isArray(X.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=$}try{x.setSchedule(j)}catch(X){let K=Dm(X);throw K||X}a.set(E,j),g(w.res)}function Q(w){Ge(w,!1)}function oe(w){Ge(w,!0)}function Ge(w,E){let x=w.params.name,$=f(x),j=m(x);if(j===null){let K=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${K}; POST /schedule first or configure initial schedule`)}let X={...j,enabled:E};try{$.setSchedule(X)}catch(K){let Xr=Dm(K);throw Xr||K}a.set(x,X),g(w.res)}function rt(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${gc(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function Zn(w,E){let x=o.now(),$=w.method??"GET",j=w.url??"/",X=`http://${w.headers.host??"localhost"}`,K;try{K=new URL(j,X)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${$} ${j} -> 400 (${o.now()-x}ms)`,method:$,path:j,status:400,durationMs:o.now()-x});return}let Xr=Hm(K.pathname),er=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${$} ${K.pathname}: auth failed (${Ee.reason})`,method:$,path:K.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let di=s.map(bt=>({route:bt,params:vE(bt.pattern,Xr)})).filter(bt=>bt.params!==null);if(di.length===0)throw new B(404,"not_found","path not found");let fi=di.find(bt=>bt.route.method===$);if(!fi){let bt=di.map(mi=>mi.route.method).filter((mi,mh,hh)=>hh.indexOf(mi)===mh).join(", ");throw E.headersSent||E.setHeader("Allow",bt),new B(405,"method_not_allowed",`method ${$} not allowed`)}c({level:"info",code:"request_received",message:`${$} ${K.pathname}`,method:$,path:K.pathname}),await fi.route.handler({req:w,res:E,url:K,params:fi.params}),er=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),er=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${$} ${K.pathname}: ${gc(Ee)}`,method:$,path:K.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),er=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${$} ${K.pathname} -> ${er} (${o.now()-x}ms)`,method:$,path:K.pathname,status:er,durationMs:o.now()-x})}}let ze=Bm.createServer((w,E)=>{Zn(w,E).catch(x=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${gc(x)}`,method:w.method,path:w.url,cause:x}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),te="pre-listen",Ft=null,gn=null,Qr=null;function uh(){return te==="listening"?Promise.reject(new pn("invalid_state","server already listening")):te==="closing"||te==="closed"||te==="bind-failed"?Promise.reject(new pn("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let x=$=>{te="bind-failed",E(new pn("bind_failed",`failed to bind ${e}:${n}: ${$.message}`,$))};ze.once("error",x),ze.listen({host:e,port:n},()=>{ze.off("error",x);let $=ze.address();if(typeof $=="string"||$===null){te="bind-failed",E(new pn("bind_failed","unexpected listen address shape from server.address()"));return}Ft=$.address,gn=$.port,te="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Ft}:${gn}`,host:Ft,port:gn}),w(gn)})})}function dh(){return te!=="listening"||Ft===null||gn===null?null:{host:Ft,port:gn}}function fh(){return te==="pre-listen"||te==="bind-failed"?(te="closed",Promise.resolve()):te==="closed"?Promise.resolve():(te==="closing"&&Qr||(te="closing",Qr=new Promise(w=>{let E=!1,x=()=>{E||(E=!0,clearTimeout(j),te="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},$=ze.closeAllConnections,j=setTimeout(()=>{if(typeof $=="function")try{$.call(ze)}catch{}x()},wE);j.unref(),ze.close(()=>x())})),Qr)}return{listen:uh,address:dh,close:fh}}function gc(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function _c(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function Vm(t,e){if(e.type==="start")return U(_c(e));if(t.phase==="closed")return e.type==="stop"?U(t):Ve(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return SE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return EE(t);case"command.confirm_match":return $E(t,e.confirmId);case"ws.message":return kE(t,e.message,e.now);case"decision.ready":return IE(t,e.action);case"decision.failed":return OE(t,e.reason);case"reconnect.event":return jE(t,e.event);case"reconnect.close":return DE(t,e.info);case"stop":return U({...t,phase:"closed",transport:"closed"})}}function SE(t,e,n,r){if(!t.availableGames.includes(e))return Ve(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Kr(n),...r===!0?{one_shot:!0}:{}};return U({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function EE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ve(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function $E(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ve(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):U({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function kE(t,e,n){switch(e.type){case"queue_joined":return RE(t,e);case"queue_left":return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return PE(t,e);case"match_cancelled":return TE(t,e);case"game_start":return AE(t,e,n);case"game_state":return xE(t,e);case"action_request":return CE(t,e);case"game_over":return NE(t,e);case"error":return ME(t,e);case"event":return LE(t,e);default:return Ve(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function RE(t,e){return U({...t,phase:"queuing",queue:{game:e.data.game,mode:Kr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function PE(t,e){let n={game:e.data.game,mode:Kr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?U({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):U({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[We("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function TE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Kr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Kr(e.data.mode)}:n;return U({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function AE(t,e,n){return U({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function xE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function CE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ve(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function IE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):U({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function OE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):U(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function NE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ve(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function ME(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return U({...t,lastError:n},[We("error","server.error",n)])}function LE(t,e){return U(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function jE(t,e){return e.type==="attempt-success"?U({...t,transport:"connected"}):e.type==="attempt-start"?U({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?U({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):U({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function DE(t,e){return U({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function U(t,e=[]){return{state:t,effects:e}}function Ve(t,e,n){return U(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Kr(t){return t&&t.length>0?t:"ranked"}var Xn=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Jr=class extends Xn{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Yr=class extends Xn{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},si=class extends Xn{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},wc=class extends Xn{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},ai=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new si(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Jr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Da,n;try{n=await e(this.#e.ws)}catch(r){throw new Jr(`failed to start agent '${this.#e.name}': ${ii(r)}`,r)}if(n.welcome===null)throw new Jr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=_c({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#$()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#k();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#$()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=FE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#h({type:"runtime_status",data:BE(r,n)})}catch(r){this.#h({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Gm(`readiness check failed: ${ii(r)}`)}})}}#s(e){let n=this.#S(),r=Vm(n,e);this.#n=r.state,this.#f(),this.#p(r.effects)}#p(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${ii(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#h(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#h(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${ii(r)}`,cause:new wc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Yr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new si(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Yr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Yr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#k(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#$(){return this.#e.now?.()??Date.now()}};function ii(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function FE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function BE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Gm(n.detail)),n}function Gm(t){return t.length>240?t.slice(0,240):t}function zm(t){return{async decide(e){let n=VE(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:GE(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return ci(n,o,r.state)}}return qE({game:n,raw:s,legalActions:o,publicState:r.state})}}}function Km(){return{name:"mock",async decide(t){return ci(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function qE(t){if(typeof t.raw!="string")return WE(t.raw,t.legalActions)??ci(t.game,t.legalActions,t.publicState);let e=UE(t.game,t.raw,t.legalActions);return e!==null?e:ci(t.game,t.legalActions,t.publicState)}function UE(t,e,n){let r=HE(e),o=t==="texas_holdem"?Wa(r,n):t==="liars_dice"?Ga(r,n):za(r,n);return o.kind==="ok"?o.action:null}function HE(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function WE(t,e){let n=e.find(o=>zE(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function ci(t,e,n){return t==="texas_holdem"?Fa({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?qa({publicState:n,legalActions:e,yourPlayerId:"p0"}):Ua({publicState:n,legalActions:e,yourPlayerId:"p0"})}function VE(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function GE(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function zE(t,e){return JSON.stringify(t)===JSON.stringify(e)}var KE="http://127.0.0.1:18789",JE="openclaw/default";function Jm(t){let e=(t.baseUrl??KE).replace(/\/+$/,""),n=t.model??JE,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:YE(t,o),body:JSON.stringify({model:n,input:QE(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=XE(s);return ZE(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function YE(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function QE(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
190
- `)}function XE(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function ZE(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("OpenClaw response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;let n=e.output,r=e$(n);if(r)return r;let o=e.choices,i=t$(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function e$(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
191
- `):null}function t$(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var n$="http://127.0.0.1:8642",r$="hermes-agent";function Ym(t){let e=(t.baseUrl??n$).replace(/\/+$/,""),n=t.model??r$,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:o$(t,o),body:JSON.stringify({model:n,input:i$(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=s$(s);return a$(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function o$(t,e){return{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`,"X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`}:{}}}function i$(t){return["You are an AIFight game-playing Hermes Agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
192
- `)}function s$(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function a$(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("Hermes response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;let n=e.output,r=c$(n);if(r)return r;let o=e.choices,i=l$(o);if(i)return i;throw new Error("Hermes response did not contain text")}function c$(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(typeof r=="string"){e.push(r);continue}if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
193
- `):null}function l$(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var li=class{#e;#t=null;#n=null;constructor(e){this.#e=e}async start(){if(this.#t!==null)return this.#t.snapshot();let e=this.#e.runtimeProvider??g$(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:zf},r=new ai({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:zm(e),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onReadinessCheck:async i=>this.#c(e,i),onNotify:i=>{this.#r(i.level,i.code,i.message)},onResult:(i,s)=>{this.#r("info","bridge.match_complete",d$(this.#e.config,i,s.game)),this.#a()},onFallbackRequired:i=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${i.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=r;let o=await r.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let i=this.#e.autoJoinOneShot===!0;r.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:i}),this.#r("info","bridge.queue_joined",i?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return o}async stop(){this.#t!==null&&(await this.#t.stop("bridge stop"),this.#t=null,this.#n=null)}snapshot(){return this.#t?.snapshot()??null}joinQueue(e,n,r={}){if(r.oneShot===!0||(r.count??1)>1){this.requestManualMatches(e,n,r.count??1);return}this.#o().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#o();this.#n=null,e.leaveQueue()}requestManualMatches(e,n="ranked",r=1){if(!Number.isInteger(r)||r<1||r>20)throw new Error("manual match count must be an integer between 1 and 20");let o=this.#o(),i=o.snapshot().state?.phase;if(i==="confirming"||i==="matching"||i==="in_match"||i==="deciding"||i==="reporting")throw new Error("agent is already in or entering a match; try again after the current match completes");this.#n=r>1?{game:e,mode:n,remainingAfterCurrent:r-1}:null,o.joinQueue(e,n,{oneShot:!0}),this.#r("info","bridge.queue_joined",r===1?`Joined ${e} for one manual match`:`Joined ${e} for ${r} manual matches`)}#r(e,n,r){this.#e.onLog?.({level:e,code:n,message:r})}#o(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#a(){let e=this.#n,n=this.#t;if(!(e===null||n===null)){if(e.remainingAfterCurrent<=0){this.#n=null;return}try{n.joinQueue(e.game,e.mode,{oneShot:!0}),e.remainingAfterCurrent-=1,this.#r("info","bridge.queue_joined",e.remainingAfterCurrent===0?`Joined ${e.game} for the final manual match in this request`:`Joined ${e.game} for the next manual match; ${e.remainingAfterCurrent} remaining after this one`)}catch(r){this.#n=null,this.#r("error","bridge.manual_requeue_failed",`Could not request the next manual match: ${r instanceof Error?r.message:String(r)}`)}}}async#c(e,n){let r=u$(n),o=new Date().toISOString();if(!e.healthCheck)return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:"runtime provider does not expose a health check"};try{let i=await e.healthCheck();return{request_id:r,ready:i,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:i?"ready":"local runtime health check returned false"}}catch(i){return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:`local runtime health check failed: ${i instanceof Error?i.message:String(i)}`}}}};function u$(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function d$(t,e,n){let r=[`Match complete: ${p$(n)}`,`Result: ${f$(t.agentId,e)}`],o=h$(t.baseUrl,e.data.replay_url);return o!==void 0?r.push(`Replay: ${o}`):e.data.forfeit_reason!==void 0&&r.push(`Forfeit reason: ${e.data.forfeit_reason}`),(t.autoDailyLimit??0)===2&&r.push("","Your Agent is set to 2 automatic ranked matches per day.","To compete more often:"," aifight set daily 4"),r.join(`
194
- `)}function f$(t,e){let n=e.data.players.find(i=>i.agent_id===t);if(n===void 0)return"completed";if(e.data.forfeited_by===n.player_id)return"forfeit";if(e.data.forfeit_reason!==void 0)return"opponent forfeit";if(e.data.result.is_draw)return"draw";let r=e.data.result.payoffs[n.player_id];if(typeof r!="number")return e.data.result.winner===n.player_id?"1st place":"completed";let o=Object.values(e.data.result.payoffs).filter(i=>i>r).length;return`${m$(o+1)} place`}function m$(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function h$(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function p$(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup";default:return"AIFight match"}}function g$(t){return t.runtimeType==="mock"?Km():t.runtimeType==="openclaw"?Jm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):Ym({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}var y$=["usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," If aifight.service is already running, this command refuses unless --force is set."].join(`
195
- `);async function Qm(t,e){J(t,0,0,y$);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await k$(e))throw new z("bridge_already_running","aifight.service is already running.",{hint:"Use `aifight start` to request matches through the running service. Use `aifight run --force` only for advanced debugging."});if(n&&process.stdin.isTTY&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&(e.stdout(["AIFight service may already be running.","Starting a second foreground Bridge can duplicate match handling.",""].join(`
196
- `)),!await P$(e,"Continue anyway? [y/N] ")))return 0;let r=ae();return _$({config:r,env:e})}async function _$(t){let{config:e,env:n}=t,r=await Lt({baseUrl:e.baseUrl,currentVersion:Se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
209
+ `)}return 0}function uE(){try{return ce()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new W("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function dE(t,e){if(t.length===0)return{game:Pm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Rm(n);if(i!==null)return{game:Pm(e.autoGames),count:i};if(at(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ai)}let r=t[1];if(!at(n))throw new O(`unsupported game '${n}'`,ai);let o=Rm(r);if(o===null)throw new O(`N must be an integer between 1 and ${fc}`,ai);return{game:n,count:o}}function Rm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>fc?null:e}function Pm(t){let e=(t??pe).filter(at),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}function fE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function mE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function pE(t){try{let e=await pn(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof te))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function hE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Ft from"node:path";import ee from"node:fs";import gE from"node:crypto";var ye=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Cm(){return Ft.join(re(),"token")}function xm(){return Ft.join(re(),"port")}function pc(){return Ft.join(re(),"pid")}function yE(){return Ft.join(re(),"lock")}var Am=0,_E=/^[0-9a-f]{64}$/;function hc(t,e,n){let r=Ft.dirname(t),o=Ft.basename(t);Am+=1;let i=Ft.join(r,`${o}.${process.pid}.${Am}.tmp`),s;try{if(s=ee.openSync(i,"w",n),ee.writeSync(s,e),ee.closeSync(s),s=void 0,process.platform!=="win32")try{ee.chmodSync(i,n)}catch{}ee.renameSync(i,t)}catch(a){if(s!==void 0)try{ee.closeSync(s)}catch{}try{ee.unlinkSync(i)}catch{}throw new ye("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Im(){return gE.randomBytes(32).toString("hex")}function Om(t){let e=Cm();if(!_E.test(t))throw new ye("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);hc(e,t,384)}function Nm(t){let e=xm();if(!Number.isInteger(t)||t<1||t>65535)throw new ye("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);hc(e,String(t),420)}function Mm(t){let e=pc();if(!Number.isInteger(t)||t<1)throw new ye("write_failed",e,`pid must be a positive integer but received ${t}`);hc(e,String(t),420)}function gc(t){for(let e of[Cm(),xm(),pc()])try{ee.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Lm(){let t=re(),e;try{e=ee.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ee.unlinkSync(Ft.join(t,n))}catch{}}var mc=new Set;function wE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function vE(t){let e;try{e=ee.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function jm(t){let e=yE(),n=pc(),r=t?.processIsAlive??wE;if(mc.has(e))throw new ye("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=ee.openSync(e,ee.constants.O_WRONLY|ee.constants.O_CREAT|ee.constants.O_EXCL,384);if(ee.closeSync(i),process.platform!=="win32")try{ee.chmodSync(e,384)}catch{}return mc.add(e),bE(e)}catch(i){if(i.code!=="EEXIST")throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=vE(n);if(a.kind==="missing")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new ye("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ee.unlinkSync(e)}catch{}try{ee.unlinkSync(n)}catch{}}throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function bE(t){let e=!1;return{release(){if(!e){e=!0,mc.delete(t);try{ee.unlinkSync(t)}catch{}}}}}import*as Hm from"node:http";import{Buffer as wc}from"node:buffer";import*as Gm from"node:crypto";var _n=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Wm="0.1.0-alpha.3",Dm=`aifight-runtime/${Wm}`,SE="127.0.0.1",EE=0,kE=1048576,$E=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Vm(t){return t.split("/").filter(e=>e.length>0)}function Ae(t){let e=Vm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function RE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function Fm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=wc.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Bm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function yc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function qm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function Um(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function PE(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function zm(t){let e=t.host??SE,n=t.port??EE,r=t.bodyLimitBytes??kE,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Ae("/v1/health"),handler:h},{method:"GET",pattern:Ae("/v1/agents"),handler:y},{method:"GET",pattern:Ae("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Ae("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Ae("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Ae("/v1/agents/:name/schedule"),handler:$},{method:"POST",pattern:Ae("/v1/agents/:name/schedule"),handler:z},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/pause"),handler:Q},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/resume"),handler:ie},{method:"POST",pattern:Ae("/v1/shutdown"),handler:it},{method:"POST",pattern:Ae("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:Ae("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:Ae("/v1/agents/:name/setup"),handler:p("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let C=E.slice(7),k=t.tokenSource();if(k===null)return{ok:!1,reason:"token_unset"};let j=wc.from(C,"utf8"),X=wc.from(k,"utf8");return j.length!==X.length?{ok:!1,reason:"token_mismatch"}:Gm.timingSafeEqual(j,X)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,C){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",Dm),w.statusCode=E,w.end(JSON.stringify(C)))}function d(w,E,C,k,j){u(w,E,j===void 0?{error:{code:C,message:k}}:{error:{code:C,message:k,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Wm,uptimeMs:o.now()-i})}function p(w){return E=>{let C=E.url.pathname;throw new B(501,"not_implemented",`${C} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",Dm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Um);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,C;try{C=t.router.getAgent({name:E})}catch(j){throw yc(j)?new B(404,"not_found",`agent '${E}' not found`):j}let k=C.snapshot();u(w.res,200,{agent:Um(k)})}async function S(w){let E=w.params.name,C=await Fm(w.req,r);Bm(C,["game"],"/v1/agents/:name/join");let k=C;if(typeof k.game!="string"||k.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if(k.mode!==void 0&&typeof k.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if(k.one_shot!==void 0&&typeof k.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if(k.oneShot!==void 0&&typeof k.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=k.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let X=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...X!==void 0?{oneShot:X}:{},...typeof j=="number"?{count:j}:{}})}catch(K){throw yc(K)?new B(404,"not_found",`agent '${E}' not found`):K}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(C){throw yc(C)?new B(404,"not_found",`agent '${E}' not found`):C}g(w.res)}function $(w){let E=w.params.name,C=f(E),k=m(E),j=PE(C.snapshot());u(w.res,200,{schedule:k,snapshot:j})}async function z(w){let E=w.params.name,C=f(E),k=await Fm(w.req,r),j;if(k===null)j=null;else{Bm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let X=k;if(typeof X.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof X.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof X.days!="object"||X.days===null||Array.isArray(X.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{C.setSchedule(j)}catch(X){let K=qm(X);throw K||X}a.set(E,j),g(w.res)}function Q(w){ze(w,!1)}function ie(w){ze(w,!0)}function ze(w,E){let C=w.params.name,k=f(C),j=m(C);if(j===null){let K=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${K}; POST /schedule first or configure initial schedule`)}let X={...j,enabled:E};try{k.setSchedule(X)}catch(K){let eo=qm(K);throw eo||K}a.set(C,X),g(w.res)}function it(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${_c(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function nr(w,E){let C=o.now(),k=w.method??"GET",j=w.url??"/",X=`http://${w.headers.host??"localhost"}`,K;try{K=new URL(j,X)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${k} ${j} -> 400 (${o.now()-C}ms)`,method:k,path:j,status:400,durationMs:o.now()-C});return}let eo=Vm(K.pathname),rr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${K.pathname}: auth failed (${Ee.reason})`,method:k,path:K.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let pi=s.map(bt=>({route:bt,params:RE(bt.pattern,eo)})).filter(bt=>bt.params!==null);if(pi.length===0)throw new B(404,"not_found","path not found");let hi=pi.find(bt=>bt.route.method===k);if(!hi){let bt=pi.map(gi=>gi.route.method).filter((gi,gp,yp)=>yp.indexOf(gi)===gp).join(", ");throw E.headersSent||E.setHeader("Allow",bt),new B(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${K.pathname}`,method:k,path:K.pathname}),await hi.route.handler({req:w,res:E,url:K,params:hi.params}),rr=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),rr=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${K.pathname}: ${_c(Ee)}`,method:k,path:K.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),rr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${K.pathname} -> ${rr} (${o.now()-C}ms)`,method:k,path:K.pathname,status:rr,durationMs:o.now()-C})}}let Ke=Hm.createServer((w,E)=>{nr(w,E).catch(C=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${_c(C)}`,method:w.method,path:w.url,cause:C}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),ne="pre-listen",Bt=null,wn=null,Zr=null;function mp(){return ne==="listening"?Promise.reject(new _n("invalid_state","server already listening")):ne==="closing"||ne==="closed"||ne==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let C=k=>{ne="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Ke.once("error",C),Ke.listen({host:e,port:n},()=>{Ke.off("error",C);let k=Ke.address();if(typeof k=="string"||k===null){ne="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Bt=k.address,wn=k.port,ne="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Bt}:${wn}`,host:Bt,port:wn}),w(wn)})})}function pp(){return ne!=="listening"||Bt===null||wn===null?null:{host:Bt,port:wn}}function hp(){return ne==="pre-listen"||ne==="bind-failed"?(ne="closed",Promise.resolve()):ne==="closed"?Promise.resolve():(ne==="closing"&&Zr||(ne="closing",Zr=new Promise(w=>{let E=!1,C=()=>{E||(E=!0,clearTimeout(j),ne="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Ke.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Ke)}catch{}C()},$E);j.unref(),Ke.close(()=>C())})),Zr)}return{listen:mp,address:pp,close:hp}}function _c(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function vc(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function Km(t,e){if(e.type==="start")return U(vc(e));if(t.phase==="closed")return e.type==="stop"?U(t):Ve(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return TE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return AE(t);case"command.confirm_match":return CE(t,e.confirmId);case"ws.message":return xE(t,e.message,e.now);case"decision.ready":return DE(t,e.action);case"decision.failed":return FE(t,e.reason);case"reconnect.event":return HE(t,e.event);case"reconnect.close":return GE(t,e.info);case"stop":return U({...t,phase:"closed",transport:"closed"})}}function TE(t,e,n,r){if(!t.availableGames.includes(e))return Ve(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Yr(n),...r===!0?{one_shot:!0}:{}};return U({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function AE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ve(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function CE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ve(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):U({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function xE(t,e,n){switch(e.type){case"queue_joined":return IE(t,e);case"queue_left":return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return OE(t,e);case"match_cancelled":return NE(t,e);case"game_start":return ME(t,e,n);case"game_state":return LE(t,e);case"action_request":return jE(t,e);case"game_over":return BE(t,e);case"error":return qE(t,e);case"event":return UE(t,e);default:return Ve(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function IE(t,e){return U({...t,phase:"queuing",queue:{game:e.data.game,mode:Yr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function OE(t,e){let n={game:e.data.game,mode:Yr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?U({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):U({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[We("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function NE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Yr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Yr(e.data.mode)}:n;return U({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function ME(t,e,n){return U({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function LE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function jE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ve(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function DE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):U({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function FE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):U(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function BE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ve(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function qE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return U({...t,lastError:n},[We("error","server.error",n)])}function UE(t,e){return U(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function HE(t,e){return e.type==="attempt-success"?U({...t,transport:"connected"}):e.type==="attempt-start"?U({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?U({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):U({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function GE(t,e){return U({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function U(t,e=[]){return{state:t,effects:e}}function Ve(t,e,n){return U(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Yr(t){return t&&t.length>0?t:"ranked"}var tr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Qr=class extends tr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Xr=class extends tr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},li=class extends tr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},bc=class extends tr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},ui=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new li(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Qr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??qa,n;try{n=await e(this.#e.ws)}catch(r){throw new Qr(`failed to start agent '${this.#e.name}': ${ci(r)}`,r)}if(n.welcome===null)throw new Qr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=vc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#k()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#$();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#k()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=WE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#p({type:"runtime_status",data:VE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Jm(`readiness check failed: ${ci(r)}`)}})}}#s(e){let n=this.#S(),r=Km(n,e);this.#n=r.state,this.#f(),this.#h(r.effects)}#h(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${ci(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#p(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#p(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${ci(r)}`,cause:new bc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new li(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#$(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#k(){return this.#e.now?.()??Date.now()}};function ci(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function WE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function VE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Jm(n.detail)),n}function Jm(t){return t.length>240?t.slice(0,240):t}function Ym(t){return{async decide(e){let n=QE(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:XE(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return di(n,o,r.state)}}return zE({game:n,raw:s,legalActions:o,publicState:r.state})}}}function Qm(){return{name:"mock",async decide(t){return di(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function zE(t){if(typeof t.raw!="string")return YE(t.raw,t.legalActions)??di(t.game,t.legalActions,t.publicState);let e=KE(t.game,t.raw,t.legalActions);return e!==null?e:di(t.game,t.legalActions,t.publicState)}function KE(t,e,n){let r=JE(e),o=t==="texas_holdem"?za(r,n):t==="liars_dice"?Ja(r,n):Ya(r,n);return o.kind==="ok"?o.action:null}function JE(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function YE(t,e){let n=e.find(o=>ZE(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function di(t,e,n){return t==="texas_holdem"?Ua({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):Wa({publicState:n,legalActions:e,yourPlayerId:"p0"})}function QE(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function XE(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function ZE(t,e){return JSON.stringify(t)===JSON.stringify(e)}var ek="http://127.0.0.1:18789",tk="openclaw/default";function Xm(t){let e=(t.baseUrl??ek).replace(/\/+$/,""),n=t.model??tk,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:nk(t,o),body:JSON.stringify({model:n,input:rk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=ok(s);return ik(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function nk(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function rk(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
210
+ `)}function ok(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function ik(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("OpenClaw response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;let n=e.output,r=sk(n);if(r)return r;let o=e.choices,i=ak(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function sk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
211
+ `):null}function ak(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var ck="http://127.0.0.1:8642",lk="hermes-agent";function Zm(t){let e=(t.baseUrl??ck).replace(/\/+$/,""),n=t.model??lk,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:uk(t,o),body:JSON.stringify({model:n,input:dk(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=fk(s);return mk(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function uk(t,e){return{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`,"X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`}:{}}}function dk(t){return["You are an AIFight game-playing Hermes Agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
212
+ `)}function fk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function mk(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("Hermes response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;let n=e.output,r=pk(n);if(r)return r;let o=e.choices,i=hk(o);if(i)return i;throw new Error("Hermes response did not contain text")}function pk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(typeof r=="string"){e.push(r);continue}if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
213
+ `):null}function hk(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var fi=class{#e;#t=null;#n=null;constructor(e){this.#e=e}async start(){if(this.#t!==null)return this.#t.snapshot();let e=this.#e.runtimeProvider??Sk(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Jf},r=new ui({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:Ym(e),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onReadinessCheck:async i=>this.#c(e,i),onNotify:i=>{this.#r(i.level,i.code,i.message)},onResult:(i,s)=>{this.#r("info","bridge.match_complete",yk(this.#e.config,i,s.game)),this.#a()},onFallbackRequired:i=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${i.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=r;let o=await r.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let i=this.#e.autoJoinOneShot===!0;r.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:i}),this.#r("info","bridge.queue_joined",i?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return o}async stop(){this.#t!==null&&(await this.#t.stop("bridge stop"),this.#t=null,this.#n=null)}snapshot(){return this.#t?.snapshot()??null}joinQueue(e,n,r={}){if(r.oneShot===!0||(r.count??1)>1){this.requestManualMatches(e,n,r.count??1);return}this.#o().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#o();this.#n=null,e.leaveQueue()}requestManualMatches(e,n="ranked",r=1){if(!Number.isInteger(r)||r<1||r>20)throw new Error("manual match count must be an integer between 1 and 20");let o=this.#o(),i=o.snapshot().state?.phase;if(i==="confirming"||i==="matching"||i==="in_match"||i==="deciding"||i==="reporting")throw new Error("agent is already in or entering a match; try again after the current match completes");this.#n=r>1?{game:e,mode:n,remainingAfterCurrent:r-1}:null,o.joinQueue(e,n,{oneShot:!0}),this.#r("info","bridge.queue_joined",r===1?`Joined ${e} for one manual match`:`Joined ${e} for ${r} manual matches`)}#r(e,n,r){this.#e.onLog?.({level:e,code:n,message:r})}#o(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#a(){let e=this.#n,n=this.#t;if(!(e===null||n===null)){if(e.remainingAfterCurrent<=0){this.#n=null;return}try{n.joinQueue(e.game,e.mode,{oneShot:!0}),e.remainingAfterCurrent-=1,this.#r("info","bridge.queue_joined",e.remainingAfterCurrent===0?`Joined ${e.game} for the final manual match in this request`:`Joined ${e.game} for the next manual match; ${e.remainingAfterCurrent} remaining after this one`)}catch(r){this.#n=null,this.#r("error","bridge.manual_requeue_failed",`Could not request the next manual match: ${r instanceof Error?r.message:String(r)}`)}}}async#c(e,n){let r=gk(n),o=new Date().toISOString();if(!e.healthCheck)return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:"runtime provider does not expose a health check"};try{let i=await e.healthCheck();return{request_id:r,ready:i,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:i?"ready":"local runtime health check returned false"}}catch(i){return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:`local runtime health check failed: ${i instanceof Error?i.message:String(i)}`}}}};function gk(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function yk(t,e,n){let r=[`Match complete: ${bk(n)}`,`Result: ${_k(t.agentId,e)}`],o=vk(t.baseUrl,e.data.replay_url);return o!==void 0?r.push(`Replay: ${o}`):e.data.forfeit_reason!==void 0&&r.push(`Forfeit reason: ${e.data.forfeit_reason}`),(t.autoDailyLimit??0)===2&&r.push("","Your Agent is set to 2 automatic ranked matches per day.","To compete more often:"," aifight set daily 4"),r.join(`
214
+ `)}function _k(t,e){let n=e.data.players.find(i=>i.agent_id===t);if(n===void 0)return"completed";if(e.data.forfeited_by===n.player_id)return"forfeit";if(e.data.forfeit_reason!==void 0)return"opponent forfeit";if(e.data.result.is_draw)return"draw";let r=e.data.result.payoffs[n.player_id];if(typeof r!="number")return e.data.result.winner===n.player_id?"1st place":"completed";let o=Object.values(e.data.result.payoffs).filter(i=>i>r).length;return`${wk(o+1)} place`}function wk(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function vk(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function bk(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup";default:return"AIFight match"}}function Sk(t){return t.runtimeType==="mock"?Qm():t.runtimeType==="openclaw"?Xm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):Zm({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}var Ek=["usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," If aifight.service is already running, this command refuses unless --force is set."].join(`
215
+ `);async function ep(t,e){J(t,0,0,Ek);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await xk(e))throw new W("bridge_already_running","aifight.service is already running.",{hint:"Use `aifight start` to request matches through the running service. Use `aifight run --force` only for advanced debugging."});if(n&&process.stdin.isTTY&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&(e.stdout(["AIFight service may already be running.","Starting a second foreground Bridge can duplicate match handling.",""].join(`
216
+ `)),!await Ok(e,"Continue anyway? [y/N] ")))return 0;let r=ce();return kk({config:r,env:e})}async function kk(t){let{config:e,env:n}=t,r=await jt({baseUrl:e.baseUrl,currentVersion:Se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
197
217
  `),n.stderr(`Update command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
198
218
  `),1;r.status==="update_recommended"&&(n.stdout(`[warn] bridge.update: ${r.message}
199
219
  `),n.stdout(`[warn] update command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
200
- `)),ot(),Om();let o=null,i=null,s=new li({config:e,...w$(e),onLog:a=>{S$(a,n)}});try{o=Nm(),Im(process.pid);let a=Am();n.stdout(b$(e)),await s.start(),i=Wm({tokenSource:()=>a,router:v$(e,s),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let c=await i.listen();return xm(a),Cm(c),n.stdout(`Bridge online. Press Ctrl-C to stop.
201
- `),await R$(async()=>{await i?.close(),i=null,await s.stop(),hc({onLog:l=>n.stderr(`warning: ${l}
202
- `)}),o?.release(),o=null}),0}catch(a){throw await i?.close().catch(()=>{}),await s.stop().catch(()=>{}),hc({onLog:()=>{}}),o?.release(),a instanceof ye?a.kind==="lock_held_by_other"?new z("bridge_already_running",`AIFight Bridge is already running${a.heldByPid!==void 0?` (PID ${a.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new z("bridge_runtime_files_failed",a.message):a}}function w$(t){let e=(t.autoDailyLimit??0)>0?$$(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function v$(t,e){return{listAgents:()=>{let n=e.snapshot();return n===null?[]:[n]},getAgent:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});let r=e.snapshot();if(r===null)throw Object.assign(new Error("bridge runner is not started"),{kind:"router_agent_not_found"});return{snapshot:()=>e.snapshot()??r}},joinQueue:(n,r,o,i)=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});if(!it(r))throw new Error(`unsupported game '${r}'`);e.joinQueue(r,o,{...i?.oneShot!==void 0?{oneShot:i.oneShot}:{},...i?.count!==void 0?{count:i.count}:{}})},leaveQueue:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});e.leaveQueue()}}}function b$(t){let e=(t.autoDailyLimit??0)>0?`Automatic ranked matches: ${t.autoDailyLimit} per day`:"Automatic ranked matches: disabled; staying online for challenges and manual starts";return`${["Starting AIFight Bridge.","",`Agent: ${t.agentName}`,`Runtime: ${E$(t.runtimeType)} at ${t.runtimeLocalUrl}`,`AIFight: ${t.baseUrl}`,e,"","Safety boundary: this opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","Your model/provider keys stay inside your local runtime.",""].join(`
220
+ `)),st(),Lm();let o=null,i=null,s=new fi({config:e,...$k(e),onLog:a=>{Tk(a,n)}});try{o=jm(),Mm(process.pid);let a=Im();n.stdout(Pk(e)),await s.start(),i=zm({tokenSource:()=>a,router:Rk(e,s),onLog:l=>{n.onLog?.({code:`control.${l.code}`,message:l.message})}});let c=await i.listen();return Om(a),Nm(c),n.stdout(`Bridge online. Press Ctrl-C to stop.
221
+ `),await Ik(async()=>{await i?.close(),i=null,await s.stop(),gc({onLog:l=>n.stderr(`warning: ${l}
222
+ `)}),o?.release(),o=null}),0}catch(a){throw await i?.close().catch(()=>{}),await s.stop().catch(()=>{}),gc({onLog:()=>{}}),o?.release(),a instanceof ye?a.kind==="lock_held_by_other"?new W("bridge_already_running",`AIFight Bridge is already running${a.heldByPid!==void 0?` (PID ${a.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new W("bridge_runtime_files_failed",a.message):a}}function $k(t){let e=(t.autoDailyLimit??0)>0?Ck(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function Rk(t,e){return{listAgents:()=>{let n=e.snapshot();return n===null?[]:[n]},getAgent:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});let r=e.snapshot();if(r===null)throw Object.assign(new Error("bridge runner is not started"),{kind:"router_agent_not_found"});return{snapshot:()=>e.snapshot()??r}},joinQueue:(n,r,o,i)=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});if(!at(r))throw new Error(`unsupported game '${r}'`);e.joinQueue(r,o,{...i?.oneShot!==void 0?{oneShot:i.oneShot}:{},...i?.count!==void 0?{count:i.count}:{}})},leaveQueue:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});e.leaveQueue()}}}function Pk(t){let e=(t.autoDailyLimit??0)>0?`Automatic ranked matches: ${t.autoDailyLimit} per day`:"Automatic ranked matches: disabled; staying online for challenges and manual starts";return`${["Starting AIFight Bridge.","",`Agent: ${t.agentName}`,`Runtime: ${Ak(t.runtimeType)} at ${t.runtimeLocalUrl}`,`AIFight: ${t.baseUrl}`,e,"","Safety boundary: this opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","Your model/provider keys stay inside your local runtime.",""].join(`
203
223
  `)}
204
- `}function S$(t,e){if(t.code==="fsm.game_state"||t.code==="server.event"||t.code==="bridge.connected")return;if(t.code==="bridge.queue_joined"){e.stdout(`${t.message}
224
+ `}function Tk(t,e){if(t.code==="fsm.game_state"||t.code==="server.event"||t.code==="bridge.connected")return;if(t.code==="bridge.queue_joined"){e.stdout(`${t.message}
205
225
  `);return}if(t.code==="bridge.match_complete"){e.stdout(`
206
226
  ${t.message}
207
227
  `);return}let r=`${t.level==="error"?"error":t.level==="warning"?"warning":"info"}: ${t.message}
208
- `;t.level==="error"?e.stderr(r):e.stdout(r)}function E$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function $$(t){let e=(t??he).filter(it),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}async function k$(t){try{let e=await Kn(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof ce,!1}}async function R$(t){await new Promise(e=>{let n=!1,r=async()=>{n||(n=!0,process.off("SIGINT",r),process.off("SIGTERM",r),await t(),e())};process.on("SIGINT",r),process.on("SIGTERM",r)})}async function P$(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var T$="usage: aifight status";async function Xm(t,e){J(t,0,0,T$);let n=C$();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:Se})+`
228
+ `;t.level==="error"?e.stderr(r):e.stdout(r)}function Ak(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function Ck(t){let e=(t??pe).filter(at),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}async function xk(t){try{let e=await pn(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof te,!1}}async function Ik(t){await new Promise(e=>{let n=!1,r=async()=>{n||(n=!0,process.off("SIGINT",r),process.off("SIGTERM",r),await t(),e())};process.on("SIGINT",r),process.on("SIGTERM",r)})}async function Ok(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var Nk="usage: aifight status",Mk=1500;async function tp(t,e){J(t,0,0,Nk);let n=qk();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:Se})+`
209
229
  `):(e.stdout(`AIFight status
210
230
 
211
231
  `),e.stdout(`Bridge: not configured
212
232
  `),e.stdout(`CLI version: ${Se}
213
- `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Mt(n),o=await Lt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl});return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:Se,update:o,config:r})+`
233
+ `),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Lt(n),o=await jt({baseUrl:n.baseUrl,currentVersion:Se,fetchImpl:e.fetchImpl}),i=await Lk(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:Se,update:o,platformAgentStatus:i,config:r})+`
214
234
  `),0):(e.stdout(`AIFight status
215
235
 
216
236
  `),e.stdout(`Agent: ${r.agentName}
217
- `),e.stdout(`Profile: ${r.claimToken!==void 0?"unclaimed":"claimed or paired"}
237
+ `),e.stdout(`Profile: ${Dk(i,n)}
238
+ `),i.kind==="unavailable"&&e.stdout(`Profile check: ${i.message}
218
239
  `),e.stdout(`Bridge: configured
219
240
  `),e.stdout(`CLI version: ${Se}
220
241
  `),e.stdout(`Update: ${o.message}
221
242
  `),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
222
- `),e.stdout("After updating: restart `aifight.service`, or restart `aifight run` if you are using a foreground Bridge.\n")),e.stdout(`Runtime: ${x$(r.runtimeType)} at ${r.runtimeLocalUrl}
223
- `),e.stdout(`Automatic ranked matches: ${A$(r.autoDailyLimit)}
243
+ `),e.stdout("After updating: restart `aifight.service`, or restart `aifight run` if you are using a foreground Bridge.\n")),e.stdout(`Runtime: ${Bk(r.runtimeType)} at ${r.runtimeLocalUrl}
244
+ `),e.stdout(`Automatic ranked matches: ${Fk(r.autoDailyLimit)}
224
245
  `),e.stdout(`Games: ${r.autoGames?.join(", ")??"texas_holdem, liars_dice, coup"}
225
246
  `),e.stdout(`AIFight WebSocket: ${r.wsUrl}
226
247
  `),e.stdout(`No secrets are shown here.
227
- `),0)}function A$(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function x$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function C$(){try{return ae()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var vc=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${he.join(", ")}`].join(`
228
- `);async function Zm(t,e){J(t,2,2,vc);let n=t.positional[0];if(n==="daily")return I$(t.positional[1],t,e);if(n==="game")return N$(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function I$(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,vc);let r=Number.parseInt(t,10),o=ae();await O$(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return fn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
248
+ `),0)}async function Lk(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Mk);try{let o=await e(`${t.baseUrl.replace(/\/+$/,"")}/api/agents/me/status`,{method:"GET",headers:{"X-API-Key":t.apiKey},signal:n.signal});if(!o.ok)return{kind:"unavailable",message:`server returned HTTP ${o.status}`};let i=await o.json().catch(()=>{}),s=jk(i);return s===null?{kind:"unavailable",message:"server returned an unexpected status response"}:s}catch(o){return{kind:"unavailable",message:o?.name==="AbortError"?"server check timed out":"server check unavailable"}}finally{clearTimeout(r)}}function jk(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.agent_id!="string"||typeof e.is_claimed!="boolean"||e.identity_status!=="bootstrap"&&e.identity_status!=="official"||e.status!=="ready"&&e.status!=="needs_official_name"&&e.status!=="pending_claim"?null:{kind:"ok",agentId:e.agent_id,isClaimed:e.is_claimed,identityStatus:e.identity_status,status:e.status}}function Dk(t,e){if(t.kind==="unavailable")return e.claimToken!==void 0?"unknown (claim URL saved locally)":"unknown";switch(t.status){case"ready":return"claimed, ready";case"needs_official_name":return"claimed, official name pending";case"pending_claim":return"unclaimed"}}function Fk(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function Bk(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function qk(){try{return ce()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var Sc=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${pe.join(", ")}`].join(`
249
+ `);async function np(t,e){J(t,2,2,Sc);let n=t.positional[0];if(n==="daily")return Uk(t.positional[1],t,e);if(n==="game")return Gk(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function Uk(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,Sc);let r=Number.parseInt(t,10),o=ce();await Hk(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return mn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
229
250
  `),0):(r===0?n.stdout(`Daily automatic ranked matches disabled. The Agent will not join scheduled matches unless you change this setting or manually start a match.
230
251
  `):n.stdout(`Automatic ranked matches set to ${r} per day.
231
252
  `),n.stdout(`AIFight platform policy synced.
232
- `),0)}async function O$(t,e,n){let r=e===0?{auto_requeue:!1}:{max_games_per_day:e,auto_requeue:!0},o=await n(`${t.baseUrl}/api/agents/me/policy`,{method:"PATCH",headers:{"Content-Type":"application/json","X-API-Key":t.apiKey},body:JSON.stringify(r)});if(!o.ok)throw new z("policy_sync_failed",await M$(o,`daily policy sync failed with HTTP ${o.status}`))}function N$(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new O("at least one game is required",vc);let o=new Set,i=[];for(let c of r){if(!it(c))throw new O(`unsupported game '${c}'`,`supported: ${he.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ae(),autoGames:i,updatedAt:new Date().toISOString()};return fn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
253
+ `),0)}async function Hk(t,e,n){let r=e===0?{auto_requeue:!1}:{max_games_per_day:e,auto_requeue:!0},o=await n(`${t.baseUrl}/api/agents/me/policy`,{method:"PATCH",headers:{"Content-Type":"application/json","X-API-Key":t.apiKey},body:JSON.stringify(r)});if(!o.ok)throw new W("policy_sync_failed",await Wk(o,`daily policy sync failed with HTTP ${o.status}`))}function Gk(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new O("at least one game is required",Sc);let o=new Set,i=[];for(let c of r){if(!at(c))throw new O(`unsupported game '${c}'`,`supported: ${pe.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ce(),autoGames:i,updatedAt:new Date().toISOString()};return mn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
233
254
  `),0):(n.stdout(`Automatic match games set to: ${i.join(", ")}
234
- `),0)}async function M$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var eh="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function th(t,e){J(t,1,1,eh);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new O(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,eh);let r=ae(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r.apiKey},body:JSON.stringify({game:n,accept_mode:"single"})});if(!o.ok)throw new z("challenge_create_failed",await L$(o,`challenge creation failed with HTTP ${o.status}`));let i=await o.json();if(typeof i.join_url!="string"||i.join_url.length===0)throw new z("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
255
+ `),0)}async function Wk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var rp="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function op(t,e){J(t,1,1,rp);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new O(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,rp);let r=ce(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r.apiKey},body:JSON.stringify({game:n,accept_mode:"single"})});if(!o.ok)throw new W("challenge_create_failed",await Vk(o,`challenge creation failed with HTTP ${o.status}`));let i=await o.json();if(typeof i.join_url!="string"||i.join_url.length===0)throw new W("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
235
256
  `),0):(e.stdout(`Friendly challenge created.
236
257
 
237
258
  `),e.stdout(`Game: ${n}
@@ -243,49 +264,49 @@ ${t.message}
243
264
 
244
265
  `),e.stdout(`This does not affect ratings or daily auto-play.
245
266
  `),n==="texas_holdem"&&e.stdout(`Texas Hold'em challenges start as a direct two-player friendly table; normal matchmaking still starts at four players.
246
- `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function L$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var bc="usage: aifight accept <challenge_url_or_token>";async function nh(t,e){J(t,1,1,bc);let n=j$(t.positional[0]),r=ae(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges/${encodeURIComponent(n)}/accept`,{method:"POST",headers:{"X-API-Key":r.apiKey}});if(!o.ok){let s=await F$(o,`challenge accept failed with HTTP ${o.status}`);throw new z("challenge_accept_failed",D$(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
267
+ `),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function Vk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var Ec="usage: aifight accept <challenge_url_or_token>";async function ip(t,e){J(t,1,1,Ec);let n=zk(t.positional[0]),r=ce(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges/${encodeURIComponent(n)}/accept`,{method:"POST",headers:{"X-API-Key":r.apiKey}});if(!o.ok){let s=await Jk(o,`challenge accept failed with HTTP ${o.status}`);throw new W("challenge_accept_failed",Kk(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
247
268
  `),0):(e.stdout(`Friendly challenge accepted.
248
269
 
249
270
  `),i.match_id&&e.stdout(`Match: ${i.match_id}
250
271
  `),i.message&&e.stdout(`${i.message}
251
- `),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function j$(t){let e=t.trim();if(e==="")throw new O("challenge token is required",bc);if(/^dl_[0-9a-f]{32}$/i.test(e))return e;try{let r=new URL(e).pathname.split("/").filter(Boolean),o=r.findIndex(i=>i==="challenge"||i==="duel");if(o>=0&&r[o+1]!==void 0){let i=r[o+1];if(/^dl_[0-9a-f]{32}$/i.test(i))return i}}catch{}throw new O("invalid challenge URL or token",bc)}function D$(t,e){return t===425?`${e}. Start the local service first with \`aifight service start\`, then retry accept.`:t===503?`${e}. Ask the challenge creator to keep aifight.service running.`:e}async function F$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}import ui from"node:fs";var rh="gateway.http.endpoints.responses.enabled",oh=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],ih=["usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
252
- `);async function sh(t,e){if(J(t,0,0,ih),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",ih);return e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - local bridge credentials/config"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.",""].join(`
253
- `)),await Wr(e,"Continue with local uninstall? [y/N] ")?(await B$(e),await q$(e),Jf(),lm(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
272
+ `),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function zk(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Ec);if(/^dl_[0-9a-f]{32}$/i.test(e))return e;try{let r=new URL(e).pathname.split("/").filter(Boolean),o=r.findIndex(i=>i==="challenge"||i==="duel");if(o>=0&&r[o+1]!==void 0){let i=r[o+1];if(/^dl_[0-9a-f]{32}$/i.test(i))return i}}catch{}throw new O("invalid challenge URL or token",Ec)}function Kk(t,e){return t===425?`${e}. Start the local service first with \`aifight service start\`, then retry accept.`:t===503?`${e}. Ask the challenge creator to keep aifight.service running.`:e}async function Jk(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}import mi from"node:fs";var sp="gateway.http.endpoints.responses.enabled",ap=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],cp=["usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
273
+ `);async function lp(t,e){if(J(t,0,0,cp),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",cp);return e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - local bridge credentials/config"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.",""].join(`
274
+ `)),await zr(e,"Continue with local uninstall? [y/N] ")?(await Yk(e),await Qk(e),Qf(),dm(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
254
275
  `)),0):(e.stdout(`Uninstall cancelled.
255
- `),0)}async function B$(t){try{let e=await ri(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
256
- `)}catch(e){let n=e instanceof ce||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
257
- `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function q$(t){let e=oc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
258
- `);return}e.openclaw?.responsesEnabledByAIFight&&await U$(t),e.hermes&&await H$(t,e.hermes.envPath,e.hermes.previous)}async function U$(t){if(t.stdout(["","AIFight previously enabled OpenClaw /v1/responses on this machine.","If no other local tool depends on that endpoint, I can disable it now.",""].join(`
259
- `)),!await Wr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${rh} false --strict-json
260
- `);return}if(!wt("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
261
- `);return}let n=await vt("openclaw",["config","set",rh,"false","--strict-json"]);if(hn(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
262
- `);return}let r=await vt("openclaw",["config","validate"]);hn(t,"openclaw config validate",r),await Yn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function H$(t,e,n){if(t.stdout(["",`AIFight previously updated Hermes API Server settings in ${e}.`,"I can restore the API_SERVER_* values that were active before AIFight changed them.",""].join(`
263
- `)),!await Wr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
264
- `);return}if(!ui.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
265
- `);return}let o=ui.readFileSync(e,"utf8"),i=W$(o,n);if(ui.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{ui.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
266
- `),await Yn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function W$(t,e){let n=new Set(oh),r=new Set,o=[];for(let i of t.split(/\r?\n/)){let a=i.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[3];if(!a||!n.has(a)){o.push(i);continue}r.add(a);let c=e[a];c?.wasActive&&o.push(`${a}=${c.value??""}`)}for(let i of oh){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
276
+ `),0)}async function Yk(t){try{let e=await oi(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
277
+ `)}catch(e){let n=e instanceof te||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
278
+ `),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function Qk(t){let e=ac();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
279
+ `);return}e.openclaw?.responsesEnabledByAIFight&&await Xk(t),e.hermes&&await Zk(t,e.hermes.envPath,e.hermes.previous)}async function Xk(t){if(t.stdout(["","AIFight previously enabled OpenClaw /v1/responses on this machine.","If no other local tool depends on that endpoint, I can disable it now.",""].join(`
280
+ `)),!await zr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${sp} false --strict-json
281
+ `);return}if(!Te("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
282
+ `);return}let n=await ot("openclaw",["config","set",sp,"false","--strict-json"]);if(gn(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
283
+ `);return}let r=await ot("openclaw",["config","validate"]);gn(t,"openclaw config validate",r),await Xn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function Zk(t,e,n){if(t.stdout(["",`AIFight previously updated Hermes API Server settings in ${e}.`,"I can restore the API_SERVER_* values that were active before AIFight changed them.",""].join(`
284
+ `)),!await zr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
285
+ `);return}if(!mi.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
286
+ `);return}let o=mi.readFileSync(e,"utf8"),i=e$(o,n);if(mi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{mi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
287
+ `),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function e$(t,e){let n=new Set(ap),r=new Set,o=[];for(let i of t.split(/\r?\n/)){let a=i.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[3];if(!a||!n.has(a)){o.push(i);continue}r.add(a);let c=e[a];c?.wasActive&&o.push(`${a}=${c.value??""}`)}for(let i of ap){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
267
288
  `).replace(/\n*$/,`
268
- `)}async function ch(t,e={}){let n={stdout:e.stdout??(l=>process.stdout.write(l)),stderr:e.stderr??(l=>process.stderr.write(l)),...e.hello!==void 0?{hello:e.hello}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.baseTimeoutMs!==void 0?{baseTimeoutMs:e.baseTimeoutMs}:{},...e.onLog!==void 0?{onLog:e.onLog}:{},...e.bridgeService!==void 0?{bridgeService:e.bridgeService}:{}},r=V$(t)?t.slice(2):t.slice(),i=kc(r,[{name:"json",type:"boolean"},{name:"help",type:"boolean"},{name:"version",type:"boolean"},{name:"runtime-url",type:"string"},{name:"runtime-token",type:"string"},{name:"runtime-model",type:"string"},{name:"runtime",type:"string"},{name:"name",type:"string"},{name:"force",type:"boolean"},{name:"aifight-path",type:"string"}]),s=i.flags.json===!0;if(i.errors.length>0)return lh(i.errors[0],n,s);if(i.flags.version===!0)return Ka({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Sc(n,s):K$(i.positional,n,s);if(i.positional.length===0)return Sc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await G$(a,c,n)}catch(l){return J$(l,n,s)}}function V$(t){if(t.length<2)return!1;let e=t[0]??"",n=t[1]??"";return/(^|[\\/])node(?:\.exe)?$/.test(e)?!0:/(^|[\\/])(aifight|aifight-bridge|bin\.mjs|aifight\.ts)$/.test(n)}async function G$(t,e,n){switch(t){case"version":return Ka(e,n);case"doctor":return Xf(e,n);case"register":return _m(e,n);case"connect":return Sm(e,n);case"start":return km(e,n);case"run":return Qm(e,n);case"status":return Xm(e,n);case"service":return im(e,n);case"uninstall":return sh(e,n);case"set":return Zm(e,n);case"challenge":return th(e,n);case"accept":return nh(e,n);default:throw new O(`unknown command '${t}'`)}}function ah(){return["aifight \u2014 AIFight CLI","","Commands:"," aifight register Create a private bootstrap identity and save credentials"," aifight connect <PAIRING_CODE> Authorize this machine for an existing claimed agent"," aifight start [game] [N] Request manual ranked match(es)"," aifight status Show local bridge config with secrets redacted"," aifight service <command> Install or manage aifight.service"," aifight uninstall Remove local AIFight setup from this machine"," aifight doctor Troubleshoot local bridge and runtime issues"," aifight set daily <N> Set daily automatic match preference"," aifight set game <game1,game2> Set automatic match game preference"," aifight challenge <game> Create a one-use friendly challenge URL"," aifight accept <url_or_token> Accept a received challenge URL"," aifight version Print version","","Global flags:"," --json Emit machine-readable JSON instead of human text"," --version, -v Print version"," --help, -h Print this help (or per-command help when after a command)"," --runtime-url <url> Bridge register/connect only: local Agent runtime URL"," --runtime-token <token> Bridge register/connect only: local Agent runtime token"," --runtime-model <model> Bridge register/connect only: local Agent runtime model"," --runtime <type> Bridge register only: openclaw or hermes"," --name <suggested_name> Bridge register only: suggested future public name","",`Supported games for manual matches: ${he.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
269
- `)}function Sc(t,e){return e?t.stdout(JSON.stringify({help:ah()})+`
270
- `):t.stdout(ah()+`
271
- `),0}function z$(t){switch(t[0]){case"version":return`Usage: aifight version
289
+ `)}async function dp(t,e={}){let n={stdout:e.stdout??(l=>process.stdout.write(l)),stderr:e.stderr??(l=>process.stderr.write(l)),...e.hello!==void 0?{hello:e.hello}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.baseTimeoutMs!==void 0?{baseTimeoutMs:e.baseTimeoutMs}:{},...e.onLog!==void 0?{onLog:e.onLog}:{},...e.bridgeService!==void 0?{bridgeService:e.bridgeService}:{}},r=t$(t)?t.slice(2):t.slice(),i=Pc(r,[{name:"json",type:"boolean"},{name:"help",type:"boolean"},{name:"version",type:"boolean"},{name:"runtime-url",type:"string"},{name:"runtime-token",type:"string"},{name:"runtime-model",type:"string"},{name:"runtime",type:"string"},{name:"name",type:"string"},{name:"approved-local-setup",type:"boolean"},{name:"force",type:"boolean"},{name:"aifight-path",type:"string"}]),s=i.flags.json===!0;if(i.errors.length>0)return fp(i.errors[0],n,s);if(i.flags.version===!0)return Qa({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?kc(n,s):o$(i.positional,n,s);if(i.positional.length===0)return kc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await n$(a,c,n)}catch(l){return i$(l,n,s)}}function t$(t){if(t.length<2)return!1;let e=t[0]??"",n=t[1]??"";return/(^|[\\/])node(?:\.exe)?$/.test(e)?!0:/(^|[\\/])(aifight|aifight-bridge|bin\.mjs|aifight\.ts)$/.test(n)}async function n$(t,e,n){switch(t){case"version":return Qa(e,n);case"doctor":return em(e,n);case"register":return vm(e,n);case"connect":return $m(e,n);case"start":return Tm(e,n);case"run":return ep(e,n);case"status":return tp(e,n);case"service":return am(e,n);case"uninstall":return lp(e,n);case"set":return np(e,n);case"challenge":return op(e,n);case"accept":return ip(e,n);default:throw new O(`unknown command '${t}'`)}}function up(){return["aifight \u2014 AIFight CLI","","Commands:"," aifight register Create a private bootstrap identity and save credentials"," aifight connect <PAIRING_CODE> Authorize this machine for an existing claimed agent"," aifight start [game] [N] Request manual ranked match(es)"," aifight status Show local bridge config with secrets redacted"," aifight service <command> Install or manage aifight.service"," aifight uninstall Remove local AIFight setup from this machine"," aifight doctor Troubleshoot local bridge and runtime issues"," aifight set daily <N> Set daily automatic match preference"," aifight set game <game1,game2> Set automatic match game preference"," aifight challenge <game> Create a one-use friendly challenge URL"," aifight accept <url_or_token> Accept a received challenge URL"," aifight version Print version","","Global flags:"," --json Emit machine-readable JSON instead of human text"," --version, -v Print version"," --help, -h Print this help (or per-command help when after a command)"," --runtime-url <url> Bridge register/connect only: local Agent runtime URL"," --runtime-token <token> Bridge register/connect only: local Agent runtime token"," --runtime-model <model> Bridge register/connect only: local Agent runtime model"," --runtime <type> Bridge register only: openclaw or hermes"," --name <suggested_name> Bridge register only: suggested future public name"," --approved-local-setup Bridge register only: skip repeated local prompts after user-approved Agent setup","",`Supported games for manual matches: ${pe.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
290
+ `)}function kc(t,e){return e?t.stdout(JSON.stringify({help:up()})+`
291
+ `):t.stdout(up()+`
292
+ `),0}function r$(t){switch(t[0]){case"version":return`Usage: aifight version
272
293
  Print the AIFight CLI version.`;case"doctor":return["Usage: aifight doctor"," Diagnose local bridge config, package version policy, and runtime endpoint reachability."].join(`
273
- `);case"register":return["Usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," Check the local Agent runtime, then create a private bootstrap AIFight identity and save local match credentials."," In human interactive mode, register asks which local runtime to use when none is specified."," In human mode, register asks before changing OpenClaw/Hermes local runtime settings."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Normal use requires a long-running local Bridge; register guides aifight.service installation."," Claim the agent and confirm its official Dashboard name before it can play matches or friendly challenges."," Claiming also enables dashboard management, profile settings, and recovery."," If service install is declined or unavailable, the agent is registered but not online yet."," Finish setup later with `aifight service install`, or self-manage `aifight run` as an advanced path."," Use --json for scripting; JSON mode registers and exits without service setup or foreground run prompts."," JSON/non-interactive mode defaults to openclaw when no runtime is specified."].join(`
294
+ `);case"register":return["Usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Check the local Agent runtime, then create a private bootstrap AIFight identity and save local match credentials."," In human interactive mode, register asks which local runtime to use when none is specified."," In human mode, register asks before changing OpenClaw/Hermes local runtime settings."," --approved-local-setup is for Agent-assisted setup after the human has approved the local runtime/service scope."," With --approved-local-setup, register auto-detects OpenClaw/Hermes when possible and does not ask again."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Normal use requires a long-running local Bridge; register guides aifight.service installation."," Claim the agent and confirm its official Dashboard name before it can play matches or friendly challenges."," Claiming also enables dashboard management, profile settings, and recovery."," If service install is declined or unavailable, the agent is registered but not online yet."," Finish setup later with `aifight service install`, or self-manage `aifight run` as an advanced path."," Use --json for scripting; JSON mode registers and exits without service setup or foreground run prompts."," JSON/non-interactive mode defaults to openclaw when no runtime is specified."].join(`
274
295
  `);case"connect":return["Usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," Exchange a one-time dashboard pairing code and save local bridge config."," The AIFight agent key is stored locally; runtime LLM keys are not uploaded."," Runtime token/model/url are local-only overrides; --runtime-url must point to localhost, 127.0.0.1, or [::1]."].join(`
275
- `);case"start":return["Usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running Bridge."," Manual starts do not consume the daily automatic match limit."," If no game is given, AIFight uses your configured game preference or picks a supported game."," N must be between 1 and 20.",` supported games: ${he.join(", ")}`].join(`
296
+ `);case"start":return["Usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running Bridge."," Manual starts do not consume the daily automatic match limit."," If no game is given, AIFight uses your configured game preference or picks a supported game."," N must be between 1 and 20.",` supported games: ${pe.join(", ")}`].join(`
276
297
  `);case"run":return["Usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," Normal installs should use aifight.service; use `aifight start` to request matches."," If aifight.service is already running, run refuses unless --force is set."].join(`
277
298
  `);case"status":return["Usage: aifight status"," Show local bridge config with API key and runtime token redacted."].join(`
278
299
  `);case"service":return["Usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
279
300
  `);case"uninstall":return["Usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This removes local credentials/config and aifight.service if installed."," It can also restore AIFight-recorded OpenClaw/Hermes setup changes with your approval."," It does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
280
- `);case"set":return["Usage: aifight set daily <N>"," aifight set game <game1,game2>"," daily 0 means the agent no longer joins daily automatic matches."," Manual matches and challenges are explicit user actions and are not daily automatic matches.",` supported games: ${he.join(", ")}`].join(`
301
+ `);case"set":return["Usage: aifight set daily <N>"," aifight set game <game1,game2>"," daily 0 means the agent no longer joins daily automatic matches."," Manual matches and challenges are explicit user actions and are not daily automatic matches.",` supported games: ${pe.join(", ")}`].join(`
281
302
  `);case"challenge":return["Usage: aifight challenge <texas_holdem|liars_dice|coup>"," Create a one-use friendly challenge URL to forward to another human or Agent."," Texas Hold'em challenges start as a direct two-player friendly table."," Challenges do not affect ratings or daily automatic match preferences."].join(`
282
303
  `);case"accept":return["Usage: aifight accept <challenge_url_or_token>"," Accept a challenge URL that someone sent to this human or Agent."," The local bridge must be online so game_start can be delivered."].join(`
283
- `);default:return}}function K$(t,e,n){let r=z$(t);return r===void 0?Sc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
304
+ `);default:return}}function o$(t,e,n){let r=r$(t);return r===void 0?kc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
284
305
  `):e.stdout(r+`
285
- `),0)}function lh(t,e,n,r){return n?e.stderr(Zr("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
306
+ `),0)}function fp(t,e,n,r){return n?e.stderr(to("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
286
307
  `),r!==void 0&&e.stderr(`${r}
287
- `)),2}function J$(t,e,n){if(t instanceof O)return lh(t.message,e,n,t.hint);if(t instanceof z)return n?e.stderr(Zr(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
308
+ `)),2}function i$(t,e,n){if(t instanceof O)return fp(t.message,e,n,t.hint);if(t instanceof W)return n?e.stderr(to(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
288
309
  `),t.hint!==void 0&&e.stderr(`${t.hint}
289
- `)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(Zr("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
290
- `),99}ch(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
310
+ `)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(to("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
311
+ `),99}dp(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
291
312
  `),process.exit(99)});