@intelliweave/embedded 2.0.72-beta.6 → 2.0.72-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,51 +1,138 @@
1
- import tt from"openai";import{v4 as $e}from"uuid";var k=class{constructor(){this.size=4096;this.groups=[]}createGroup(t){let e=new Me;return e.id=t,this.groups.push(e),e}group(t){return this.groups.find(e=>e.id===t)}static countTokensInText(t){return t==null?t="":typeof t=="number"?t=t+"":typeof t!="string"&&(t=JSON.stringify(t)),Math.ceil(t.length/3)}countTokens(){return this.groups.reduce((t,e)=>t+e.tokenCount,0)}removeOverflow(){let t=this.countTokens(),e=this.groups.reduce((i,o)=>i+o.weight,0);for(;t>this.size;){let i=this.groups.slice().sort((s,n)=>{let a=Math.floor(s.weight/e*this.size),l=Math.floor(n.weight/e*this.size),c=s.tokenCount-a;return n.tokenCount-l-c}),o=this.removeOneItem(i);if(!o)throw new Error("Too many items in the token window that cannot be removed.");t-=o.tokenCount}}removeOneItem(t){for(let e of t){let i=e.items.findIndex(s=>!s.cannotRemove);if(i===-1)continue;let o=e.items[i];return e.items.splice(i,1),e.tokenCount-=o.tokenCount,o}return null}},Me=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
2
- `;this.itemPadding=0;this.sortFunction=(t,e)=>t.sortOrder!==e.sortOrder?t.sortOrder-e.sortOrder:t.dateAdded!==e.dateAdded?t.dateAdded-e.dateAdded:0}setItemPadding(t){return this.itemPadding=t,this.recalculateTokens(),this}sortBy(t){return this.sortFunction=t,this.items.sort(this.sortFunction),this}setSeparator(t){return this.separator==t?this:(this.separator=t,this.recalculateTokens(),this)}setWeight(t){return this.weight=t,this}recalculateTokens(){this.tokenCount=this.items.reduce((t,e)=>(e.tokenCount=k.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+k.countTokensInText(this.separator)+this.itemPadding,t+e.tokenCount),0)}add(t){typeof t=="string"&&(t={source:"user",data:t});let e=t;e.id===void 0&&(e.id=$e()),!e.sections?.length&&typeof e.data=="string"?e.text=e.data:e.text=e.sections?.map(o=>{if(o.type==="text")return o.text||"";if(o.type==="tool_call")return`[Tool Call: ${o.toolKbName||o.toolName}] `;if(o.type==="tool_result"&&o.toolErrorResponse)return`[Tool Error: ${o.toolErrorResponse}] `}).filter(o=>!!o).join(`
1
+ import{b as N,c as Qu,d as t_}from"./chunk-FSRPMVAS.js";var wf=N(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.regexpCode=Je.getEsmExportName=Je.getProperty=Je.safeStringify=Je.stringify=Je.strConcat=Je.addCodeArg=Je.str=Je._=Je.nil=Je._Code=Je.Name=Je.IDENTIFIER=Je._CodeOrName=void 0;var _f=class{};Je._CodeOrName=_f;Je.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ea=class extends _f{constructor(e){if(super(),!Je.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}}};Je.Name=Ea;var jn=class extends _f{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Ea&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Je._Code=jn;Je.nil=new jn("");function nz(t,...e){let r=[t[0]],n=0;for(;n<e.length;)yx(r,e[n]),r.push(t[++n]);return new jn(r)}Je._=nz;var gx=new jn("+");function iz(t,...e){let r=[bf(t[0])],n=0;for(;n<e.length;)r.push(gx),yx(r,e[n]),r.push(gx,bf(t[++n]));return HF(r),new jn(r)}Je.str=iz;function yx(t,e){e instanceof jn?t.push(...e._items):e instanceof Ea?t.push(e):t.push(JF(e))}Je.addCodeArg=yx;function HF(t){let e=1;for(;e<t.length-1;){if(t[e]===gx){let r=XF(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function XF(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ea||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 Ea))return`"${t}${e.slice(1)}`}function KF(t,e){return e.emptyStr()?t:t.emptyStr()?e:iz`${t}${e}`}Je.strConcat=KF;function JF(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:bf(Array.isArray(t)?t.join(","):t)}function YF(t){return new jn(bf(t))}Je.stringify=YF;function bf(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Je.safeStringify=bf;function QF(t){return typeof t=="string"&&Je.IDENTIFIER.test(t)?new jn(`.${t}`):nz`[${t}]`}Je.getProperty=QF;function e9(t){if(typeof t=="string"&&Je.IDENTIFIER.test(t))return new jn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Je.getEsmExportName=e9;function t9(t){return new jn(t.toString())}Je.regexpCode=t9});var bx=N(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ValueScope=tn.ValueScopeName=tn.Scope=tn.varKinds=tn.UsedValueState=void 0;var en=wf(),vx=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Pg;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Pg||(tn.UsedValueState=Pg={}));tn.varKinds={const:new en.Name("const"),let:new en.Name("let"),var:new en.Name("var")};var Tg=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof en.Name?e:this.name(e)}name(e){return new en.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};tn.Scope=Tg;var Ag=class extends en.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,en._)`.${new en.Name(r)}[${n}]`}};tn.ValueScopeName=Ag;var r9=(0,en._)`\n`,_x=class extends Tg{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?r9:en.nil}}get(){return this._scope}name(e){return new Ag(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,en._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=en.nil;for(let s in e){let a=e[s];if(!a)continue;let l=n[s]=n[s]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,Pg.Started);let u=r(c);if(u){let d=this.opts.es5?tn.varKinds.var:tn.varKinds.const;o=(0,en._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=i?.(c))o=(0,en._)`${o}${u}${this.opts._n}`;else throw new vx(c);l.set(c,Pg.Completed)})}return o}};tn.ValueScope=_x});var Le=N(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.or=Me.and=Me.not=Me.CodeGen=Me.operators=Me.varKinds=Me.ValueScopeName=Me.ValueScope=Me.Scope=Me.Name=Me.regexpCode=Me.stringify=Me.getProperty=Me.nil=Me.strConcat=Me.str=Me._=void 0;var We=wf(),si=bx(),gs=wf();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return gs._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return gs.str}});Object.defineProperty(Me,"strConcat",{enumerable:!0,get:function(){return gs.strConcat}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return gs.nil}});Object.defineProperty(Me,"getProperty",{enumerable:!0,get:function(){return gs.getProperty}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return gs.stringify}});Object.defineProperty(Me,"regexpCode",{enumerable:!0,get:function(){return gs.regexpCode}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return gs.Name}});var Og=bx();Object.defineProperty(Me,"Scope",{enumerable:!0,get:function(){return Og.Scope}});Object.defineProperty(Me,"ValueScope",{enumerable:!0,get:function(){return Og.ValueScope}});Object.defineProperty(Me,"ValueScopeName",{enumerable:!0,get:function(){return Og.ValueScopeName}});Object.defineProperty(Me,"varKinds",{enumerable:!0,get:function(){return Og.varKinds}});Me.operators={GT:new We._Code(">"),GTE:new We._Code(">="),LT:new We._Code("<"),LTE:new We._Code("<="),EQ:new We._Code("==="),NEQ:new We._Code("!=="),NOT:new We._Code("!"),OR:new We._Code("||"),AND:new We._Code("&&"),ADD:new We._Code("+")};var xo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},wx=class extends xo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?si.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Yc(this.rhs,e,r)),this}get names(){return this.rhs instanceof We._CodeOrName?this.rhs.names:{}}},zg=class extends xo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof We.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Yc(this.rhs,e,r),this}get names(){let e=this.lhs instanceof We.Name?{}:{...this.lhs.names};return Cg(e,this.rhs)}},xx=class extends zg{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},$x=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},kx=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Sx=class extends xo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ix=class extends xo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Yc(this.code,e,r),this}get names(){return this.code instanceof We._CodeOrName?this.code.names:{}}},xf=class extends xo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(n9(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Aa(e,r.names),{})}},$o=class extends xf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ex=class extends xf{},Jc=class extends $o{};Jc.kind="else";var Pa=class t extends $o{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Jc(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(oz(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Yc(this.condition,e,r),this}get names(){let e=super.names;return Cg(e,this.condition),this.else&&Aa(e,this.else.names),e}};Pa.kind="if";var Ta=class extends $o{};Ta.kind="for";var Px=class extends Ta{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Yc(this.iteration,e,r),this}get names(){return Aa(super.names,this.iteration.names)}},Tx=class extends Ta{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?si.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Cg(super.names,this.from);return Cg(e,this.to)}},Ng=class extends Ta{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Yc(this.iterable,e,r),this}get names(){return Aa(super.names,this.iterable.names)}},$f=class extends $o{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};$f.kind="func";var kf=class extends xf{render(e){return"return "+super.render(e)}};kf.kind="return";var Ax=class extends $o{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Aa(e,this.catch.names),this.finally&&Aa(e,this.finally.names),e}},Sf=class extends $o{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Sf.kind="catch";var If=class extends $o{render(e){return"finally"+super.render(e)}};If.kind="finally";var zx=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new si.Scope({parent:e}),this._nodes=[new Ex]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new wx(e,o,n)),o}const(e,r,n){return this._def(si.varKinds.const,e,r,n)}let(e,r,n){return this._def(si.varKinds.let,e,r,n)}var(e,r,n){return this._def(si.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new zg(e,r,n))}add(e,r){return this._leafNode(new xx(e,Me.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==We.nil&&this._leafNode(new Ix(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,We.addCodeArg)(r,i));return r.push("}"),new We._Code(r)}if(e,r,n){if(this._blockNode(new Pa(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Pa(e))}else(){return this._elseNode(new Jc)}endIf(){return this._endBlockNode(Pa,Jc)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Px(e),r)}forRange(e,r,n,i,o=this.opts.es5?si.varKinds.var:si.varKinds.let){let s=this._scope.toName(e);return this._for(new Tx(o,s,r,n),()=>i(s))}forOf(e,r,n,i=si.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof We.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,We._)`${s}.length`,a=>{this.var(o,(0,We._)`${s}[${a}]`),n(o)})}return this._for(new Ng("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?si.varKinds.var:si.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,We._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Ng("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Ta)}label(e){return this._leafNode(new $x(e))}break(e){return this._leafNode(new kx(e))}return(e){let r=new kf;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(kf)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Ax;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new Sf(o),r(o)}return n&&(this._currNode=i.finally=new If,this.code(n)),this._endBlockNode(Sf,If)}throw(e){return this._leafNode(new Sx(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=We.nil,n,i){return this._blockNode(new $f(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode($f)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Pa))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Me.CodeGen=zx;function Aa(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Cg(t,e){return e instanceof We._CodeOrName?Aa(t,e.names):t}function Yc(t,e,r){if(t instanceof We.Name)return n(t);if(!i(t))return t;return new We._Code(t._items.reduce((o,s)=>(s instanceof We.Name&&(s=n(s)),s instanceof We._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof We._Code&&o._items.some(s=>s instanceof We.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function n9(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function oz(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,We._)`!${Nx(t)}`}Me.not=oz;var i9=sz(Me.operators.AND);function o9(...t){return t.reduce(i9)}Me.and=o9;var s9=sz(Me.operators.OR);function a9(...t){return t.reduce(s9)}Me.or=a9;function sz(t){return(e,r)=>e===We.nil?r:r===We.nil?e:(0,We._)`${Nx(e)} ${t} ${Nx(r)}`}function Nx(t){return t instanceof We.Name?t:(0,We._)`(${t})`}});var Ye=N(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.checkStrictMode=Ue.getErrorPath=Ue.Type=Ue.useFunc=Ue.setEvaluated=Ue.evaluatedPropsToName=Ue.mergeEvaluated=Ue.eachItem=Ue.unescapeJsonPointer=Ue.escapeJsonPointer=Ue.escapeFragment=Ue.unescapeFragment=Ue.schemaRefOrVal=Ue.schemaHasRulesButRef=Ue.schemaHasRules=Ue.checkUnknownRules=Ue.alwaysValidSchema=Ue.toHash=void 0;var mt=Le(),l9=wf();function c9(t){let e={};for(let r of t)e[r]=!0;return e}Ue.toHash=c9;function u9(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(cz(t,e),!uz(e,t.self.RULES.all))}Ue.alwaysValidSchema=u9;function cz(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||pz(t,`unknown keyword: "${o}"`)}Ue.checkUnknownRules=cz;function uz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Ue.schemaHasRules=uz;function d9(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Ue.schemaHasRulesButRef=d9;function f9({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,mt._)`${r}`}return(0,mt._)`${t}${e}${(0,mt.getProperty)(n)}`}Ue.schemaRefOrVal=f9;function p9(t){return dz(decodeURIComponent(t))}Ue.unescapeFragment=p9;function m9(t){return encodeURIComponent(Ox(t))}Ue.escapeFragment=m9;function Ox(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Ue.escapeJsonPointer=Ox;function dz(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Ue.unescapeJsonPointer=dz;function h9(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Ue.eachItem=h9;function az({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let l=s===void 0?o:s instanceof mt.Name?(o instanceof mt.Name?t(i,o,s):e(i,o,s),s):o instanceof mt.Name?(e(i,s,o),o):r(o,s);return a===mt.Name&&!(l instanceof mt.Name)?n(i,l):l}}Ue.mergeEvaluated={props:az({mergeNames:(t,e,r)=>t.if((0,mt._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,mt._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,mt._)`${r} || {}`).code((0,mt._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,mt._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,mt._)`${r} || {}`),Rx(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:fz}),items:az({mergeNames:(t,e,r)=>t.if((0,mt._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,mt._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,mt._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,mt._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function fz(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,mt._)`{}`);return e!==void 0&&Rx(t,r,e),r}Ue.evaluatedPropsToName=fz;function Rx(t,e,r){Object.keys(r).forEach(n=>t.assign((0,mt._)`${e}${(0,mt.getProperty)(n)}`,!0))}Ue.setEvaluated=Rx;var lz={};function g9(t,e){return t.scopeValue("func",{ref:e,code:lz[e.code]||(lz[e.code]=new l9._Code(e.code))})}Ue.useFunc=g9;var Cx;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Cx||(Ue.Type=Cx={}));function y9(t,e,r){if(t instanceof mt.Name){let n=e===Cx.Num;return r?n?(0,mt._)`"[" + ${t} + "]"`:(0,mt._)`"['" + ${t} + "']"`:n?(0,mt._)`"/" + ${t}`:(0,mt._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,mt.getProperty)(t).toString():"/"+Ox(t)}Ue.getErrorPath=y9;function pz(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Ue.checkStrictMode=pz});var ko=N(Mx=>{"use strict";Object.defineProperty(Mx,"__esModule",{value:!0});var Ar=Le(),v9={data:new Ar.Name("data"),valCxt:new Ar.Name("valCxt"),instancePath:new Ar.Name("instancePath"),parentData:new Ar.Name("parentData"),parentDataProperty:new Ar.Name("parentDataProperty"),rootData:new Ar.Name("rootData"),dynamicAnchors:new Ar.Name("dynamicAnchors"),vErrors:new Ar.Name("vErrors"),errors:new Ar.Name("errors"),this:new Ar.Name("this"),self:new Ar.Name("self"),scope:new Ar.Name("scope"),json:new Ar.Name("json"),jsonPos:new Ar.Name("jsonPos"),jsonLen:new Ar.Name("jsonLen"),jsonPart:new Ar.Name("jsonPart")};Mx.default=v9});var Ef=N(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.extendErrors=zr.resetErrorsCount=zr.reportExtraError=zr.reportError=zr.keyword$DataError=zr.keywordError=void 0;var He=Le(),Rg=Ye(),Zr=ko();zr.keywordError={message:({keyword:t})=>(0,He.str)`must pass "${t}" keyword validation`};zr.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,He.str)`"${t}" keyword must be ${e} ($data)`:(0,He.str)`"${t}" keyword is invalid ($data)`};function _9(t,e=zr.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,l=gz(t,e,r);n??(s||a)?mz(o,l):hz(i,(0,He._)`[${l}]`)}zr.reportError=_9;function b9(t,e=zr.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=gz(t,e,r);mz(i,a),o||s||hz(n,Zr.default.vErrors)}zr.reportExtraError=b9;function w9(t,e){t.assign(Zr.default.errors,e),t.if((0,He._)`${Zr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,He._)`${Zr.default.vErrors}.length`,e),()=>t.assign(Zr.default.vErrors,null)))}zr.resetErrorsCount=w9;function x9({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Zr.default.errors,a=>{t.const(s,(0,He._)`${Zr.default.vErrors}[${a}]`),t.if((0,He._)`${s}.instancePath === undefined`,()=>t.assign((0,He._)`${s}.instancePath`,(0,He.strConcat)(Zr.default.instancePath,o.errorPath))),t.assign((0,He._)`${s}.schemaPath`,(0,He.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,He._)`${s}.schema`,r),t.assign((0,He._)`${s}.data`,n))})}zr.extendErrors=x9;function mz(t,e){let r=t.const("err",e);t.if((0,He._)`${Zr.default.vErrors} === null`,()=>t.assign(Zr.default.vErrors,(0,He._)`[${r}]`),(0,He._)`${Zr.default.vErrors}.push(${r})`),t.code((0,He._)`${Zr.default.errors}++`)}function hz(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,He._)`new ${t.ValidationError}(${e})`):(r.assign((0,He._)`${n}.errors`,e),r.return(!1))}var za={keyword:new He.Name("keyword"),schemaPath:new He.Name("schemaPath"),params:new He.Name("params"),propertyName:new He.Name("propertyName"),message:new He.Name("message"),schema:new He.Name("schema"),parentSchema:new He.Name("parentSchema")};function gz(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,He._)`{}`:$9(t,e,r)}function $9(t,e,r={}){let{gen:n,it:i}=t,o=[k9(i,r),S9(t,r)];return I9(t,e,o),n.object(...o)}function k9({errorPath:t},{instancePath:e}){let r=e?(0,He.str)`${t}${(0,Rg.getErrorPath)(e,Rg.Type.Str)}`:t;return[Zr.default.instancePath,(0,He.strConcat)(Zr.default.instancePath,r)]}function S9({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,He.str)`${e}/${t}`;return r&&(i=(0,He.str)`${i}${(0,Rg.getErrorPath)(r,Rg.Type.Str)}`),[za.schemaPath,i]}function I9(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([za.keyword,i],[za.params,typeof e=="function"?e(t):e||(0,He._)`{}`]),l.messages&&n.push([za.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([za.schema,s],[za.parentSchema,(0,He._)`${u}${d}`],[Zr.default.data,o]),c&&n.push([za.propertyName,c])}});var vz=N(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});Qc.boolOrEmptySchema=Qc.topBoolOrEmptySchema=void 0;var E9=Ef(),P9=Le(),T9=ko(),A9={message:"boolean schema is false"};function z9(t){let{gen:e,schema:r,validateName:n}=t;r===!1?yz(t,!1):typeof r=="object"&&r.$async===!0?e.return(T9.default.data):(e.assign((0,P9._)`${n}.errors`,null),e.return(!0))}Qc.topBoolOrEmptySchema=z9;function N9(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),yz(t)):r.var(e,!0)}Qc.boolOrEmptySchema=N9;function yz(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,E9.reportError)(i,A9,void 0,e)}});var jx=N(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.getRules=eu.isJSONType=void 0;var C9=["string","number","integer","boolean","null","object","array"],O9=new Set(C9);function R9(t){return typeof t=="string"&&O9.has(t)}eu.isJSONType=R9;function M9(){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:{}}}eu.getRules=M9});var Dx=N(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.shouldUseRule=ys.shouldUseGroup=ys.schemaHasRulesForType=void 0;function j9({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&_z(t,n)}ys.schemaHasRulesForType=j9;function _z(t,e){return e.rules.some(r=>bz(t,r))}ys.shouldUseGroup=_z;function bz(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ys.shouldUseRule=bz});var Pf=N(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.reportTypeError=Nr.checkDataTypes=Nr.checkDataType=Nr.coerceAndCheckDataType=Nr.getJSONTypes=Nr.getSchemaTypes=Nr.DataType=void 0;var D9=jx(),L9=Dx(),U9=Ef(),ze=Le(),wz=Ye(),tu;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(tu||(Nr.DataType=tu={}));function Z9(t){let e=xz(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}Nr.getSchemaTypes=Z9;function xz(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(D9.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Nr.getJSONTypes=xz;function F9(t,e){let{gen:r,data:n,opts:i}=t,o=V9(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,L9.schemaHasRulesForType)(t,e[0]));if(s){let a=Ux(e,n,i.strictNumbers,tu.Wrong);r.if(a,()=>{o.length?q9(t,e,o):Zx(t)})}return s}Nr.coerceAndCheckDataType=F9;var $z=new Set(["string","number","integer","boolean","null"]);function V9(t,e){return e?t.filter(r=>$z.has(r)||e==="array"&&r==="array"):[]}function q9(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,ze._)`typeof ${i}`),a=n.let("coerced",(0,ze._)`undefined`);o.coerceTypes==="array"&&n.if((0,ze._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ze._)`${i}[0]`).assign(s,(0,ze._)`typeof ${i}`).if(Ux(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,ze._)`${a} !== undefined`);for(let c of r)($z.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Zx(t),n.endIf(),n.if((0,ze._)`${a} !== undefined`,()=>{n.assign(i,a),W9(t,a)});function l(c){switch(c){case"string":n.elseIf((0,ze._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,ze._)`"" + ${i}`).elseIf((0,ze._)`${i} === null`).assign(a,(0,ze._)`""`);return;case"number":n.elseIf((0,ze._)`${s} == "boolean" || ${i} === null
3
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,ze._)`+${i}`);return;case"integer":n.elseIf((0,ze._)`${s} === "boolean" || ${i} === null
4
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,ze._)`+${i}`);return;case"boolean":n.elseIf((0,ze._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,ze._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ze._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ze._)`${s} === "string" || ${s} === "number"
5
+ || ${s} === "boolean" || ${i} === null`).assign(a,(0,ze._)`[${i}]`)}}}function W9({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ze._)`${e} !== undefined`,()=>t.assign((0,ze._)`${e}[${r}]`,n))}function Lx(t,e,r,n=tu.Correct){let i=n===tu.Correct?ze.operators.EQ:ze.operators.NEQ,o;switch(t){case"null":return(0,ze._)`${e} ${i} null`;case"array":o=(0,ze._)`Array.isArray(${e})`;break;case"object":o=(0,ze._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,ze._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,ze._)`typeof ${e} ${i} ${t}`}return n===tu.Correct?o:(0,ze.not)(o);function s(a=ze.nil){return(0,ze.and)((0,ze._)`typeof ${e} == "number"`,a,r?(0,ze._)`isFinite(${e})`:ze.nil)}}Nr.checkDataType=Lx;function Ux(t,e,r,n){if(t.length===1)return Lx(t[0],e,r,n);let i,o=(0,wz.toHash)(t);if(o.array&&o.object){let s=(0,ze._)`typeof ${e} != "object"`;i=o.null?s:(0,ze._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=ze.nil;o.number&&delete o.integer;for(let s in o)i=(0,ze.and)(i,Lx(s,e,r,n));return i}Nr.checkDataTypes=Ux;var B9={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ze._)`{type: ${t}}`:(0,ze._)`{type: ${e}}`};function Zx(t){let e=G9(t);(0,U9.reportError)(e,B9)}Nr.reportTypeError=Zx;function G9(t){let{gen:e,data:r,schema:n}=t,i=(0,wz.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var Sz=N(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});Mg.assignDefaults=void 0;var ru=Le(),H9=Ye();function X9(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)kz(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>kz(t,o,i.default))}Mg.assignDefaults=X9;function kz(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,ru._)`${o}${(0,ru.getProperty)(e)}`;if(i){(0,H9.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,ru._)`${a} === undefined`;s.useDefaults==="empty"&&(l=(0,ru._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,ru._)`${a} = ${(0,ru.stringify)(r)}`)}});var Dn=N(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.validateUnion=dt.validateArray=dt.usePattern=dt.callValidateCode=dt.schemaProperties=dt.allSchemaProperties=dt.noPropertyInData=dt.propertyInData=dt.isOwnProperty=dt.hasPropFunc=dt.reportMissingProp=dt.checkMissingProp=dt.checkReportMissingProp=void 0;var xt=Le(),Fx=Ye(),vs=ko(),K9=Ye();function J9(t,e){let{gen:r,data:n,it:i}=t;r.if(qx(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,xt._)`${e}`},!0),t.error()})}dt.checkReportMissingProp=J9;function Y9({gen:t,data:e,it:{opts:r}},n,i){return(0,xt.or)(...n.map(o=>(0,xt.and)(qx(t,e,o,r.ownProperties),(0,xt._)`${i} = ${o}`)))}dt.checkMissingProp=Y9;function Q9(t,e){t.setParams({missingProperty:e},!0),t.error()}dt.reportMissingProp=Q9;function Iz(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,xt._)`Object.prototype.hasOwnProperty`})}dt.hasPropFunc=Iz;function Vx(t,e,r){return(0,xt._)`${Iz(t)}.call(${e}, ${r})`}dt.isOwnProperty=Vx;function eV(t,e,r,n){let i=(0,xt._)`${e}${(0,xt.getProperty)(r)} !== undefined`;return n?(0,xt._)`${i} && ${Vx(t,e,r)}`:i}dt.propertyInData=eV;function qx(t,e,r,n){let i=(0,xt._)`${e}${(0,xt.getProperty)(r)} === undefined`;return n?(0,xt.or)(i,(0,xt.not)(Vx(t,e,r))):i}dt.noPropertyInData=qx;function Ez(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}dt.allSchemaProperties=Ez;function tV(t,e){return Ez(e).filter(r=>!(0,Fx.alwaysValidSchema)(t,e[r]))}dt.schemaProperties=tV;function rV({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,l,c){let u=c?(0,xt._)`${t}, ${e}, ${n}${i}`:e,d=[[vs.default.instancePath,(0,xt.strConcat)(vs.default.instancePath,o)],[vs.default.parentData,s.parentData],[vs.default.parentDataProperty,s.parentDataProperty],[vs.default.rootData,vs.default.rootData]];s.opts.dynamicRef&&d.push([vs.default.dynamicAnchors,vs.default.dynamicAnchors]);let p=(0,xt._)`${u}, ${r.object(...d)}`;return l!==xt.nil?(0,xt._)`${a}.call(${l}, ${p})`:(0,xt._)`${a}(${p})`}dt.callValidateCode=rV;var nV=(0,xt._)`new RegExp`;function iV({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,xt._)`${i.code==="new RegExp"?nV:(0,K9.useFunc)(t,i)}(${r}, ${n})`})}dt.usePattern=iV;function oV(t){let{gen:e,data:r,keyword:n,it:i}=t,o=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(o,!0),s(()=>e.break()),o;function s(a){let l=e.const("len",(0,xt._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:Fx.Type.Num},o),e.if((0,xt.not)(o),a)})}}dt.validateArray=oV;function sV(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Fx.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{let u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(s,(0,xt._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,xt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}dt.validateUnion=sV});var Az=N(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.validateKeywordUsage=Ci.validSchemaType=Ci.funcKeywordCode=Ci.macroKeywordCode=void 0;var Fr=Le(),Na=ko(),aV=Dn(),lV=Ef();function cV(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),l=Tz(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");t.subschema({schema:a,schemaPath:Fr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Ci.macroKeywordCode=cV;function uV(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:l}=t;fV(l,e);let c=!a&&e.compile?e.compile.call(l.self,o,s,l):e.validate,u=Tz(n,i,c),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&Pz(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&Pz(t),y(()=>dV(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Fr._)`await `),_=>n.assign(d,!1).if((0,Fr._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(g,(0,Fr._)`${_}.errors`),()=>n.throw(_))),g}function m(){let g=(0,Fr._)`${u}.errors`;return n.assign(g,null),h(Fr.nil),g}function h(g=e.async?(0,Fr._)`await `:Fr.nil){let _=l.opts.passContext?Na.default.this:Na.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Fr._)`${g}${(0,aV.callValidateCode)(t,u,_,b)}`,e.modifying)}function y(g){var _;n.if((0,Fr.not)((_=e.valid)!==null&&_!==void 0?_:d),g)}}Ci.funcKeywordCode=uV;function Pz(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Fr._)`${n.parentData}[${n.parentDataProperty}]`))}function dV(t,e){let{gen:r}=t;r.if((0,Fr._)`Array.isArray(${e})`,()=>{r.assign(Na.default.vErrors,(0,Fr._)`${Na.default.vErrors} === null ? ${e} : ${Na.default.vErrors}.concat(${e})`).assign(Na.default.errors,(0,Fr._)`${Na.default.vErrors}.length`),(0,lV.extendErrors)(t)},()=>t.error())}function fV({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Tz(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fr.stringify)(r)})}function pV(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ci.validSchemaType=pV;function mV({schema:t,opts:e,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ci.validateKeywordUsage=mV});var Nz=N(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.extendSubschemaMode=_s.extendSubschemaData=_s.getSubschema=void 0;var Oi=Le(),zz=Ye();function hV(t,{keyword:e,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Oi._)`${t.schemaPath}${(0,Oi.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Oi._)`${t.schemaPath}${(0,Oi.getProperty)(e)}${(0,Oi.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,zz.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}_s.getSubschema=hV;function gV(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,p=a.let("data",(0,Oi._)`${e.data}${(0,Oi.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Oi.str)`${c}${(0,zz.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Oi._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let c=i instanceof Oi.Name?i:a.let("data",i,!0);l(c),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}_s.extendSubschemaData=gV;function yV(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}_s.extendSubschemaMode=yV});var Tf=N((f_e,Cz)=>{"use strict";Cz.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var Wx=N((p_e,Oz)=>{"use strict";var bs=Oz.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};jg(e,n,i,t,"",t)};bs.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bs.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bs.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bs.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 jg(t,e,r,n,i,o,s,a,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in bs.arrayKeywords)for(var p=0;p<d.length;p++)jg(t,e,r,d[p],i+"/"+u+"/"+p,o,i,u,n,p)}else if(u in bs.propsKeywords){if(d&&typeof d=="object")for(var f in d)jg(t,e,r,d[f],i+"/"+u+"/"+vV(f),o,i,u,n,f)}else(u in bs.keywords||t.allKeys&&!(u in bs.skipKeywords))&&jg(t,e,r,d,i+"/"+u,o,i,u,n)}r(n,i,o,s,a,l,c)}}function vV(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Af=N(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.getSchemaRefs=rn.resolveUrl=rn.normalizeId=rn._getFullPath=rn.getFullPath=rn.inlineRef=void 0;var _V=Ye(),bV=Tf(),wV=Wx(),xV=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $V(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Bx(t):e?Rz(t)<=e:!1}rn.inlineRef=$V;var kV=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Bx(t){for(let e in t){if(kV.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Bx)||typeof r=="object"&&Bx(r))return!0}return!1}function Rz(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!xV.has(r)&&(typeof t[r]=="object"&&(0,_V.eachItem)(t[r],n=>e+=Rz(n)),e===1/0))return 1/0}return e}function Mz(t,e="",r){r!==!1&&(e=nu(e));let n=t.parse(e);return jz(t,n)}rn.getFullPath=Mz;function jz(t,e){return t.serialize(e).split("#")[0]+"#"}rn._getFullPath=jz;var SV=/#\/?$/;function nu(t){return t?t.replace(SV,""):""}rn.normalizeId=nu;function IV(t,e,r){return r=nu(r),t.resolve(e,r)}rn.resolveUrl=IV;var EV=/^[a-z_][-a-z0-9._]*$/i;function PV(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=nu(t[r]||e),o={"":i},s=Mz(n,i,!1),a={},l=new Set;return wV(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=s+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function g(b){let E=this.opts.uriResolver.resolve;if(b=nu(y?E(y,b):b),l.has(b))throw u(b);l.add(b);let I=this.refs[b];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?c(d,I.schema,b):b!==nu(h)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!EV.test(b))throw new Error(`invalid anchor "${b}"`);g.call(this,`#${b}`)}}}),a;function c(d,p,f){if(p!==void 0&&!bV(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rn.getSchemaRefs=PV});var Cf=N(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.getData=ws.KeywordCxt=ws.validateFunctionCode=void 0;var Fz=vz(),Dz=Pf(),Hx=Dx(),Dg=Pf(),TV=Sz(),Nf=Az(),Gx=Nz(),le=Le(),xe=ko(),AV=Af(),So=Ye(),zf=Ef();function zV(t){if(Wz(t)&&(Bz(t),qz(t))){OV(t);return}Vz(t,()=>(0,Fz.topBoolOrEmptySchema)(t))}ws.validateFunctionCode=zV;function Vz({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,le._)`${xe.default.data}, ${xe.default.valCxt}`,n.$async,()=>{t.code((0,le._)`"use strict"; ${Lz(r,i)}`),CV(t,i),t.code(o)}):t.func(e,(0,le._)`${xe.default.data}, ${NV(i)}`,n.$async,()=>t.code(Lz(r,i)).code(o))}function NV(t){return(0,le._)`{${xe.default.instancePath}="", ${xe.default.parentData}, ${xe.default.parentDataProperty}, ${xe.default.rootData}=${xe.default.data}${t.dynamicRef?(0,le._)`, ${xe.default.dynamicAnchors}={}`:le.nil}}={}`}function CV(t,e){t.if(xe.default.valCxt,()=>{t.var(xe.default.instancePath,(0,le._)`${xe.default.valCxt}.${xe.default.instancePath}`),t.var(xe.default.parentData,(0,le._)`${xe.default.valCxt}.${xe.default.parentData}`),t.var(xe.default.parentDataProperty,(0,le._)`${xe.default.valCxt}.${xe.default.parentDataProperty}`),t.var(xe.default.rootData,(0,le._)`${xe.default.valCxt}.${xe.default.rootData}`),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,le._)`${xe.default.valCxt}.${xe.default.dynamicAnchors}`)},()=>{t.var(xe.default.instancePath,(0,le._)`""`),t.var(xe.default.parentData,(0,le._)`undefined`),t.var(xe.default.parentDataProperty,(0,le._)`undefined`),t.var(xe.default.rootData,xe.default.data),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,le._)`{}`)})}function OV(t){let{schema:e,opts:r,gen:n}=t;Vz(t,()=>{r.$comment&&e.$comment&&Hz(t),LV(t),n.let(xe.default.vErrors,null),n.let(xe.default.errors,0),r.unevaluated&&RV(t),Gz(t),FV(t)})}function RV(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,le._)`${r}.evaluated`),e.if((0,le._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,le._)`${t.evaluated}.props`,(0,le._)`undefined`)),e.if((0,le._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,le._)`${t.evaluated}.items`,(0,le._)`undefined`))}function Lz(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,le._)`/*# sourceURL=${r} */`:le.nil}function MV(t,e){if(Wz(t)&&(Bz(t),qz(t))){jV(t,e);return}(0,Fz.boolOrEmptySchema)(t,e)}function qz({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Wz(t){return typeof t.schema!="boolean"}function jV(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&Hz(t),UV(t),ZV(t);let o=n.const("_errs",xe.default.errors);Gz(t,o),n.var(e,(0,le._)`${o} === ${xe.default.errors}`)}function Bz(t){(0,So.checkUnknownRules)(t),DV(t)}function Gz(t,e){if(t.opts.jtd)return Uz(t,[],!1,e);let r=(0,Dz.getSchemaTypes)(t.schema),n=(0,Dz.coerceAndCheckDataType)(t,r);Uz(t,r,!n,e)}function DV(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,So.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function LV(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,So.checkStrictMode)(t,"default is ignored in the schema root")}function UV(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,AV.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function ZV(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Hz({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,le._)`${xe.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,le.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,le._)`${xe.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function FV(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,le._)`${xe.default.errors} === 0`,()=>e.return(xe.default.data),()=>e.throw((0,le._)`new ${i}(${xe.default.vErrors})`)):(e.assign((0,le._)`${n}.errors`,xe.default.vErrors),o.unevaluated&&VV(t),e.return((0,le._)`${xe.default.errors} === 0`))}function VV({gen:t,evaluated:e,props:r,items:n}){r instanceof le.Name&&t.assign((0,le._)`${e}.props`,r),n instanceof le.Name&&t.assign((0,le._)`${e}.items`,n)}function Uz(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,So.schemaHasRulesButRef)(o,u))){i.block(()=>Kz(t,"$ref",u.all.$ref.definition));return}l.jtd||qV(t,e),i.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,Hx.shouldUseGroup)(o,p)&&(p.type?(i.if((0,Dg.checkDataType)(p.type,s,l.strictNumbers)),Zz(t,p),e.length===1&&e[0]===p.type&&r&&(i.else(),(0,Dg.reportTypeError)(t)),i.endIf()):Zz(t,p),a||i.if((0,le._)`${xe.default.errors} === ${n||0}`))}}function Zz(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,TV.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Hx.shouldUseRule)(n,o)&&Kz(t,o.keyword,o.definition,e.type)})}function qV(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(WV(t,e),t.opts.allowUnionTypes||BV(t,e),GV(t,t.dataTypes))}function WV(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Xz(t.dataTypes,r)||Xx(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),XV(t,e)}}function BV(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Xx(t,"use allowUnionTypes to allow union type keyword")}function GV(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Hx.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>HV(e,s))&&Xx(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function HV(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Xz(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function XV(t,e){let r=[];for(let n of t.dataTypes)Xz(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Xx(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,So.checkStrictMode)(t,e,t.opts.strictTypes)}var Lg=class{constructor(e,r,n){if((0,Nf.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,So.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Jz(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Nf.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",xe.default.errors))}result(e,r,n){this.failResult((0,le.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,le.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,le._)`${r} !== undefined && (${(0,le.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?zf.reportExtraError:zf.reportError)(this,this.def.error,r)}$dataError(){(0,zf.reportError)(this,this.def.$dataError||zf.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zf.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=le.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=le.nil,r=le.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,le.or)((0,le._)`${i} === undefined`,r)),e!==le.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==le.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,le.or)(s(),a());function s(){if(n.length){if(!(r instanceof le.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,le._)`${(0,Dg.checkDataTypes)(l,r,o.opts.strictNumbers,Dg.DataType.Wrong)}`}return le.nil}function a(){if(i.validateSchema){let l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,le._)`!${l}(${r})`}return le.nil}}subschema(e,r){let n=(0,Gx.getSubschema)(this.it,e);(0,Gx.extendSubschemaData)(n,this.it,e),(0,Gx.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return MV(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=So.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=So.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,le.Name)),!0}};ws.KeywordCxt=Lg;function Kz(t,e,r,n){let i=new Lg(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,Nf.funcKeywordCode)(i,r):"macro"in r?(0,Nf.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,Nf.funcKeywordCode)(i,r)}var KV=/^\/(?:[^~]|~0|~1)*$/,JV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jz(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return xe.default.rootData;if(t[0]==="/"){if(!KV.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=xe.default.rootData}else{let c=JV.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(i=c[2],i==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,le._)`${o}${(0,le.getProperty)((0,So.unescapeJsonPointer)(c))}`,s=(0,le._)`${s} && ${o}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}ws.getData=Jz});var Ug=N(Jx=>{"use strict";Object.defineProperty(Jx,"__esModule",{value:!0});var Kx=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Jx.default=Kx});var Of=N(e$=>{"use strict";Object.defineProperty(e$,"__esModule",{value:!0});var Yx=Af(),Qx=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Yx.resolveUrl)(e,r,n),this.missingSchema=(0,Yx.normalizeId)((0,Yx.getFullPath)(e,this.missingRef))}};e$.default=Qx});var Fg=N(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.resolveSchema=Ln.getCompilingSchema=Ln.resolveRef=Ln.compileSchema=Ln.SchemaEnv=void 0;var ai=Le(),YV=Ug(),Ca=ko(),li=Af(),Yz=Ye(),QV=Cf(),iu=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,li.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ln.SchemaEnv=iu;function r$(t){let e=Qz.call(this,t);if(e)return e;let r=(0,li.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new ai.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:YV.default,code:(0,ai._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:Ca.default.data,parentData:Ca.default.parentData,parentDataProperty:Ca.default.parentDataProperty,dataNames:[Ca.default.data],dataPathArr:[ai.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ai.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ai.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ai._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,QV.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Ca.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Ca.default.self}`,`${Ca.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=c;f.evaluated={props:m instanceof ai.Name?void 0:m,items:h instanceof ai.Name?void 0:h,dynamicProps:m instanceof ai.Name,dynamicItems:h instanceof ai.Name},f.source&&(f.source.evaluated=(0,ai.stringify)(f.evaluated))}return t.validate=f,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)}}Ln.compileSchema=r$;function e5(t,e,r){var n;r=(0,li.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=n5.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new iu({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=t5.call(this,o)}Ln.resolveRef=e5;function t5(t){return(0,li.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:r$.call(this,t)}function Qz(t){for(let e of this._compilations)if(r5(e,t))return e}Ln.getCompilingSchema=Qz;function r5(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function n5(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Zg.call(this,t,e)}function Zg(t,e){let r=this.opts.uriResolver.parse(e),n=(0,li._getFullPath)(this.opts.uriResolver,r),i=(0,li.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return t$.call(this,r,t);let o=(0,li.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Zg.call(this,t,s);return typeof a?.schema!="object"?void 0:t$.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||r$.call(this,s),o===(0,li.normalizeId)(e)){let{schema:a}=s,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,li.resolveUrl)(this.opts.uriResolver,i,c)),new iu({schema:a,schemaId:l,root:t,baseId:i})}return t$.call(this,r,s)}}Ln.resolveSchema=Zg;var i5=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function t$(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,Yz.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!i5.has(a)&&c&&(e=(0,li.resolveUrl)(this.opts.uriResolver,e,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Yz.schemaHasRulesButRef)(r,this.RULES)){let a=(0,li.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Zg.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new iu({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var eN=N((__e,o5)=>{o5.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 i$=N((b_e,iN)=>{"use strict";var s5=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),rN=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 n$(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var a5=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function tN(t){return t.length=0,!0}function l5(t,e,r){if(t.length){let n=n$(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function c5(t){let e=0,r={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=l5;for(let l=0;l<t.length;l++){let c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(o===!0&&(s=!0),!a(i,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(c==="%"){if(!a(i,n,r))break;a=tN}else{i.push(c);continue}}return i.length&&(a===tN?r.zone=i.join(""):s?n.push(i.join("")):n.push(n$(i))),r.address=n.join(""),r}function nN(t){if(u5(t,":")<2)return{host:t,isIPV6:!1};let e=c5(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function u5(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function d5(t){let e=t,r=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(i===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function f5(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function p5(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!rN(r)){let n=nN(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}iN.exports={nonSimpleDomain:a5,recomposeAuthority:p5,normalizeComponentEncoding:f5,removeDotSegments:d5,isIPv4:rN,isUUID:s5,normalizeIPv6:nN,stringArrayToHexStripped:n$}});var cN=N((w_e,lN)=>{"use strict";var{isUUID:m5}=i$(),h5=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,g5=["http","https","ws","wss","urn","urn:uuid"];function y5(t){return g5.indexOf(t)!==-1}function o$(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 oN(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sN(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 v5(t){return t.secure=o$(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function _5(t){if((t.port===(o$(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function b5(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(h5);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let i=`${n}:${e.nid||t.nid}`,o=s$(i);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function w5(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),i=`${r}:${e.nid||n}`,o=s$(i);o&&(t=o.serialize(t,e));let s=t,a=t.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function x5(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!m5(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function $5(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var aN={scheme:"http",domainHost:!0,parse:oN,serialize:sN},k5={scheme:"https",domainHost:aN.domainHost,parse:oN,serialize:sN},Vg={scheme:"ws",domainHost:!0,parse:v5,serialize:_5},S5={scheme:"wss",domainHost:Vg.domainHost,parse:Vg.parse,serialize:Vg.serialize},I5={scheme:"urn",parse:b5,serialize:w5,skipNormalize:!0},E5={scheme:"urn:uuid",parse:x5,serialize:$5,skipNormalize:!0},qg={http:aN,https:k5,ws:Vg,wss:S5,urn:I5,"urn:uuid":E5};Object.setPrototypeOf(qg,null);function s$(t){return t&&(qg[t]||qg[t.toLowerCase()])||void 0}lN.exports={wsIsSecure:o$,SCHEMES:qg,isValidSchemeName:y5,getSchemeHandler:s$}});var fN=N((x_e,Bg)=>{"use strict";var{normalizeIPv6:P5,removeDotSegments:Rf,recomposeAuthority:T5,normalizeComponentEncoding:Wg,isIPv4:A5,nonSimpleDomain:z5}=i$(),{SCHEMES:N5,getSchemeHandler:uN}=cN();function C5(t,e){return typeof t=="string"?t=Ri(Io(t,e),e):typeof t=="object"&&(t=Io(Ri(t,e),e)),t}function O5(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=dN(Io(t,n),Io(e,n),n,!0);return n.skipEscape=!0,Ri(i,n)}function dN(t,e,r,n){let i={};return n||(t=Io(Ri(t,r),r),e=Io(Ri(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Rf(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Rf(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Rf(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?i.path="/"+e.path:t.path?i.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Rf(i.path)),i.query=e.query):(i.path=t.path,e.query!==void 0?i.query=e.query:i.query=t.query),i.userinfo=t.userinfo,i.host=t.host,i.port=t.port),i.scheme=t.scheme),i.fragment=e.fragment,i}function R5(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ri(Wg(Io(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ri(Wg(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ri(Wg(Io(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ri(Wg(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ri(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),i=[],o=uN(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=T5(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Rf(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var M5=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Io(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(M5);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(A5(n.host)===!1){let l=P5(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=uN(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&z5(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var a$={SCHEMES:N5,normalize:C5,resolve:O5,resolveComponent:dN,equal:R5,serialize:Ri,parse:Io};Bg.exports=a$;Bg.exports.default=a$;Bg.exports.fastUri=a$});var mN=N(l$=>{"use strict";Object.defineProperty(l$,"__esModule",{value:!0});var pN=fN();pN.code='require("ajv/dist/runtime/uri").default';l$.default=pN});var xN=N(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.CodeGen=yr.Name=yr.nil=yr.stringify=yr.str=yr._=yr.KeywordCxt=void 0;var j5=Cf();Object.defineProperty(yr,"KeywordCxt",{enumerable:!0,get:function(){return j5.KeywordCxt}});var ou=Le();Object.defineProperty(yr,"_",{enumerable:!0,get:function(){return ou._}});Object.defineProperty(yr,"str",{enumerable:!0,get:function(){return ou.str}});Object.defineProperty(yr,"stringify",{enumerable:!0,get:function(){return ou.stringify}});Object.defineProperty(yr,"nil",{enumerable:!0,get:function(){return ou.nil}});Object.defineProperty(yr,"Name",{enumerable:!0,get:function(){return ou.Name}});Object.defineProperty(yr,"CodeGen",{enumerable:!0,get:function(){return ou.CodeGen}});var D5=Ug(),_N=Of(),L5=jx(),Mf=Fg(),U5=Le(),jf=Af(),Gg=Pf(),u$=Ye(),hN=eN(),Z5=mN(),bN=(t,e)=>new RegExp(t,e);bN.code="new RegExp";var F5=["removeAdditional","useDefaults","coerceTypes"],V5=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),q5={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."},W5={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},gN=200;function B5(t){var e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R;let L=t.strict,G=(e=t.code)===null||e===void 0?void 0:e.optimize,H=G===!0||G===void 0?1:G||0,W=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:bN,Y=(i=t.uriResolver)!==null&&i!==void 0?i:Z5.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:L)!==null&&s!==void 0?s:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:L)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:L)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:L)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:L)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:H,regExp:W}:{optimize:H,regExp:W},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:gN,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:gN,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(M=t.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(V=t.unicodeRegExp)!==null&&V!==void 0?V:!0,int32range:(R=t.int32range)!==null&&R!==void 0?R:!0,uriResolver:Y}}var Df=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...B5(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new U5.ValueScope({scope:{},prefixes:V5,es5:r,lines:n}),this.logger=Y5(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,L5.getRules)(),yN.call(this,q5,e,"NOT SUPPORTED"),yN.call(this,W5,e,"DEPRECATED","warn"),this._metaOpts=K5.call(this),e.formats&&H5.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&X5.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),G5.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=hN;n==="id"&&(i={...hN},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,r);async function i(u,d){await o.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof _N.default))throw d;return a.call(this,d),await l.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 l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,jf.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(e){let r;for(;typeof(r=vN.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Mf.SchemaEnv({schema:{},schemaId:n});if(r=Mf.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=vN.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,jf.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(eq.call(this,n,r),!r)return(0,u$.eachItem)(n,o=>c$.call(this,o)),this;rq.call(this,r);let i={...r,type:(0,Gg.getJSONTypes)(r.type),schemaType:(0,Gg.getJSONTypes)(r.schemaType)};return(0,u$.eachItem)(n,i.type.length===0?o=>c$.call(this,o,i):o=>i.type.forEach(s=>c$.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[a];c&&u&&(s[a]=wN(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,n,i=this.opts.validateSchema,o=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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,jf.normalizeId)(s||n);let c=jf.getSchemaRefs.call(this,e,n);return l=new Mf.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Mf.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Mf.compileSchema.call(this,e)}finally{this.opts=r}}};Df.ValidationError=D5.default;Df.MissingRefError=_N.default;yr.default=Df;function yN(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function vN(t){return t=(0,jf.normalizeId)(t),this.schemas[t]||this.refs[t]}function G5(){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 H5(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function X5(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function K5(){let t={...this.opts};for(let e of F5)delete t[e];return t}var J5={log(){},warn(){},error(){}};function Y5(t){if(t===!1)return J5;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 Q5=/^[a-z_$][a-z0-9_$:-]*$/i;function eq(t,e){let{RULES:r}=this;if((0,u$.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Q5.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function c$(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:l})=>l===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Gg.getJSONTypes)(e.type),schemaType:(0,Gg.getJSONTypes)(e.schemaType)}};e.before?tq.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function tq(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function rq(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=wN(e)),t.validateSchema=this.compile(e,!0))}var nq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function wN(t){return{anyOf:[t,nq]}}});var $N=N(d$=>{"use strict";Object.defineProperty(d$,"__esModule",{value:!0});var iq={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};d$.default=iq});var EN=N(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.callRef=Oa.getValidate=void 0;var oq=Of(),kN=Dn(),nn=Le(),su=ko(),SN=Fg(),Hg=Ye(),sq={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let u=SN.resolveRef.call(l,c,i,r);if(u===void 0)throw new oq.default(n.opts.uriResolver,i,r);if(u instanceof SN.SchemaEnv)return p(u);return f(u);function d(){if(o===c)return Xg(t,s,o,o.$async);let m=e.scopeValue("root",{ref:c});return Xg(t,(0,nn._)`${m}.validate`,c,c.$async)}function p(m){let h=IN(t,m);Xg(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nn.stringify)(m)}:{ref:m}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:nn.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function IN(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nn._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Oa.getValidate=IN;function Xg(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:l}=o,c=l.passContext?su.default.this:nn.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,nn._)`await ${(0,kN.callValidateCode)(t,e,c)}`),f(e),s||i.assign(m,!0)},h=>{i.if((0,nn._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),p(h),s||i.assign(m,!1)}),t.ok(m)}function d(){t.result((0,kN.callValidateCode)(t,e,c),()=>f(e),()=>p(e))}function p(m){let h=(0,nn._)`${m}.errors`;i.assign(su.default.vErrors,(0,nn._)`${su.default.vErrors} === null ? ${h} : ${su.default.vErrors}.concat(${h})`),i.assign(su.default.errors,(0,nn._)`${su.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Hg.mergeEvaluated.props(i,y.props,o.props));else{let g=i.var("props",(0,nn._)`${m}.evaluated.props`);o.props=Hg.mergeEvaluated.props(i,g,o.props,nn.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Hg.mergeEvaluated.items(i,y.items,o.items));else{let g=i.var("items",(0,nn._)`${m}.evaluated.items`);o.items=Hg.mergeEvaluated.items(i,g,o.items,nn.Name)}}}Oa.callRef=Xg;Oa.default=sq});var PN=N(f$=>{"use strict";Object.defineProperty(f$,"__esModule",{value:!0});var aq=$N(),lq=EN(),cq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",aq.default,lq.default];f$.default=cq});var TN=N(p$=>{"use strict";Object.defineProperty(p$,"__esModule",{value:!0});var Kg=Le(),xs=Kg.operators,Jg={maximum:{okStr:"<=",ok:xs.LTE,fail:xs.GT},minimum:{okStr:">=",ok:xs.GTE,fail:xs.LT},exclusiveMaximum:{okStr:"<",ok:xs.LT,fail:xs.GTE},exclusiveMinimum:{okStr:">",ok:xs.GT,fail:xs.LTE}},uq={message:({keyword:t,schemaCode:e})=>(0,Kg.str)`must be ${Jg[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Kg._)`{comparison: ${Jg[t].okStr}, limit: ${e}}`},dq={keyword:Object.keys(Jg),type:"number",schemaType:"number",$data:!0,error:uq,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Kg._)`${r} ${Jg[e].fail} ${n} || isNaN(${r})`)}};p$.default=dq});var AN=N(m$=>{"use strict";Object.defineProperty(m$,"__esModule",{value:!0});var Lf=Le(),fq={message:({schemaCode:t})=>(0,Lf.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Lf._)`{multipleOf: ${t}}`},pq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:fq,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,Lf._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Lf._)`${s} !== parseInt(${s})`;t.fail$data((0,Lf._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};m$.default=pq});var NN=N(h$=>{"use strict";Object.defineProperty(h$,"__esModule",{value:!0});function zN(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}h$.default=zN;zN.code='require("ajv/dist/runtime/ucs2length").default'});var CN=N(g$=>{"use strict";Object.defineProperty(g$,"__esModule",{value:!0});var Ra=Le(),mq=Ye(),hq=NN(),gq={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ra.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ra._)`{limit: ${t}}`},yq={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:gq,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Ra.operators.GT:Ra.operators.LT,s=i.opts.unicode===!1?(0,Ra._)`${r}.length`:(0,Ra._)`${(0,mq.useFunc)(t.gen,hq.default)}(${r})`;t.fail$data((0,Ra._)`${s} ${o} ${n}`)}};g$.default=yq});var ON=N(y$=>{"use strict";Object.defineProperty(y$,"__esModule",{value:!0});var vq=Dn(),Yg=Le(),_q={message:({schemaCode:t})=>(0,Yg.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Yg._)`{pattern: ${t}}`},bq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_q,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Yg._)`(new RegExp(${i}, ${s}))`:(0,vq.usePattern)(t,n);t.fail$data((0,Yg._)`!${a}.test(${e})`)}};y$.default=bq});var RN=N(v$=>{"use strict";Object.defineProperty(v$,"__esModule",{value:!0});var Uf=Le(),wq={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Uf.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Uf._)`{limit: ${t}}`},xq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wq,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?Uf.operators.GT:Uf.operators.LT;t.fail$data((0,Uf._)`Object.keys(${r}).length ${i} ${n}`)}};v$.default=xq});var MN=N(_$=>{"use strict";Object.defineProperty(_$,"__esModule",{value:!0});var Zf=Dn(),Ff=Le(),$q=Ye(),kq={message:({params:{missingProperty:t}})=>(0,Ff.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ff._)`{missingProperty: ${t}}`},Sq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kq,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(s.allErrors?c():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let y=s.schemaEnv.baseId+s.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,$q.checkStrictMode)(s,g,s.opts.strictRequired)}}function c(){if(l||o)t.block$data(Ff.nil,d);else for(let f of r)(0,Zf.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Zf.checkMissingProp)(t,r,f)),(0,Zf.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Zf.noPropertyInData)(e,i,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Zf.propertyInData)(e,i,f,a.ownProperties)),e.if((0,Ff.not)(m),()=>{t.error(),e.break()})},Ff.nil)}}};_$.default=Sq});var jN=N(b$=>{"use strict";Object.defineProperty(b$,"__esModule",{value:!0});var Vf=Le(),Iq={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Vf.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Vf._)`{limit: ${t}}`},Eq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Iq,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?Vf.operators.GT:Vf.operators.LT;t.fail$data((0,Vf._)`${r}.length ${i} ${n}`)}};b$.default=Eq});var Qg=N(w$=>{"use strict";Object.defineProperty(w$,"__esModule",{value:!0});var DN=Tf();DN.code='require("ajv/dist/runtime/equal").default';w$.default=DN});var LN=N($$=>{"use strict";Object.defineProperty($$,"__esModule",{value:!0});var x$=Pf(),vr=Le(),Pq=Ye(),Tq=Qg(),Aq={message:({params:{i:t,j:e}})=>(0,vr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,vr._)`{i: ${t}, j: ${e}}`},zq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Aq,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let l=e.let("valid"),c=o.items?(0,x$.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,vr._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,vr._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(l,!0),e.if((0,vr._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),g=(0,x$.checkDataTypes)(c,y,a.opts.strictNumbers,x$.DataType.Wrong),_=e.const("indices",(0,vr._)`{}`);e.for((0,vr._)`;${m}--;`,()=>{e.let(y,(0,vr._)`${r}[${m}]`),e.if(g,(0,vr._)`continue`),c.length>1&&e.if((0,vr._)`typeof ${y} == "string"`,(0,vr._)`${y} += "_"`),e.if((0,vr._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,vr._)`${_}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,vr._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,Pq.useFunc)(e,Tq.default),g=e.name("outer");e.label(g).for((0,vr._)`;${m}--;`,()=>e.for((0,vr._)`${h} = ${m}; ${h}--;`,()=>e.if((0,vr._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(l,!1).break(g)})))}}};$$.default=zq});var UN=N(S$=>{"use strict";Object.defineProperty(S$,"__esModule",{value:!0});var k$=Le(),Nq=Ye(),Cq=Qg(),Oq={message:"must be equal to constant",params:({schemaCode:t})=>(0,k$._)`{allowedValue: ${t}}`},Rq={keyword:"const",$data:!0,error:Oq,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,k$._)`!${(0,Nq.useFunc)(e,Cq.default)}(${r}, ${i})`):t.fail((0,k$._)`${o} !== ${r}`)}};S$.default=Rq});var ZN=N(I$=>{"use strict";Object.defineProperty(I$,"__esModule",{value:!0});var qf=Le(),Mq=Ye(),jq=Qg(),Dq={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,qf._)`{allowedValues: ${t}}`},Lq={keyword:"enum",schemaType:"array",$data:!0,error:Dq,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,Mq.useFunc)(e,jq.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",o);u=(0,qf.or)(...i.map((m,h)=>p(f,h)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,f=>e.if((0,qf._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function p(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,qf._)`${c()}(${r}, ${f}[${m}])`:(0,qf._)`${r} === ${h}`}}};I$.default=Lq});var FN=N(E$=>{"use strict";Object.defineProperty(E$,"__esModule",{value:!0});var Uq=TN(),Zq=AN(),Fq=CN(),Vq=ON(),qq=RN(),Wq=MN(),Bq=jN(),Gq=LN(),Hq=UN(),Xq=ZN(),Kq=[Uq.default,Zq.default,Fq.default,Vq.default,qq.default,Wq.default,Bq.default,Gq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Hq.default,Xq.default];E$.default=Kq});var T$=N(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});Wf.validateAdditionalItems=void 0;var Ma=Le(),P$=Ye(),Jq={message:({params:{len:t}})=>(0,Ma.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ma._)`{limit: ${t}}`},Yq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Jq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,P$.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}VN(t,n)}};function VN(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,Ma._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ma._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,P$.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Ma._)`${a} <= ${e.length}`);r.if((0,Ma.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:P$.Type.Num},c),s.allErrors||r.if((0,Ma.not)(c),()=>r.break())})}}Wf.validateAdditionalItems=VN;Wf.default=Yq});var A$=N(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});Bf.validateTuple=void 0;var qN=Le(),ey=Ye(),Qq=Dn(),e3={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return WN(t,"additionalItems",e);r.items=!0,!(0,ey.alwaysValidSchema)(r,e)&&t.ok((0,Qq.validateArray)(t))}};function WN(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ey.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,qN._)`${o}.length`);r.forEach((d,p)=>{(0,ey.alwaysValidSchema)(a,d)||(n.if((0,qN._)`${c} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},l)),t.ok(l))});function u(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ey.checkStrictMode)(a,y,p.strictTuples)}}}Bf.validateTuple=WN;Bf.default=e3});var BN=N(z$=>{"use strict";Object.defineProperty(z$,"__esModule",{value:!0});var t3=A$(),r3={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,t3.validateTuple)(t,"items")};z$.default=r3});var HN=N(N$=>{"use strict";Object.defineProperty(N$,"__esModule",{value:!0});var GN=Le(),n3=Ye(),i3=Dn(),o3=T$(),s3={message:({params:{len:t}})=>(0,GN.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,GN._)`{limit: ${t}}`},a3={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:s3,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,n3.alwaysValidSchema)(n,e)&&(i?(0,o3.validateAdditionalItems)(t,i):t.ok((0,i3.validateArray)(t)))}};N$.default=a3});var XN=N(C$=>{"use strict";Object.defineProperty(C$,"__esModule",{value:!0});var Un=Le(),ty=Ye(),l3={message:({params:{min:t,max:e}})=>e===void 0?(0,Un.str)`must contain at least ${t} valid item(s)`:(0,Un.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Un._)`{minContains: ${t}}`:(0,Un._)`{minContains: ${t}, maxContains: ${e}}`},c3={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:l3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:l,maxContains:c}=n;o.opts.next?(s=l===void 0?1:l,a=c):s=1;let u=e.const("len",(0,Un._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,ty.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,ty.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ty.alwaysValidSchema)(o,r)){let h=(0,Un._)`${u} >= ${s}`;a!==void 0&&(h=(0,Un._)`${h} && ${u} <= ${a}`),t.pass(h);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?f(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Un._)`${i}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,u,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:ty.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Un._)`${h}++`),a===void 0?e.if((0,Un._)`${h} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Un._)`${h} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Un._)`${h} >= ${s}`,()=>e.assign(d,!0)))}}};C$.default=c3});var YN=N(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.validateSchemaDeps=Mi.validatePropertyDeps=Mi.error=void 0;var O$=Le(),u3=Ye(),Gf=Dn();Mi.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,O$.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,O$._)`{property: ${t},
6
+ missingProperty: ${n},
7
+ depsCount: ${e},
8
+ deps: ${r}}`};var d3={keyword:"dependencies",type:"object",schemaType:"object",error:Mi.error,code(t){let[e,r]=f3(t);KN(t,e),JN(t,r)}};function f3({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function KN(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let l=(0,Gf.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(l,()=>{for(let c of a)(0,Gf.checkReportMissingProp)(t,c)}):(r.if((0,O$._)`${l} && (${(0,Gf.checkMissingProp)(t,a,o)})`),(0,Gf.reportMissingProp)(t,o),r.else())}}Mi.validatePropertyDeps=KN;function JN(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,u3.alwaysValidSchema)(o,e[a])||(r.if((0,Gf.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(l,s)},()=>r.var(s,!0)),t.ok(s))}Mi.validateSchemaDeps=JN;Mi.default=d3});var eC=N(R$=>{"use strict";Object.defineProperty(R$,"__esModule",{value:!0});var QN=Le(),p3=Ye(),m3={message:"property name must be valid",params:({params:t})=>(0,QN._)`{propertyName: ${t.propertyName}}`},h3={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:m3,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,p3.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,QN.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};R$.default=h3});var j$=N(M$=>{"use strict";Object.defineProperty(M$,"__esModule",{value:!0});var ry=Dn(),ci=Le(),g3=ko(),ny=Ye(),y3={message:"must NOT have additional properties",params:({params:t})=>(0,ci._)`{additionalProperty: ${t.additionalProperty}}`},v3={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:y3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,ny.alwaysValidSchema)(s,r))return;let c=(0,ry.allSchemaProperties)(n.properties),u=(0,ry.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ci._)`${o} === ${g3.default.errors}`);function d(){e.forIn("key",i,y=>{!c.length&&!u.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(c.length>8){let _=(0,ny.schemaRefOrVal)(s,n.properties,"properties");g=(0,ry.isOwnProperty)(e,_,y)}else c.length?g=(0,ci.or)(...c.map(_=>(0,ci._)`${y} === ${_}`)):g=ci.nil;return u.length&&(g=(0,ci.or)(g,...u.map(_=>(0,ci._)`${(0,ry.usePattern)(t,_)}.test(${y})`))),(0,ci.not)(g)}function f(y){e.code((0,ci._)`delete ${i}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ny.alwaysValidSchema)(s,r)){let g=e.name("valid");l.removeAdditional==="failing"?(h(y,g,!1),e.if((0,ci.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,ci.not)(g),()=>e.break()))}}function h(y,g,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:ny.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,g)}}};M$.default=v3});var nC=N(L$=>{"use strict";Object.defineProperty(L$,"__esModule",{value:!0});var _3=Cf(),tC=Dn(),D$=Ye(),rC=j$(),b3={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&rC.default.code(new _3.KeywordCxt(o,rC.default,"additionalProperties"));let s=(0,tC.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=D$.mergeEvaluated.props(e,(0,D$.toHash)(s),o.props));let a=s.filter(d=>!(0,D$.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,tC.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};L$.default=b3});var aC=N(U$=>{"use strict";Object.defineProperty(U$,"__esModule",{value:!0});var iC=Dn(),iy=Le(),oC=Ye(),sC=Ye(),w3={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,iC.allSchemaProperties)(r),l=a.filter(h=>(0,oC.alwaysValidSchema)(o,r[h]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof iy.Name)&&(o.props=(0,sC.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)c&&f(h),o.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function f(h){for(let y in c)new RegExp(h).test(y)&&(0,oC.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,iy._)`${(0,iC.usePattern)(t,h)}.test(${y})`,()=>{let g=l.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:sC.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,iy._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,iy.not)(u),()=>e.break())})})}}};U$.default=w3});var lC=N(Z$=>{"use strict";Object.defineProperty(Z$,"__esModule",{value:!0});var x3=Ye(),$3={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,x3.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Z$.default=$3});var cC=N(F$=>{"use strict";Object.defineProperty(F$,"__esModule",{value:!0});var k3=Dn(),S3={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:k3.validateUnion,error:{message:"must match a schema in anyOf"}};F$.default=S3});var uC=N(V$=>{"use strict";Object.defineProperty(V$,"__esModule",{value:!0});var oy=Le(),I3=Ye(),E3={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,oy._)`{passingSchemas: ${t.passing}}`},P3={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:E3,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let p;(0,I3.alwaysValidSchema)(i,u)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,oy._)`${l} && ${s}`).assign(s,!1).assign(a,(0,oy._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,oy.Name)})})}}};V$.default=P3});var dC=N(q$=>{"use strict";Object.defineProperty(q$,"__esModule",{value:!0});var T3=Ye(),A3={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,T3.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};q$.default=A3});var mC=N(W$=>{"use strict";Object.defineProperty(W$,"__esModule",{value:!0});var sy=Le(),pC=Ye(),z3={message:({params:t})=>(0,sy.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,sy._)`{failingKeyword: ${t.ifClause}}`},N3={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:z3,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,pC.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=fC(n,"then"),o=fC(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else i?e.if(a,c("then")):e.if((0,sy.not)(a),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let p=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,sy._)`${u}`):t.setParams({ifClause:u})}}}};function fC(t,e){let r=t.schema[e];return r!==void 0&&!(0,pC.alwaysValidSchema)(t,r)}W$.default=N3});var hC=N(B$=>{"use strict";Object.defineProperty(B$,"__esModule",{value:!0});var C3=Ye(),O3={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,C3.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};B$.default=O3});var gC=N(G$=>{"use strict";Object.defineProperty(G$,"__esModule",{value:!0});var R3=T$(),M3=BN(),j3=A$(),D3=HN(),L3=XN(),U3=YN(),Z3=eC(),F3=j$(),V3=nC(),q3=aC(),W3=lC(),B3=cC(),G3=uC(),H3=dC(),X3=mC(),K3=hC();function J3(t=!1){let e=[W3.default,B3.default,G3.default,H3.default,X3.default,K3.default,Z3.default,F3.default,U3.default,V3.default,q3.default];return t?e.push(M3.default,D3.default):e.push(R3.default,j3.default),e.push(L3.default),e}G$.default=J3});var yC=N(H$=>{"use strict";Object.defineProperty(H$,"__esModule",{value:!0});var Dt=Le(),Y3={message:({schemaCode:t})=>(0,Dt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Dt._)`{format: ${t}}`},Q3={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Y3,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=r.const("fDef",(0,Dt._)`${m}[${s}]`),y=r.let("fType"),g=r.let("format");r.if((0,Dt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Dt._)`${h}.type || "string"`).assign(g,(0,Dt._)`${h}.validate`),()=>r.assign(y,(0,Dt._)`"string"`).assign(g,h)),t.fail$data((0,Dt.or)(_(),b()));function _(){return l.strictSchema===!1?Dt.nil:(0,Dt._)`${s} && !${g}`}function b(){let E=u.$async?(0,Dt._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Dt._)`${g}(${n})`,I=(0,Dt._)`(typeof ${g} == "function" ? ${E} : ${g}.test(${n}))`;return(0,Dt._)`${g} && ${g} !== true && ${y} === ${e} && !${I}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,g]=b(m);h===e&&t.pass(E());function _(){if(l.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(I){let P=I instanceof RegExp?(0,Dt.regexpCode)(I):l.code.formats?(0,Dt._)`${l.code.formats}${(0,Dt.getProperty)(o)}`:void 0,M=r.scopeValue("formats",{key:o,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,Dt._)`${M}.validate`]:["string",I,M]}function E(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Dt._)`await ${g}(${n})`}return typeof y=="function"?(0,Dt._)`${g}(${n})`:(0,Dt._)`${g}.test(${n})`}}}};H$.default=Q3});var vC=N(X$=>{"use strict";Object.defineProperty(X$,"__esModule",{value:!0});var eW=yC(),tW=[eW.default];X$.default=tW});var _C=N(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.contentVocabulary=au.metadataVocabulary=void 0;au.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];au.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var wC=N(K$=>{"use strict";Object.defineProperty(K$,"__esModule",{value:!0});var rW=PN(),nW=FN(),iW=gC(),oW=vC(),bC=_C(),sW=[rW.default,nW.default,(0,iW.default)(),oW.default,bC.metadataVocabulary,bC.contentVocabulary];K$.default=sW});var $C=N(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});ay.DiscrError=void 0;var xC;(function(t){t.Tag="tag",t.Mapping="mapping"})(xC||(ay.DiscrError=xC={}))});var SC=N(Y$=>{"use strict";Object.defineProperty(Y$,"__esModule",{value:!0});var lu=Le(),J$=$C(),kC=Fg(),aW=Of(),lW=Ye(),cW={message:({params:{discrError:t,tagName:e}})=>t===J$.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uW={keyword:"discriminator",type:"object",schemaType:"object",error:cW,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,lu._)`${r}${(0,lu.getProperty)(a)}`);e.if((0,lu._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:J$.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,lu._)`${c} === ${m}`),e.assign(l,d(f[m]));e.else(),t.error(!1,{discrError:J$.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,lu.Name),m}function p(){var f;let m={},h=g(i),y=!0;for(let E=0;E<s.length;E++){let I=s[E];if(I?.$ref&&!(0,lW.schemaHasRulesButRef)(I,o.self.RULES)){let M=I.$ref;if(I=kC.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,M),I instanceof kC.SchemaEnv&&(I=I.schema),I===void 0)throw new aW.default(o.opts.uriResolver,o.baseId,M)}let P=(f=I?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(I)),_(P,E)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:E}){return Array.isArray(E)&&E.includes(a)}function _(E,I){if(E.const)b(E.const,I);else if(E.enum)for(let P of E.enum)b(P,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,I){if(typeof E!="string"||E in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[E]=I}}}};Y$.default=uW});var IC=N((ube,dW)=>{dW.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var PC=N(($t,Q$)=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.MissingRefError=$t.ValidationError=$t.CodeGen=$t.Name=$t.nil=$t.stringify=$t.str=$t._=$t.KeywordCxt=$t.Ajv=void 0;var fW=xN(),pW=wC(),mW=SC(),EC=IC(),hW=["/properties"],ly="http://json-schema.org/draft-07/schema",cu=class extends fW.default{_addVocabularies(){super._addVocabularies(),pW.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(mW.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(EC,hW):EC;this.addMetaSchema(e,ly,!1),this.refs["http://json-schema.org/schema"]=ly}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ly)?ly:void 0)}};$t.Ajv=cu;Q$.exports=$t=cu;Q$.exports.Ajv=cu;Object.defineProperty($t,"__esModule",{value:!0});$t.default=cu;var gW=Cf();Object.defineProperty($t,"KeywordCxt",{enumerable:!0,get:function(){return gW.KeywordCxt}});var uu=Le();Object.defineProperty($t,"_",{enumerable:!0,get:function(){return uu._}});Object.defineProperty($t,"str",{enumerable:!0,get:function(){return uu.str}});Object.defineProperty($t,"stringify",{enumerable:!0,get:function(){return uu.stringify}});Object.defineProperty($t,"nil",{enumerable:!0,get:function(){return uu.nil}});Object.defineProperty($t,"Name",{enumerable:!0,get:function(){return uu.Name}});Object.defineProperty($t,"CodeGen",{enumerable:!0,get:function(){return uu.CodeGen}});var yW=Ug();Object.defineProperty($t,"ValidationError",{enumerable:!0,get:function(){return yW.default}});var vW=Of();Object.defineProperty($t,"MissingRefError",{enumerable:!0,get:function(){return vW.default}})});var MC=N(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.formatNames=Di.fastFormats=Di.fullFormats=void 0;function ji(t,e){return{validate:t,compare:e}}Di.fullFormats={date:ji(NC,nk),time:ji(tk(!0),ik),"date-time":ji(TC(!0),OC),"iso-time":ji(tk(),CC),"iso-date-time":ji(TC(),RC),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kW,"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:zW,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:SW,int32:{type:"number",validate:PW},int64:{type:"number",validate:TW},float:{type:"number",validate:zC},double:{type:"number",validate:zC},password:!0,binary:!0};Di.fastFormats={...Di.fullFormats,date:ji(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nk),time:ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ik),"date-time":ji(/^\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,OC),"iso-time":ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,CC),"iso-date-time":ji(/^\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,RC),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};Di.formatNames=Object.keys(Di.fullFormats);function _W(t){return t%4===0&&(t%100!==0||t%400===0)}var bW=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wW=[0,31,28,31,30,31,30,31,31,30,31,30,31];function NC(t){let e=bW.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&_W(r)?29:wW[n])}function nk(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ek=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function tk(t){return function(r){let n=ek.exec(r);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],l=n[5]==="-"?-1:1,c=+(n[6]||0),u=+(n[7]||0);if(c>23||u>59||t&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let d=o-u*l,p=i-c*l-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function ik(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function CC(t,e){if(!(t&&e))return;let r=ek.exec(t),n=ek.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var rk=/t|\s/i;function TC(t){let e=tk(t);return function(n){let i=n.split(rk);return i.length===2&&NC(i[0])&&e(i[1])}}function OC(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function RC(t,e){if(!(t&&e))return;let[r,n]=t.split(rk),[i,o]=e.split(rk),s=nk(r,i);if(s!==void 0)return s||ik(n,o)}var xW=/\/|:/,$W=/^(?:[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 kW(t){return xW.test(t)&&$W.test(t)}var AC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SW(t){return AC.lastIndex=0,AC.test(t)}var IW=-(2**31),EW=2**31-1;function PW(t){return Number.isInteger(t)&&t<=EW&&t>=IW}function TW(t){return Number.isInteger(t)}function zC(){return!0}var AW=/[^\\]\\Z/;function zW(t){if(AW.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Kf=N(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.regexpCode=Qe.getEsmExportName=Qe.getProperty=Qe.safeStringify=Qe.stringify=Qe.strConcat=Qe.addCodeArg=Qe.str=Qe._=Qe.nil=Qe._Code=Qe.Name=Qe.IDENTIFIER=Qe._CodeOrName=void 0;var Hf=class{};Qe._CodeOrName=Hf;Qe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ja=class extends Hf{constructor(e){if(super(),!Qe.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}}};Qe.Name=ja;var Zn=class extends Hf{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ja&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Qe._Code=Zn;Qe.nil=new Zn("");function jC(t,...e){let r=[t[0]],n=0;for(;n<e.length;)sk(r,e[n]),r.push(t[++n]);return new Zn(r)}Qe._=jC;var ok=new Zn("+");function DC(t,...e){let r=[Xf(t[0])],n=0;for(;n<e.length;)r.push(ok),sk(r,e[n]),r.push(ok,Xf(t[++n]));return NW(r),new Zn(r)}Qe.str=DC;function sk(t,e){e instanceof Zn?t.push(...e._items):e instanceof ja?t.push(e):t.push(RW(e))}Qe.addCodeArg=sk;function NW(t){let e=1;for(;e<t.length-1;){if(t[e]===ok){let r=CW(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function CW(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ja||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 ja))return`"${t}${e.slice(1)}`}function OW(t,e){return e.emptyStr()?t:t.emptyStr()?e:DC`${t}${e}`}Qe.strConcat=OW;function RW(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xf(Array.isArray(t)?t.join(","):t)}function MW(t){return new Zn(Xf(t))}Qe.stringify=MW;function Xf(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Qe.safeStringify=Xf;function jW(t){return typeof t=="string"&&Qe.IDENTIFIER.test(t)?new Zn(`.${t}`):jC`[${t}]`}Qe.getProperty=jW;function DW(t){if(typeof t=="string"&&Qe.IDENTIFIER.test(t))return new Zn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Qe.getEsmExportName=DW;function LW(t){return new Zn(t.toString())}Qe.regexpCode=LW});var uk=N(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.ValueScope=Vr.ValueScopeName=Vr.Scope=Vr.varKinds=Vr.UsedValueState=void 0;var on=Kf(),ak=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},lk;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(lk=Vr.UsedValueState||(Vr.UsedValueState={}));Vr.varKinds={const:new on.Name("const"),let:new on.Name("let"),var:new on.Name("var")};var cy=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof on.Name?e:this.name(e)}name(e){return new on.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Vr.Scope=cy;var uy=class extends on.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,on._)`.${new on.Name(r)}[${n}]`}};Vr.ValueScopeName=uy;var UW=(0,on._)`\n`,ck=class extends cy{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?UW:on.nil}}get(){return this._scope}name(e){return new uy(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,i.setValue(r,{property:o,itemIndex:c}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,on._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=on.nil;for(let s in e){let a=e[s];if(!a)continue;let l=n[s]=n[s]||new Map;a.forEach(c=>{if(l.has(c))return;l.set(c,lk.Started);let u=r(c);if(u){let d=this.opts.es5?Vr.varKinds.var:Vr.varKinds.const;o=(0,on._)`${o}${d} ${c} = ${u};${this.opts._n}`}else if(u=i?.(c))o=(0,on._)`${o}${u}${this.opts._n}`;else throw new ak(c);l.set(c,lk.Completed)})}return o}};Vr.ValueScope=ck});var Ce=N(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.or=je.and=je.not=je.CodeGen=je.operators=je.varKinds=je.ValueScopeName=je.ValueScope=je.Scope=je.Name=je.regexpCode=je.stringify=je.getProperty=je.nil=je.strConcat=je.str=je._=void 0;var Be=Kf(),ui=uk(),$s=Kf();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return $s._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return $s.str}});Object.defineProperty(je,"strConcat",{enumerable:!0,get:function(){return $s.strConcat}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return $s.nil}});Object.defineProperty(je,"getProperty",{enumerable:!0,get:function(){return $s.getProperty}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return $s.stringify}});Object.defineProperty(je,"regexpCode",{enumerable:!0,get:function(){return $s.regexpCode}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return $s.Name}});var my=uk();Object.defineProperty(je,"Scope",{enumerable:!0,get:function(){return my.Scope}});Object.defineProperty(je,"ValueScope",{enumerable:!0,get:function(){return my.ValueScope}});Object.defineProperty(je,"ValueScopeName",{enumerable:!0,get:function(){return my.ValueScopeName}});Object.defineProperty(je,"varKinds",{enumerable:!0,get:function(){return my.varKinds}});je.operators={GT:new Be._Code(">"),GTE:new Be._Code(">="),LT:new Be._Code("<"),LTE:new Be._Code("<="),EQ:new Be._Code("==="),NEQ:new Be._Code("!=="),NOT:new Be._Code("!"),OR:new Be._Code("||"),AND:new Be._Code("&&"),ADD:new Be._Code("+")};var Eo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},dk=class extends Eo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ui.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=fu(this.rhs,e,r)),this}get names(){return this.rhs instanceof Be._CodeOrName?this.rhs.names:{}}},dy=class extends Eo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Be.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=fu(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Be.Name?{}:{...this.lhs.names};return py(e,this.rhs)}},fk=class extends dy{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},pk=class extends Eo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},mk=class extends Eo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},hk=class extends Eo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},gk=class extends Eo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=fu(this.code,e,r),this}get names(){return this.code instanceof Be._CodeOrName?this.code.names:{}}},Jf=class extends Eo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(ZW(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ua(e,r.names),{})}},Po=class extends Jf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},yk=class extends Jf{},du=class extends Po{};du.kind="else";var Da=class t extends Po{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new du(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(LC(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=fu(this.condition,e,r),this}get names(){let e=super.names;return py(e,this.condition),this.else&&Ua(e,this.else.names),e}};Da.kind="if";var La=class extends Po{};La.kind="for";var vk=class extends La{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=fu(this.iteration,e,r),this}get names(){return Ua(super.names,this.iteration.names)}},_k=class extends La{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?ui.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=py(super.names,this.from);return py(e,this.to)}},fy=class extends La{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=fu(this.iterable,e,r),this}get names(){return Ua(super.names,this.iterable.names)}},Yf=class extends Po{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Yf.kind="func";var Qf=class extends Jf{render(e){return"return "+super.render(e)}};Qf.kind="return";var bk=class extends Po{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ua(e,this.catch.names),this.finally&&Ua(e,this.finally.names),e}},ep=class extends Po{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ep.kind="catch";var tp=class extends Po{render(e){return"finally"+super.render(e)}};tp.kind="finally";var wk=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
9
+ `:""},this._extScope=e,this._scope=new ui.Scope({parent:e}),this._nodes=[new yk]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new dk(e,o,n)),o}const(e,r,n){return this._def(ui.varKinds.const,e,r,n)}let(e,r,n){return this._def(ui.varKinds.let,e,r,n)}var(e,r,n){return this._def(ui.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new dy(e,r,n))}add(e,r){return this._leafNode(new fk(e,je.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Be.nil&&this._leafNode(new gk(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Be.addCodeArg)(r,i));return r.push("}"),new Be._Code(r)}if(e,r,n){if(this._blockNode(new Da(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Da(e))}else(){return this._elseNode(new du)}endIf(){return this._endBlockNode(Da,du)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new vk(e),r)}forRange(e,r,n,i,o=this.opts.es5?ui.varKinds.var:ui.varKinds.let){let s=this._scope.toName(e);return this._for(new _k(o,s,r,n),()=>i(s))}forOf(e,r,n,i=ui.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof Be.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Be._)`${s}.length`,a=>{this.var(o,(0,Be._)`${s}[${a}]`),n(o)})}return this._for(new fy("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?ui.varKinds.var:ui.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Be._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new fy("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(La)}label(e){return this._leafNode(new pk(e))}break(e){return this._leafNode(new mk(e))}return(e){let r=new Qf;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Qf)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new bk;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new ep(o),r(o)}return n&&(this._currNode=i.finally=new tp,this.code(n)),this._endBlockNode(ep,tp)}throw(e){return this._leafNode(new hk(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Be.nil,n,i){return this._blockNode(new Yf(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Yf)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Da))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};je.CodeGen=wk;function Ua(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function py(t,e){return e instanceof Be._CodeOrName?Ua(t,e.names):t}function fu(t,e,r){if(t instanceof Be.Name)return n(t);if(!i(t))return t;return new Be._Code(t._items.reduce((o,s)=>(s instanceof Be.Name&&(s=n(s)),s instanceof Be._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof Be._Code&&o._items.some(s=>s instanceof Be.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function ZW(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function LC(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Be._)`!${xk(t)}`}je.not=LC;var FW=UC(je.operators.AND);function VW(...t){return t.reduce(FW)}je.and=VW;var qW=UC(je.operators.OR);function WW(...t){return t.reduce(qW)}je.or=WW;function UC(t){return(e,r)=>e===Be.nil?r:r===Be.nil?e:(0,Be._)`${xk(e)} ${t} ${xk(r)}`}function xk(t){return t instanceof Be.Name?t:(0,Be._)`(${t})`}});var et=N(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.checkStrictMode=De.getErrorPath=De.Type=De.useFunc=De.setEvaluated=De.evaluatedPropsToName=De.mergeEvaluated=De.eachItem=De.unescapeJsonPointer=De.escapeJsonPointer=De.escapeFragment=De.unescapeFragment=De.schemaRefOrVal=De.schemaHasRulesButRef=De.schemaHasRules=De.checkUnknownRules=De.alwaysValidSchema=De.toHash=void 0;var ht=Ce(),BW=Kf();function GW(t){let e={};for(let r of t)e[r]=!0;return e}De.toHash=GW;function HW(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(VC(t,e),!qC(e,t.self.RULES.all))}De.alwaysValidSchema=HW;function VC(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||HC(t,`unknown keyword: "${o}"`)}De.checkUnknownRules=VC;function qC(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}De.schemaHasRules=qC;function XW(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}De.schemaHasRulesButRef=XW;function KW({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ht._)`${r}`}return(0,ht._)`${t}${e}${(0,ht.getProperty)(n)}`}De.schemaRefOrVal=KW;function JW(t){return WC(decodeURIComponent(t))}De.unescapeFragment=JW;function YW(t){return encodeURIComponent($k(t))}De.escapeFragment=YW;function $k(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}De.escapeJsonPointer=$k;function WC(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}De.unescapeJsonPointer=WC;function QW(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}De.eachItem=QW;function ZC({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let l=s===void 0?o:s instanceof ht.Name?(o instanceof ht.Name?t(i,o,s):e(i,o,s),s):o instanceof ht.Name?(e(i,s,o),o):r(o,s);return a===ht.Name&&!(l instanceof ht.Name)?n(i,l):l}}De.mergeEvaluated={props:ZC({mergeNames:(t,e,r)=>t.if((0,ht._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ht._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ht._)`${r} || {}`).code((0,ht._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ht._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ht._)`${r} || {}`),kk(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:BC}),items:ZC({mergeNames:(t,e,r)=>t.if((0,ht._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ht._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ht._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ht._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function BC(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ht._)`{}`);return e!==void 0&&kk(t,r,e),r}De.evaluatedPropsToName=BC;function kk(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ht._)`${e}${(0,ht.getProperty)(n)}`,!0))}De.setEvaluated=kk;var FC={};function eB(t,e){return t.scopeValue("func",{ref:e,code:FC[e.code]||(FC[e.code]=new BW._Code(e.code))})}De.useFunc=eB;var GC;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(GC=De.Type||(De.Type={}));function tB(t,e,r){if(t instanceof ht.Name){let n=e===GC.Num;return r?n?(0,ht._)`"[" + ${t} + "]"`:(0,ht._)`"['" + ${t} + "']"`:n?(0,ht._)`"/" + ${t}`:(0,ht._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ht.getProperty)(t).toString():"/"+$k(t)}De.getErrorPath=tB;function HC(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}De.checkStrictMode=HC});var To=N(Sk=>{"use strict";Object.defineProperty(Sk,"__esModule",{value:!0});var Cr=Ce(),rB={data:new Cr.Name("data"),valCxt:new Cr.Name("valCxt"),instancePath:new Cr.Name("instancePath"),parentData:new Cr.Name("parentData"),parentDataProperty:new Cr.Name("parentDataProperty"),rootData:new Cr.Name("rootData"),dynamicAnchors:new Cr.Name("dynamicAnchors"),vErrors:new Cr.Name("vErrors"),errors:new Cr.Name("errors"),this:new Cr.Name("this"),self:new Cr.Name("self"),scope:new Cr.Name("scope"),json:new Cr.Name("json"),jsonPos:new Cr.Name("jsonPos"),jsonLen:new Cr.Name("jsonLen"),jsonPart:new Cr.Name("jsonPart")};Sk.default=rB});var rp=N(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.extendErrors=Or.resetErrorsCount=Or.reportExtraError=Or.reportError=Or.keyword$DataError=Or.keywordError=void 0;var Xe=Ce(),hy=et(),qr=To();Or.keywordError={message:({keyword:t})=>(0,Xe.str)`must pass "${t}" keyword validation`};Or.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Xe.str)`"${t}" keyword must be ${e} ($data)`:(0,Xe.str)`"${t}" keyword is invalid ($data)`};function nB(t,e=Or.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,l=JC(t,e,r);n??(s||a)?XC(o,l):KC(i,(0,Xe._)`[${l}]`)}Or.reportError=nB;function iB(t,e=Or.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=JC(t,e,r);XC(i,a),o||s||KC(n,qr.default.vErrors)}Or.reportExtraError=iB;function oB(t,e){t.assign(qr.default.errors,e),t.if((0,Xe._)`${qr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Xe._)`${qr.default.vErrors}.length`,e),()=>t.assign(qr.default.vErrors,null)))}Or.resetErrorsCount=oB;function sB({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,qr.default.errors,a=>{t.const(s,(0,Xe._)`${qr.default.vErrors}[${a}]`),t.if((0,Xe._)`${s}.instancePath === undefined`,()=>t.assign((0,Xe._)`${s}.instancePath`,(0,Xe.strConcat)(qr.default.instancePath,o.errorPath))),t.assign((0,Xe._)`${s}.schemaPath`,(0,Xe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,Xe._)`${s}.schema`,r),t.assign((0,Xe._)`${s}.data`,n))})}Or.extendErrors=sB;function XC(t,e){let r=t.const("err",e);t.if((0,Xe._)`${qr.default.vErrors} === null`,()=>t.assign(qr.default.vErrors,(0,Xe._)`[${r}]`),(0,Xe._)`${qr.default.vErrors}.push(${r})`),t.code((0,Xe._)`${qr.default.errors}++`)}function KC(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,Xe._)`new ${t.ValidationError}(${e})`):(r.assign((0,Xe._)`${n}.errors`,e),r.return(!1))}var Za={keyword:new Xe.Name("keyword"),schemaPath:new Xe.Name("schemaPath"),params:new Xe.Name("params"),propertyName:new Xe.Name("propertyName"),message:new Xe.Name("message"),schema:new Xe.Name("schema"),parentSchema:new Xe.Name("parentSchema")};function JC(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Xe._)`{}`:aB(t,e,r)}function aB(t,e,r={}){let{gen:n,it:i}=t,o=[lB(i,r),cB(t,r)];return uB(t,e,o),n.object(...o)}function lB({errorPath:t},{instancePath:e}){let r=e?(0,Xe.str)`${t}${(0,hy.getErrorPath)(e,hy.Type.Str)}`:t;return[qr.default.instancePath,(0,Xe.strConcat)(qr.default.instancePath,r)]}function cB({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,Xe.str)`${e}/${t}`;return r&&(i=(0,Xe.str)`${i}${(0,hy.getErrorPath)(r,hy.Type.Str)}`),[Za.schemaPath,i]}function uB(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=a;n.push([Za.keyword,i],[Za.params,typeof e=="function"?e(t):e||(0,Xe._)`{}`]),l.messages&&n.push([Za.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Za.schema,s],[Za.parentSchema,(0,Xe._)`${u}${d}`],[qr.default.data,o]),c&&n.push([Za.propertyName,c])}});var QC=N(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.boolOrEmptySchema=pu.topBoolOrEmptySchema=void 0;var dB=rp(),fB=Ce(),pB=To(),mB={message:"boolean schema is false"};function hB(t){let{gen:e,schema:r,validateName:n}=t;r===!1?YC(t,!1):typeof r=="object"&&r.$async===!0?e.return(pB.default.data):(e.assign((0,fB._)`${n}.errors`,null),e.return(!0))}pu.topBoolOrEmptySchema=hB;function gB(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),YC(t)):r.var(e,!0)}pu.boolOrEmptySchema=gB;function YC(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,dB.reportError)(i,mB,void 0,e)}});var Ik=N(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.getRules=mu.isJSONType=void 0;var yB=["string","number","integer","boolean","null","object","array"],vB=new Set(yB);function _B(t){return typeof t=="string"&&vB.has(t)}mu.isJSONType=_B;function bB(){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:{}}}mu.getRules=bB});var Ek=N(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.shouldUseRule=ks.shouldUseGroup=ks.schemaHasRulesForType=void 0;function wB({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&eO(t,n)}ks.schemaHasRulesForType=wB;function eO(t,e){return e.rules.some(r=>tO(t,r))}ks.shouldUseGroup=eO;function tO(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}ks.shouldUseRule=tO});var ip=N(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.reportTypeError=_r.checkDataTypes=_r.checkDataType=_r.coerceAndCheckDataType=_r.getJSONTypes=_r.getSchemaTypes=_r.DataType=void 0;var xB=Ik(),$B=Ek(),kB=rp(),Ne=Ce(),rO=et(),np;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(np=_r.DataType||(_r.DataType={}));function SB(t){let e=nO(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}_r.getSchemaTypes=SB;function nO(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(xB.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}_r.getJSONTypes=nO;function IB(t,e){let{gen:r,data:n,opts:i}=t,o=EB(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,$B.schemaHasRulesForType)(t,e[0]));if(s){let a=Tk(e,n,i.strictNumbers,np.Wrong);r.if(a,()=>{o.length?PB(t,e,o):Ak(t)})}return s}_r.coerceAndCheckDataType=IB;var iO=new Set(["string","number","integer","boolean","null"]);function EB(t,e){return e?t.filter(r=>iO.has(r)||e==="array"&&r==="array"):[]}function PB(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,Ne._)`typeof ${i}`),a=n.let("coerced",(0,Ne._)`undefined`);o.coerceTypes==="array"&&n.if((0,Ne._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,Ne._)`${i}[0]`).assign(s,(0,Ne._)`typeof ${i}`).if(Tk(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,Ne._)`${a} !== undefined`);for(let c of r)(iO.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Ak(t),n.endIf(),n.if((0,Ne._)`${a} !== undefined`,()=>{n.assign(i,a),TB(t,a)});function l(c){switch(c){case"string":n.elseIf((0,Ne._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,Ne._)`"" + ${i}`).elseIf((0,Ne._)`${i} === null`).assign(a,(0,Ne._)`""`);return;case"number":n.elseIf((0,Ne._)`${s} == "boolean" || ${i} === null
10
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,Ne._)`+${i}`);return;case"integer":n.elseIf((0,Ne._)`${s} === "boolean" || ${i} === null
11
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,Ne._)`+${i}`);return;case"boolean":n.elseIf((0,Ne._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,Ne._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Ne._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Ne._)`${s} === "string" || ${s} === "number"
12
+ || ${s} === "boolean" || ${i} === null`).assign(a,(0,Ne._)`[${i}]`)}}}function TB({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Ne._)`${e} !== undefined`,()=>t.assign((0,Ne._)`${e}[${r}]`,n))}function Pk(t,e,r,n=np.Correct){let i=n===np.Correct?Ne.operators.EQ:Ne.operators.NEQ,o;switch(t){case"null":return(0,Ne._)`${e} ${i} null`;case"array":o=(0,Ne._)`Array.isArray(${e})`;break;case"object":o=(0,Ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,Ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,Ne._)`typeof ${e} ${i} ${t}`}return n===np.Correct?o:(0,Ne.not)(o);function s(a=Ne.nil){return(0,Ne.and)((0,Ne._)`typeof ${e} == "number"`,a,r?(0,Ne._)`isFinite(${e})`:Ne.nil)}}_r.checkDataType=Pk;function Tk(t,e,r,n){if(t.length===1)return Pk(t[0],e,r,n);let i,o=(0,rO.toHash)(t);if(o.array&&o.object){let s=(0,Ne._)`typeof ${e} != "object"`;i=o.null?s:(0,Ne._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=Ne.nil;o.number&&delete o.integer;for(let s in o)i=(0,Ne.and)(i,Pk(s,e,r,n));return i}_r.checkDataTypes=Tk;var AB={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Ne._)`{type: ${t}}`:(0,Ne._)`{type: ${e}}`};function Ak(t){let e=zB(t);(0,kB.reportError)(e,AB)}_r.reportTypeError=Ak;function zB(t){let{gen:e,data:r,schema:n}=t,i=(0,rO.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var sO=N(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});gy.assignDefaults=void 0;var hu=Ce(),NB=et();function CB(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)oO(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>oO(t,o,i.default))}gy.assignDefaults=CB;function oO(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,hu._)`${o}${(0,hu.getProperty)(e)}`;if(i){(0,NB.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,hu._)`${a} === undefined`;s.useDefaults==="empty"&&(l=(0,hu._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,hu._)`${a} = ${(0,hu.stringify)(r)}`)}});var Fn=N(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateUnion=ft.validateArray=ft.usePattern=ft.callValidateCode=ft.schemaProperties=ft.allSchemaProperties=ft.noPropertyInData=ft.propertyInData=ft.isOwnProperty=ft.hasPropFunc=ft.reportMissingProp=ft.checkMissingProp=ft.checkReportMissingProp=void 0;var kt=Ce(),zk=et(),Ss=To(),OB=et();function RB(t,e){let{gen:r,data:n,it:i}=t;r.if(Ck(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,kt._)`${e}`},!0),t.error()})}ft.checkReportMissingProp=RB;function MB({gen:t,data:e,it:{opts:r}},n,i){return(0,kt.or)(...n.map(o=>(0,kt.and)(Ck(t,e,o,r.ownProperties),(0,kt._)`${i} = ${o}`)))}ft.checkMissingProp=MB;function jB(t,e){t.setParams({missingProperty:e},!0),t.error()}ft.reportMissingProp=jB;function aO(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,kt._)`Object.prototype.hasOwnProperty`})}ft.hasPropFunc=aO;function Nk(t,e,r){return(0,kt._)`${aO(t)}.call(${e}, ${r})`}ft.isOwnProperty=Nk;function DB(t,e,r,n){let i=(0,kt._)`${e}${(0,kt.getProperty)(r)} !== undefined`;return n?(0,kt._)`${i} && ${Nk(t,e,r)}`:i}ft.propertyInData=DB;function Ck(t,e,r,n){let i=(0,kt._)`${e}${(0,kt.getProperty)(r)} === undefined`;return n?(0,kt.or)(i,(0,kt.not)(Nk(t,e,r))):i}ft.noPropertyInData=Ck;function lO(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ft.allSchemaProperties=lO;function LB(t,e){return lO(e).filter(r=>!(0,zk.alwaysValidSchema)(t,e[r]))}ft.schemaProperties=LB;function UB({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,l,c){let u=c?(0,kt._)`${t}, ${e}, ${n}${i}`:e,d=[[Ss.default.instancePath,(0,kt.strConcat)(Ss.default.instancePath,o)],[Ss.default.parentData,s.parentData],[Ss.default.parentDataProperty,s.parentDataProperty],[Ss.default.rootData,Ss.default.rootData]];s.opts.dynamicRef&&d.push([Ss.default.dynamicAnchors,Ss.default.dynamicAnchors]);let p=(0,kt._)`${u}, ${r.object(...d)}`;return l!==kt.nil?(0,kt._)`${a}.call(${l}, ${p})`:(0,kt._)`${a}(${p})`}ft.callValidateCode=UB;var ZB=(0,kt._)`new RegExp`;function FB({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,kt._)`${i.code==="new RegExp"?ZB:(0,OB.useFunc)(t,i)}(${r}, ${n})`})}ft.usePattern=FB;function VB(t){let{gen:e,data:r,keyword:n,it:i}=t,o=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(o,!0),s(()=>e.break()),o;function s(a){let l=e.const("len",(0,kt._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:n,dataProp:c,dataPropType:zk.Type.Num},o),e.if((0,kt.not)(o),a)})}}ft.validateArray=VB;function qB(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,zk.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,c)=>{let u=t.subschema({keyword:n,schemaProp:c,compositeRule:!0},a);e.assign(s,(0,kt._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,kt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ft.validateUnion=qB});var dO=N(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.validateKeywordUsage=Li.validSchemaType=Li.funcKeywordCode=Li.macroKeywordCode=void 0;var Wr=Ce(),Fa=To(),WB=Fn(),BB=rp();function GB(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),l=uO(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let c=r.name("valid");t.subschema({schema:a,schemaPath:Wr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Li.macroKeywordCode=GB;function HB(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:l}=t;KB(l,e);let c=!a&&e.compile?e.compile.call(l.self,o,s,l):e.validate,u=uO(n,i,c),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&cO(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&cO(t),y(()=>XB(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Wr._)`await `),_=>n.assign(d,!1).if((0,Wr._)`${_} instanceof ${l.ValidationError}`,()=>n.assign(g,(0,Wr._)`${_}.errors`),()=>n.throw(_))),g}function m(){let g=(0,Wr._)`${u}.errors`;return n.assign(g,null),h(Wr.nil),g}function h(g=e.async?(0,Wr._)`await `:Wr.nil){let _=l.opts.passContext?Fa.default.this:Fa.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Wr._)`${g}${(0,WB.callValidateCode)(t,u,_,b)}`,e.modifying)}function y(g){var _;n.if((0,Wr.not)((_=e.valid)!==null&&_!==void 0?_:d),g)}}Li.funcKeywordCode=HB;function cO(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Wr._)`${n.parentData}[${n.parentDataProperty}]`))}function XB(t,e){let{gen:r}=t;r.if((0,Wr._)`Array.isArray(${e})`,()=>{r.assign(Fa.default.vErrors,(0,Wr._)`${Fa.default.vErrors} === null ? ${e} : ${Fa.default.vErrors}.concat(${e})`).assign(Fa.default.errors,(0,Wr._)`${Fa.default.vErrors}.length`),(0,BB.extendErrors)(t)},()=>t.error())}function KB({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function uO(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Wr.stringify)(r)})}function JB(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Li.validSchemaType=JB;function YB({schema:t,opts:e,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Li.validateKeywordUsage=YB});var pO=N(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.extendSubschemaMode=Is.extendSubschemaData=Is.getSubschema=void 0;var Ui=Ce(),fO=et();function QB(t,{keyword:e,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ui._)`${t.schemaPath}${(0,Ui.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ui._)`${t.schemaPath}${(0,Ui.getProperty)(e)}${(0,Ui.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,fO.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Is.getSubschema=QB;function eG(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=e,p=a.let("data",(0,Ui._)`${e.data}${(0,Ui.getProperty)(r)}`,!0);l(p),t.errorPath=(0,Ui.str)`${c}${(0,fO.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ui._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let c=i instanceof Ui.Name?i:a.let("data",i,!0);l(c),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}Is.extendSubschemaData=eG;function tG(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Is.extendSubschemaMode=tG});var op=N(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getSchemaRefs=sn.resolveUrl=sn.normalizeId=sn._getFullPath=sn.getFullPath=sn.inlineRef=void 0;var rG=et(),nG=Tf(),iG=Wx(),oG=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function sG(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ok(t):e?mO(t)<=e:!1}sn.inlineRef=sG;var aG=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ok(t){for(let e in t){if(aG.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ok)||typeof r=="object"&&Ok(r))return!0}return!1}function mO(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!oG.has(r)&&(typeof t[r]=="object"&&(0,rG.eachItem)(t[r],n=>e+=mO(n)),e===1/0))return 1/0}return e}function hO(t,e="",r){r!==!1&&(e=gu(e));let n=t.parse(e);return gO(t,n)}sn.getFullPath=hO;function gO(t,e){return t.serialize(e).split("#")[0]+"#"}sn._getFullPath=gO;var lG=/#\/?$/;function gu(t){return t?t.replace(lG,""):""}sn.normalizeId=gu;function cG(t,e,r){return r=gu(r),t.resolve(e,r)}sn.resolveUrl=cG;var uG=/^[a-z_][-a-z0-9._]*$/i;function dG(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=gu(t[r]||e),o={"":i},s=hO(n,i,!1),a={},l=new Set;return iG(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=s+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function g(b){let E=this.opts.uriResolver.resolve;if(b=gu(y?E(y,b):b),l.has(b))throw u(b);l.add(b);let I=this.refs[b];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?c(d,I.schema,b):b!==gu(h)&&(b[0]==="#"?(c(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!uG.test(b))throw new Error(`invalid anchor "${b}"`);g.call(this,`#${b}`)}}}),a;function c(d,p,f){if(p!==void 0&&!nG(d,p))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}sn.getSchemaRefs=dG});var lp=N(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.getData=Es.KeywordCxt=Es.validateFunctionCode=void 0;var wO=QC(),yO=ip(),Mk=Ek(),yy=ip(),fG=sO(),ap=dO(),Rk=pO(),ce=Ce(),$e=To(),pG=op(),Ao=et(),sp=rp();function mG(t){if(kO(t)&&(SO(t),$O(t))){yG(t);return}xO(t,()=>(0,wO.topBoolOrEmptySchema)(t))}Es.validateFunctionCode=mG;function xO({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,ce._)`${$e.default.data}, ${$e.default.valCxt}`,n.$async,()=>{t.code((0,ce._)`"use strict"; ${vO(r,i)}`),gG(t,i),t.code(o)}):t.func(e,(0,ce._)`${$e.default.data}, ${hG(i)}`,n.$async,()=>t.code(vO(r,i)).code(o))}function hG(t){return(0,ce._)`{${$e.default.instancePath}="", ${$e.default.parentData}, ${$e.default.parentDataProperty}, ${$e.default.rootData}=${$e.default.data}${t.dynamicRef?(0,ce._)`, ${$e.default.dynamicAnchors}={}`:ce.nil}}={}`}function gG(t,e){t.if($e.default.valCxt,()=>{t.var($e.default.instancePath,(0,ce._)`${$e.default.valCxt}.${$e.default.instancePath}`),t.var($e.default.parentData,(0,ce._)`${$e.default.valCxt}.${$e.default.parentData}`),t.var($e.default.parentDataProperty,(0,ce._)`${$e.default.valCxt}.${$e.default.parentDataProperty}`),t.var($e.default.rootData,(0,ce._)`${$e.default.valCxt}.${$e.default.rootData}`),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ce._)`${$e.default.valCxt}.${$e.default.dynamicAnchors}`)},()=>{t.var($e.default.instancePath,(0,ce._)`""`),t.var($e.default.parentData,(0,ce._)`undefined`),t.var($e.default.parentDataProperty,(0,ce._)`undefined`),t.var($e.default.rootData,$e.default.data),e.dynamicRef&&t.var($e.default.dynamicAnchors,(0,ce._)`{}`)})}function yG(t){let{schema:e,opts:r,gen:n}=t;xO(t,()=>{r.$comment&&e.$comment&&EO(t),xG(t),n.let($e.default.vErrors,null),n.let($e.default.errors,0),r.unevaluated&&vG(t),IO(t),SG(t)})}function vG(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ce._)`${r}.evaluated`),e.if((0,ce._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ce._)`${t.evaluated}.props`,(0,ce._)`undefined`)),e.if((0,ce._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ce._)`${t.evaluated}.items`,(0,ce._)`undefined`))}function vO(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ce._)`/*# sourceURL=${r} */`:ce.nil}function _G(t,e){if(kO(t)&&(SO(t),$O(t))){bG(t,e);return}(0,wO.boolOrEmptySchema)(t,e)}function $O({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function kO(t){return typeof t.schema!="boolean"}function bG(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&EO(t),$G(t),kG(t);let o=n.const("_errs",$e.default.errors);IO(t,o),n.var(e,(0,ce._)`${o} === ${$e.default.errors}`)}function SO(t){(0,Ao.checkUnknownRules)(t),wG(t)}function IO(t,e){if(t.opts.jtd)return _O(t,[],!1,e);let r=(0,yO.getSchemaTypes)(t.schema),n=(0,yO.coerceAndCheckDataType)(t,r);_O(t,r,!n,e)}function wG(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ao.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function xG(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ao.checkStrictMode)(t,"default is ignored in the schema root")}function $G(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,pG.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function kG(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function EO({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,ce._)`${$e.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,ce.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,ce._)`${$e.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function SG(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,ce._)`${$e.default.errors} === 0`,()=>e.return($e.default.data),()=>e.throw((0,ce._)`new ${i}(${$e.default.vErrors})`)):(e.assign((0,ce._)`${n}.errors`,$e.default.vErrors),o.unevaluated&&IG(t),e.return((0,ce._)`${$e.default.errors} === 0`))}function IG({gen:t,evaluated:e,props:r,items:n}){r instanceof ce.Name&&t.assign((0,ce._)`${e}.props`,r),n instanceof ce.Name&&t.assign((0,ce._)`${e}.items`,n)}function _O(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:l,self:c}=t,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Ao.schemaHasRulesButRef)(o,u))){i.block(()=>TO(t,"$ref",u.all.$ref.definition));return}l.jtd||EG(t,e),i.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){(0,Mk.shouldUseGroup)(o,p)&&(p.type?(i.if((0,yy.checkDataType)(p.type,s,l.strictNumbers)),bO(t,p),e.length===1&&e[0]===p.type&&r&&(i.else(),(0,yy.reportTypeError)(t)),i.endIf()):bO(t,p),a||i.if((0,ce._)`${$e.default.errors} === ${n||0}`))}}function bO(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,fG.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Mk.shouldUseRule)(n,o)&&TO(t,o.keyword,o.definition,e.type)})}function EG(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(PG(t,e),t.opts.allowUnionTypes||TG(t,e),AG(t,t.dataTypes))}function PG(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{PO(t.dataTypes,r)||jk(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),NG(t,e)}}function TG(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&jk(t,"use allowUnionTypes to allow union type keyword")}function AG(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Mk.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>zG(e,s))&&jk(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function zG(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function PO(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function NG(t,e){let r=[];for(let n of t.dataTypes)PO(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function jk(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ao.checkStrictMode)(t,e,t.opts.strictTypes)}var vy=class{constructor(e,r,n){if((0,ap.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ao.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",AO(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ap.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",$e.default.errors))}result(e,r,n){this.failResult((0,ce.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ce.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,ce._)`${r} !== undefined && (${(0,ce.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?sp.reportExtraError:sp.reportError)(this,this.def.error,r)}$dataError(){(0,sp.reportError)(this,this.def.$dataError||sp.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,sp.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=ce.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=ce.nil,r=ce.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,ce.or)((0,ce._)`${i} === undefined`,r)),e!==ce.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ce.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,ce.or)(s(),a());function s(){if(n.length){if(!(r instanceof ce.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,ce._)`${(0,yy.checkDataTypes)(l,r,o.opts.strictNumbers,yy.DataType.Wrong)}`}return ce.nil}function a(){if(i.validateSchema){let l=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,ce._)`!${l}(${r})`}return ce.nil}}subschema(e,r){let n=(0,Rk.getSubschema)(this.it,e);(0,Rk.extendSubschemaData)(n,this.it,e),(0,Rk.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return _G(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ao.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ao.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,ce.Name)),!0}};Es.KeywordCxt=vy;function TO(t,e,r,n){let i=new vy(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,ap.funcKeywordCode)(i,r):"macro"in r?(0,ap.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,ap.funcKeywordCode)(i,r)}var CG=/^\/(?:[^~]|~0|~1)*$/,OG=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function AO(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return $e.default.rootData;if(t[0]==="/"){if(!CG.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=$e.default.rootData}else{let c=OG.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+c[1];if(i=c[2],i==="#"){if(u>=e)throw new Error(l("property/index",u));return n[e-u]}if(u>e)throw new Error(l("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let c of a)c&&(o=(0,ce._)`${o}${(0,ce.getProperty)((0,Ao.unescapeJsonPointer)(c))}`,s=(0,ce._)`${s} && ${o}`);return s;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}Es.getData=AO});var _y=N(Lk=>{"use strict";Object.defineProperty(Lk,"__esModule",{value:!0});var Dk=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Lk.default=Dk});var by=N(Fk=>{"use strict";Object.defineProperty(Fk,"__esModule",{value:!0});var Uk=op(),Zk=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Uk.resolveUrl)(e,r,n),this.missingSchema=(0,Uk.normalizeId)((0,Uk.getFullPath)(e,this.missingRef))}};Fk.default=Zk});var xy=N(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.resolveSchema=Vn.getCompilingSchema=Vn.resolveRef=Vn.compileSchema=Vn.SchemaEnv=void 0;var di=Ce(),RG=_y(),Va=To(),fi=op(),zO=et(),MG=lp(),yu=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,fi.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Vn.SchemaEnv=yu;function qk(t){let e=NO.call(this,t);if(e)return e;let r=(0,fi.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new di.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:RG.default,code:(0,di._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let c={gen:s,allErrors:this.opts.allErrors,data:Va.default.data,parentData:Va.default.parentData,parentDataProperty:Va.default.parentDataProperty,dataNames:[Va.default.data],dataPathArr:[di.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,di.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:di.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,di._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,MG.validateFunctionCode)(c),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Va.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Va.default.self}`,`${Va.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=c;f.evaluated={props:m instanceof di.Name?void 0:m,items:h instanceof di.Name?void 0:h,dynamicProps:m instanceof di.Name,dynamicItems:h instanceof di.Name},f.source&&(f.source.evaluated=(0,di.stringify)(f.evaluated))}return t.validate=f,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)}}Vn.compileSchema=qk;function jG(t,e,r){var n;r=(0,fi.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=UG.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new yu({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=DG.call(this,o)}Vn.resolveRef=jG;function DG(t){return(0,fi.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qk.call(this,t)}function NO(t){for(let e of this._compilations)if(LG(e,t))return e}Vn.getCompilingSchema=NO;function LG(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function UG(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||wy.call(this,t,e)}function wy(t,e){let r=this.opts.uriResolver.parse(e),n=(0,fi._getFullPath)(this.opts.uriResolver,r),i=(0,fi.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return Vk.call(this,r,t);let o=(0,fi.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=wy.call(this,t,s);return typeof a?.schema!="object"?void 0:Vk.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||qk.call(this,s),o===(0,fi.normalizeId)(e)){let{schema:a}=s,{schemaId:l}=this.opts,c=a[l];return c&&(i=(0,fi.resolveUrl)(this.opts.uriResolver,i,c)),new yu({schema:a,schemaId:l,root:t,baseId:i})}return Vk.call(this,r,s)}}Vn.resolveSchema=wy;var ZG=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Vk(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,zO.unescapeFragment)(a)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!ZG.has(a)&&c&&(e=(0,fi.resolveUrl)(this.opts.uriResolver,e,c))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,zO.schemaHasRulesButRef)(r,this.RULES)){let a=(0,fi.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=wy.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new yu({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var CO=N((zbe,FG)=>{FG.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 RO=N(($y,OO)=>{"use strict";(function(t,e){typeof $y=="object"&&typeof OO<"u"?e($y):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})($y,function(t){"use strict";function e(){for(var w=arguments.length,v=Array(w),S=0;S<w;S++)v[S]=arguments[S];if(v.length>1){v[0]=v[0].slice(0,-1);for(var A=v.length-1,z=1;z<A;++z)v[z]=v[z].slice(1,-1);return v[A]=v[A].slice(1),v.join("")}else return v[0]}function r(w){return"(?:"+w+")"}function n(w){return w===void 0?"undefined":w===null?"null":Object.prototype.toString.call(w).split(" ").pop().split("]").shift().toLowerCase()}function i(w){return w.toUpperCase()}function o(w){return w!=null?w instanceof Array?w:typeof w.length!="number"||w.split||w.setInterval||w.call?[w]:Array.prototype.slice.call(w):[]}function s(w,v){var S=w;if(v)for(var A in v)S[A]=v[A];return S}function a(w){var v="[A-Za-z]",S="[\\x0D]",A="[0-9]",z="[\\x22]",re=e(A,"[A-Fa-f]"),Te="[\\x0A]",Ke="[\\x20]",ot=r(r("%[EFef]"+re+"%"+re+re+"%"+re+re)+"|"+r("%[89A-Fa-f]"+re+"%"+re+re)+"|"+r("%"+re+re)),Wt="[\\:\\/\\?\\#\\[\\]\\@]",Ge="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Tt=e(Wt,Ge),Bt=w?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",St=w?"[\\uE000-\\uF8FF]":"[]",tt=e(v,A,"[\\-\\.\\_\\~]",Bt),At=r(v+e(v,A,"[\\+\\-\\.]")+"*"),ct=r(r(ot+"|"+e(tt,Ge,"[\\:]"))+"*"),Ls=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("[1-9]"+A)+"|"+A),fn=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("0?[1-9]"+A)+"|0?0?"+A),An=r(fn+"\\."+fn+"\\."+fn+"\\."+fn),pt=r(re+"{1,4}"),pn=r(r(pt+"\\:"+pt)+"|"+An),zn=r(r(pt+"\\:")+"{6}"+pn),vi=r("\\:\\:"+r(pt+"\\:")+"{5}"+pn),Us=r(r(pt)+"?\\:\\:"+r(pt+"\\:")+"{4}"+pn),Ki=r(r(r(pt+"\\:")+"{0,1}"+pt)+"?\\:\\:"+r(pt+"\\:")+"{3}"+pn),Hu=r(r(r(pt+"\\:")+"{0,2}"+pt)+"?\\:\\:"+r(pt+"\\:")+"{2}"+pn),xm=r(r(r(pt+"\\:")+"{0,3}"+pt)+"?\\:\\:"+pt+"\\:"+pn),$m=r(r(r(pt+"\\:")+"{0,4}"+pt)+"?\\:\\:"+pn),cl=r(r(r(pt+"\\:")+"{0,5}"+pt)+"?\\:\\:"+pt),ul=r(r(r(pt+"\\:")+"{0,6}"+pt)+"?\\:\\:"),Ji=r([zn,vi,Us,Ki,Hu,xm,$m,cl,ul].join("|")),dl=r(r(tt+"|"+ot)+"+"),Qv=r(Ji+"\\%25"+dl),Zs=r(Ji+r("\\%25|\\%(?!"+re+"{2})")+dl),JD=r("[vV]"+re+"+\\."+e(tt,Ge,"[\\:]")+"+"),YD=r("\\["+r(Zs+"|"+Ji+"|"+JD)+"\\]"),pE=r(r(ot+"|"+e(tt,Ge))+"*"),Xu=r(YD+"|"+An+"(?!"+pE+")|"+pE),Ku=r(A+"*"),mE=r(r(ct+"@")+"?"+Xu+r("\\:"+Ku)+"?"),Ju=r(ot+"|"+e(tt,Ge,"[\\:\\@]")),QD=r(Ju+"*"),hE=r(Ju+"+"),e4=r(r(ot+"|"+e(tt,Ge,"[\\@]"))+"+"),Yi=r(r("\\/"+QD)+"*"),fl=r("\\/"+r(hE+Yi)+"?"),e_=r(e4+Yi),km=r(hE+Yi),pl="(?!"+Ju+")",ZY=r(Yi+"|"+fl+"|"+e_+"|"+km+"|"+pl),ml=r(r(Ju+"|"+e("[\\/\\?]",St))+"*"),Yu=r(r(Ju+"|[\\/\\?]")+"*"),gE=r(r("\\/\\/"+mE+Yi)+"|"+fl+"|"+km+"|"+pl),t4=r(At+"\\:"+gE+r("\\?"+ml)+"?"+r("\\#"+Yu)+"?"),r4=r(r("\\/\\/"+mE+Yi)+"|"+fl+"|"+e_+"|"+pl),n4=r(r4+r("\\?"+ml)+"?"+r("\\#"+Yu)+"?"),FY=r(t4+"|"+n4),VY=r(At+"\\:"+gE+r("\\?"+ml)+"?"),qY="^("+At+")\\:"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Xu+")"+r("\\:("+Ku+")")+"?)")+"?("+Yi+"|"+fl+"|"+km+"|"+pl+")")+r("\\?("+ml+")")+"?"+r("\\#("+Yu+")")+"?$",WY="^(){0}"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Xu+")"+r("\\:("+Ku+")")+"?)")+"?("+Yi+"|"+fl+"|"+e_+"|"+pl+")")+r("\\?("+ml+")")+"?"+r("\\#("+Yu+")")+"?$",BY="^("+At+")\\:"+r(r("\\/\\/("+r("("+ct+")@")+"?("+Xu+")"+r("\\:("+Ku+")")+"?)")+"?("+Yi+"|"+fl+"|"+km+"|"+pl+")")+r("\\?("+ml+")")+"?$",GY="^"+r("\\#("+Yu+")")+"?$",HY="^"+r("("+ct+")@")+"?("+Xu+")"+r("\\:("+Ku+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,A,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",tt,Ge),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",tt,Ge),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",tt,Ge),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",tt,Ge),"g"),NOT_QUERY:new RegExp(e("[^\\%]",tt,Ge,"[\\:\\@\\/\\?]",St),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",tt,Ge,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",tt,Ge),"g"),UNRESERVED:new RegExp(tt,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",tt,Tt),"g"),PCT_ENCODED:new RegExp(ot,"g"),IPV4ADDRESS:new RegExp("^("+An+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Ji+")"+r(r("\\%25|\\%(?!"+re+"{2})")+"("+dl+")")+"?\\]?$")}}var l=a(!1),c=a(!0),u=function(){function w(v,S){var A=[],z=!0,re=!1,Te=void 0;try{for(var Ke=v[Symbol.iterator](),ot;!(z=(ot=Ke.next()).done)&&(A.push(ot.value),!(S&&A.length===S));z=!0);}catch(Wt){re=!0,Te=Wt}finally{try{!z&&Ke.return&&Ke.return()}finally{if(re)throw Te}}return A}return function(v,S){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return w(v,S);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(w){if(Array.isArray(w)){for(var v=0,S=Array(w.length);v<w.length;v++)S[v]=w[v];return S}else return Array.from(w)},p=2147483647,f=36,m=1,h=26,y=38,g=700,_=72,b=128,E="-",I=/^xn--/,P=/[^\0-\x7E]/,M=/[\x2E\u3002\uFF0E\uFF61]/g,V={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},R=f-m,L=Math.floor,G=String.fromCharCode;function H(w){throw new RangeError(V[w])}function W(w,v){for(var S=[],A=w.length;A--;)S[A]=v(w[A]);return S}function Y(w,v){var S=w.split("@"),A="";S.length>1&&(A=S[0]+"@",w=S[1]),w=w.replace(M,".");var z=w.split("."),re=W(z,v).join(".");return A+re}function ie(w){for(var v=[],S=0,A=w.length;S<A;){var z=w.charCodeAt(S++);if(z>=55296&&z<=56319&&S<A){var re=w.charCodeAt(S++);(re&64512)==56320?v.push(((z&1023)<<10)+(re&1023)+65536):(v.push(z),S--)}else v.push(z)}return v}var Fe=function(v){return String.fromCodePoint.apply(String,d(v))},it=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f},Ot=function(v,S){return v+22+75*(v<26)-((S!=0)<<5)},Pt=function(v,S,A){var z=0;for(v=A?L(v/g):v>>1,v+=L(v/S);v>R*h>>1;z+=f)v=L(v/R);return L(z+(R+1)*v/(v+y))},x=function(v){var S=[],A=v.length,z=0,re=b,Te=_,Ke=v.lastIndexOf(E);Ke<0&&(Ke=0);for(var ot=0;ot<Ke;++ot)v.charCodeAt(ot)>=128&&H("not-basic"),S.push(v.charCodeAt(ot));for(var Wt=Ke>0?Ke+1:0;Wt<A;){for(var Ge=z,Tt=1,Bt=f;;Bt+=f){Wt>=A&&H("invalid-input");var St=it(v.charCodeAt(Wt++));(St>=f||St>L((p-z)/Tt))&&H("overflow"),z+=St*Tt;var tt=Bt<=Te?m:Bt>=Te+h?h:Bt-Te;if(St<tt)break;var At=f-tt;Tt>L(p/At)&&H("overflow"),Tt*=At}var ct=S.length+1;Te=Pt(z-Ge,ct,Ge==0),L(z/ct)>p-re&&H("overflow"),re+=L(z/ct),z%=ct,S.splice(z++,0,re)}return String.fromCodePoint.apply(String,S)},Dr=function(v){var S=[];v=ie(v);var A=v.length,z=b,re=0,Te=_,Ke=!0,ot=!1,Wt=void 0;try{for(var Ge=v[Symbol.iterator](),Tt;!(Ke=(Tt=Ge.next()).done);Ke=!0){var Bt=Tt.value;Bt<128&&S.push(G(Bt))}}catch(Zs){ot=!0,Wt=Zs}finally{try{!Ke&&Ge.return&&Ge.return()}finally{if(ot)throw Wt}}var St=S.length,tt=St;for(St&&S.push(E);tt<A;){var At=p,ct=!0,Ls=!1,fn=void 0;try{for(var An=v[Symbol.iterator](),pt;!(ct=(pt=An.next()).done);ct=!0){var pn=pt.value;pn>=z&&pn<At&&(At=pn)}}catch(Zs){Ls=!0,fn=Zs}finally{try{!ct&&An.return&&An.return()}finally{if(Ls)throw fn}}var zn=tt+1;At-z>L((p-re)/zn)&&H("overflow"),re+=(At-z)*zn,z=At;var vi=!0,Us=!1,Ki=void 0;try{for(var Hu=v[Symbol.iterator](),xm;!(vi=(xm=Hu.next()).done);vi=!0){var $m=xm.value;if($m<z&&++re>p&&H("overflow"),$m==z){for(var cl=re,ul=f;;ul+=f){var Ji=ul<=Te?m:ul>=Te+h?h:ul-Te;if(cl<Ji)break;var dl=cl-Ji,Qv=f-Ji;S.push(G(Ot(Ji+dl%Qv,0))),cl=L(dl/Qv)}S.push(G(Ot(cl,0))),Te=Pt(re,zn,tt==St),re=0,++tt}}}catch(Zs){Us=!0,Ki=Zs}finally{try{!vi&&Hu.return&&Hu.return()}finally{if(Us)throw Ki}}++re,++z}return S.join("")},Gn=function(v){return Y(v,function(S){return I.test(S)?x(S.slice(4).toLowerCase()):S})},k=function(v){return Y(v,function(S){return P.test(S)?"xn--"+Dr(S):S})},Vt={version:"2.1.0",ucs2:{decode:ie,encode:Fe},decode:x,encode:Dr,toASCII:k,toUnicode:Gn},qt={};function Xr(w){var v=w.charCodeAt(0),S=void 0;return v<16?S="%0"+v.toString(16).toUpperCase():v<128?S="%"+v.toString(16).toUpperCase():v<2048?S="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():S="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),S}function Hn(w){for(var v="",S=0,A=w.length;S<A;){var z=parseInt(w.substr(S+1,2),16);if(z<128)v+=String.fromCharCode(z),S+=3;else if(z>=194&&z<224){if(A-S>=6){var re=parseInt(w.substr(S+4,2),16);v+=String.fromCharCode((z&31)<<6|re&63)}else v+=w.substr(S,6);S+=6}else if(z>=224){if(A-S>=9){var Te=parseInt(w.substr(S+4,2),16),Ke=parseInt(w.substr(S+7,2),16);v+=String.fromCharCode((z&15)<<12|(Te&63)<<6|Ke&63)}else v+=w.substr(S,9);S+=9}else v+=w.substr(S,3),S+=3}return v}function Rt(w,v){function S(A){var z=Hn(A);return z.match(v.UNRESERVED)?z:A}return w.scheme&&(w.scheme=String(w.scheme).replace(v.PCT_ENCODED,S).toLowerCase().replace(v.NOT_SCHEME,"")),w.userinfo!==void 0&&(w.userinfo=String(w.userinfo).replace(v.PCT_ENCODED,S).replace(v.NOT_USERINFO,Xr).replace(v.PCT_ENCODED,i)),w.host!==void 0&&(w.host=String(w.host).replace(v.PCT_ENCODED,S).toLowerCase().replace(v.NOT_HOST,Xr).replace(v.PCT_ENCODED,i)),w.path!==void 0&&(w.path=String(w.path).replace(v.PCT_ENCODED,S).replace(w.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Xr).replace(v.PCT_ENCODED,i)),w.query!==void 0&&(w.query=String(w.query).replace(v.PCT_ENCODED,S).replace(v.NOT_QUERY,Xr).replace(v.PCT_ENCODED,i)),w.fragment!==void 0&&(w.fragment=String(w.fragment).replace(v.PCT_ENCODED,S).replace(v.NOT_FRAGMENT,Xr).replace(v.PCT_ENCODED,i)),w}function Hi(w){return w.replace(/^0*(.*)/,"$1")||"0"}function Kr(w,v){var S=w.match(v.IPV4ADDRESS)||[],A=u(S,2),z=A[1];return z?z.split(".").map(Hi).join("."):w}function Xi(w,v){var S=w.match(v.IPV6ADDRESS)||[],A=u(S,3),z=A[1],re=A[2];if(z){for(var Te=z.toLowerCase().split("::").reverse(),Ke=u(Te,2),ot=Ke[0],Wt=Ke[1],Ge=Wt?Wt.split(":").map(Hi):[],Tt=ot.split(":").map(Hi),Bt=v.IPV4ADDRESS.test(Tt[Tt.length-1]),St=Bt?7:8,tt=Tt.length-St,At=Array(St),ct=0;ct<St;++ct)At[ct]=Ge[ct]||Tt[tt+ct]||"";Bt&&(At[St-1]=Kr(At[St-1],v));var Ls=At.reduce(function(zn,vi,Us){if(!vi||vi==="0"){var Ki=zn[zn.length-1];Ki&&Ki.index+Ki.length===Us?Ki.length++:zn.push({index:Us,length:1})}return zn},[]),fn=Ls.sort(function(zn,vi){return vi.length-zn.length})[0],An=void 0;if(fn&&fn.length>1){var pt=At.slice(0,fn.index),pn=At.slice(fn.index+fn.length);An=pt.join(":")+"::"+pn.join(":")}else An=At.join(":");return re&&(An+="%"+re),An}else return w}var jo=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Wu="".match(/(){0}/)[1]===void 0;function En(w){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S={},A=v.iri!==!1?c:l;v.reference==="suffix"&&(w=(v.scheme?v.scheme+":":"")+"//"+w);var z=w.match(jo);if(z){Wu?(S.scheme=z[1],S.userinfo=z[3],S.host=z[4],S.port=parseInt(z[5],10),S.path=z[6]||"",S.query=z[7],S.fragment=z[8],isNaN(S.port)&&(S.port=z[5])):(S.scheme=z[1]||void 0,S.userinfo=w.indexOf("@")!==-1?z[3]:void 0,S.host=w.indexOf("//")!==-1?z[4]:void 0,S.port=parseInt(z[5],10),S.path=z[6]||"",S.query=w.indexOf("?")!==-1?z[7]:void 0,S.fragment=w.indexOf("#")!==-1?z[8]:void 0,isNaN(S.port)&&(S.port=w.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?z[4]:void 0)),S.host&&(S.host=Xi(Kr(S.host,A),A)),S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&!S.path&&S.query===void 0?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==S.reference&&(S.error=S.error||"URI is not a "+v.reference+" reference.");var re=qt[(v.scheme||S.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!re||!re.unicodeSupport)){if(S.host&&(v.domainHost||re&&re.domainHost))try{S.host=Vt.toASCII(S.host.replace(A.PCT_ENCODED,Hn).toLowerCase())}catch(Te){S.error=S.error||"Host's domain name can not be converted to ASCII via punycode: "+Te}Rt(S,l)}else Rt(S,A);re&&re.parse&&re.parse(S,v)}else S.error=S.error||"URI can not be parsed.";return S}function vm(w,v){var S=v.iri!==!1?c:l,A=[];return w.userinfo!==void 0&&(A.push(w.userinfo),A.push("@")),w.host!==void 0&&A.push(Xi(Kr(String(w.host),S),S).replace(S.IPV6ADDRESS,function(z,re,Te){return"["+re+(Te?"%25"+Te:"")+"]"})),(typeof w.port=="number"||typeof w.port=="string")&&(A.push(":"),A.push(String(w.port))),A.length?A.join(""):void 0}var Bu=/^\.\.?\//,_m=/^\/\.(\/|$)/,Gu=/^\/\.\.(\/|$)/,bm=/^\/?(?:.|\n)*?(?=\/|$)/;function Do(w){for(var v=[];w.length;)if(w.match(Bu))w=w.replace(Bu,"");else if(w.match(_m))w=w.replace(_m,"/");else if(w.match(Gu))w=w.replace(Gu,"/"),v.pop();else if(w==="."||w==="..")w="";else{var S=w.match(bm);if(S){var A=S[0];w=w.slice(A.length),v.push(A)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function Pn(w){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S=v.iri?c:l,A=[],z=qt[(v.scheme||w.scheme||"").toLowerCase()];if(z&&z.serialize&&z.serialize(w,v),w.host&&!S.IPV6ADDRESS.test(w.host)){if(v.domainHost||z&&z.domainHost)try{w.host=v.iri?Vt.toUnicode(w.host):Vt.toASCII(w.host.replace(S.PCT_ENCODED,Hn).toLowerCase())}catch(Ke){w.error=w.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Ke}}Rt(w,S),v.reference!=="suffix"&&w.scheme&&(A.push(w.scheme),A.push(":"));var re=vm(w,v);if(re!==void 0&&(v.reference!=="suffix"&&A.push("//"),A.push(re),w.path&&w.path.charAt(0)!=="/"&&A.push("/")),w.path!==void 0){var Te=w.path;!v.absolutePath&&(!z||!z.absolutePath)&&(Te=Do(Te)),re===void 0&&(Te=Te.replace(/^\/\//,"/%2F")),A.push(Te)}return w.query!==void 0&&(A.push("?"),A.push(w.query)),w.fragment!==void 0&&(A.push("#"),A.push(w.fragment)),A.join("")}function wm(w,v){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],z={};return A||(w=En(Pn(w,S),S),v=En(Pn(v,S),S)),S=S||{},!S.tolerant&&v.scheme?(z.scheme=v.scheme,z.userinfo=v.userinfo,z.host=v.host,z.port=v.port,z.path=Do(v.path||""),z.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(z.userinfo=v.userinfo,z.host=v.host,z.port=v.port,z.path=Do(v.path||""),z.query=v.query):(v.path?(v.path.charAt(0)==="/"?z.path=Do(v.path):((w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)&&!w.path?z.path="/"+v.path:w.path?z.path=w.path.slice(0,w.path.lastIndexOf("/")+1)+v.path:z.path=v.path,z.path=Do(z.path)),z.query=v.query):(z.path=w.path,v.query!==void 0?z.query=v.query:z.query=w.query),z.userinfo=w.userinfo,z.host=w.host,z.port=w.port),z.scheme=w.scheme),z.fragment=v.fragment,z}function Kv(w,v,S){var A=s({scheme:"null"},S);return Pn(wm(En(w,A),En(v,A),A,!0),A)}function Jv(w,v){return typeof w=="string"?w=Pn(En(w,v),v):n(w)==="object"&&(w=En(Pn(w,v),v)),w}function j(w,v,S){return typeof w=="string"?w=Pn(En(w,S),S):n(w)==="object"&&(w=Pn(w,S)),typeof v=="string"?v=Pn(En(v,S),S):n(v)==="object"&&(v=Pn(v,S)),w===v}function K(w,v){return w&&w.toString().replace(!v||!v.iri?l.ESCAPE:c.ESCAPE,Xr)}function fe(w,v){return w&&w.toString().replace(!v||!v.iri?l.PCT_ENCODED:c.PCT_ENCODED,Hn)}var Pe={scheme:"http",domainHost:!0,parse:function(v,S){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,S){var A=String(v.scheme).toLowerCase()==="https";return(v.port===(A?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},nt={scheme:"https",domainHost:Pe.domainHost,parse:Pe.parse,serialize:Pe.serialize};function Jr(w){return typeof w.secure=="boolean"?w.secure:String(w.scheme).toLowerCase()==="wss"}var dn={scheme:"ws",domainHost:!0,parse:function(v,S){var A=v;return A.secure=Jr(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(v,S){if((v.port===(Jr(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var A=v.resourceName.split("?"),z=u(A,2),re=z[0],Te=z[1];v.path=re&&re!=="/"?re:void 0,v.query=Te,v.resourceName=void 0}return v.fragment=void 0,v}},Tn={scheme:"wss",domainHost:dn.domainHost,parse:dn.parse,serialize:dn.serialize},js={},Ds=!0,$r="[A-Za-z0-9\\-\\.\\_\\~"+(Ds?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",lr="[0-9A-Fa-f]",Xn=r(r("%[EFef]"+lr+"%"+lr+lr+"%"+lr+lr)+"|"+r("%[89A-Fa-f]"+lr+"%"+lr+lr)+"|"+r("%"+lr+lr)),FD="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",VD="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",qD=e(VD,'[\\"\\\\]'),WD="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",BD=new RegExp($r,"g"),ll=new RegExp(Xn,"g"),GD=new RegExp(e("[^]",FD,"[\\.]",'[\\"]',qD),"g"),cE=new RegExp(e("[^]",$r,WD),"g"),HD=cE;function Yv(w){var v=Hn(w);return v.match(BD)?v:w}var uE={scheme:"mailto",parse:function(v,S){var A=v,z=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var re=!1,Te={},Ke=A.query.split("&"),ot=0,Wt=Ke.length;ot<Wt;++ot){var Ge=Ke[ot].split("=");switch(Ge[0]){case"to":for(var Tt=Ge[1].split(","),Bt=0,St=Tt.length;Bt<St;++Bt)z.push(Tt[Bt]);break;case"subject":A.subject=fe(Ge[1],S);break;case"body":A.body=fe(Ge[1],S);break;default:re=!0,Te[fe(Ge[0],S)]=fe(Ge[1],S);break}}re&&(A.headers=Te)}A.query=void 0;for(var tt=0,At=z.length;tt<At;++tt){var ct=z[tt].split("@");if(ct[0]=fe(ct[0]),S.unicodeSupport)ct[1]=fe(ct[1],S).toLowerCase();else try{ct[1]=Vt.toASCII(fe(ct[1],S).toLowerCase())}catch(Ls){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ls}z[tt]=ct.join("@")}return A},serialize:function(v,S){var A=v,z=o(v.to);if(z){for(var re=0,Te=z.length;re<Te;++re){var Ke=String(z[re]),ot=Ke.lastIndexOf("@"),Wt=Ke.slice(0,ot).replace(ll,Yv).replace(ll,i).replace(GD,Xr),Ge=Ke.slice(ot+1);try{Ge=S.iri?Vt.toUnicode(Ge):Vt.toASCII(fe(Ge,S).toLowerCase())}catch(tt){A.error=A.error||"Email address's domain name can not be converted to "+(S.iri?"Unicode":"ASCII")+" via punycode: "+tt}z[re]=Wt+"@"+Ge}A.path=z.join(",")}var Tt=v.headers=v.headers||{};v.subject&&(Tt.subject=v.subject),v.body&&(Tt.body=v.body);var Bt=[];for(var St in Tt)Tt[St]!==js[St]&&Bt.push(St.replace(ll,Yv).replace(ll,i).replace(cE,Xr)+"="+Tt[St].replace(ll,Yv).replace(ll,i).replace(HD,Xr));return Bt.length&&(A.query=Bt.join("&")),A}},XD=/^([^\:]+)\:(.*)/,dE={scheme:"urn",parse:function(v,S){var A=v.path&&v.path.match(XD),z=v;if(A){var re=S.scheme||z.scheme||"urn",Te=A[1].toLowerCase(),Ke=A[2],ot=re+":"+(S.nid||Te),Wt=qt[ot];z.nid=Te,z.nss=Ke,z.path=void 0,Wt&&(z=Wt.parse(z,S))}else z.error=z.error||"URN can not be parsed.";return z},serialize:function(v,S){var A=S.scheme||v.scheme||"urn",z=v.nid,re=A+":"+(S.nid||z),Te=qt[re];Te&&(v=Te.serialize(v,S));var Ke=v,ot=v.nss;return Ke.path=(z||S.nid)+":"+ot,Ke}},KD=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,fE={scheme:"urn:uuid",parse:function(v,S){var A=v;return A.uuid=A.nss,A.nss=void 0,!S.tolerant&&(!A.uuid||!A.uuid.match(KD))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(v,S){var A=v;return A.nss=(v.uuid||"").toLowerCase(),A}};qt[Pe.scheme]=Pe,qt[nt.scheme]=nt,qt[dn.scheme]=dn,qt[Tn.scheme]=Tn,qt[uE.scheme]=uE,qt[dE.scheme]=dE,qt[fE.scheme]=fE,t.SCHEMES=qt,t.pctEncChar=Xr,t.pctDecChars=Hn,t.parse=En,t.removeDotSegments=Do,t.serialize=Pn,t.resolveComponents=wm,t.resolve=Kv,t.normalize=Jv,t.equal=j,t.escapeComponent=K,t.unescapeComponent=fe,Object.defineProperty(t,"__esModule",{value:!0})})});var jO=N(Wk=>{"use strict";Object.defineProperty(Wk,"__esModule",{value:!0});var MO=RO();MO.code='require("ajv/dist/runtime/uri").default';Wk.default=MO});var WO=N(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.CodeGen=br.Name=br.nil=br.stringify=br.str=br._=br.KeywordCxt=void 0;var VG=lp();Object.defineProperty(br,"KeywordCxt",{enumerable:!0,get:function(){return VG.KeywordCxt}});var vu=Ce();Object.defineProperty(br,"_",{enumerable:!0,get:function(){return vu._}});Object.defineProperty(br,"str",{enumerable:!0,get:function(){return vu.str}});Object.defineProperty(br,"stringify",{enumerable:!0,get:function(){return vu.stringify}});Object.defineProperty(br,"nil",{enumerable:!0,get:function(){return vu.nil}});Object.defineProperty(br,"Name",{enumerable:!0,get:function(){return vu.Name}});Object.defineProperty(br,"CodeGen",{enumerable:!0,get:function(){return vu.CodeGen}});var qG=_y(),FO=by(),WG=Ik(),cp=xy(),BG=Ce(),up=op(),ky=ip(),Gk=et(),DO=CO(),GG=jO(),VO=(t,e)=>new RegExp(t,e);VO.code="new RegExp";var HG=["removeAdditional","useDefaults","coerceTypes"],XG=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),KG={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."},JG={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},LO=200;function YG(t){var e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R;let L=t.strict,G=(e=t.code)===null||e===void 0?void 0:e.optimize,H=G===!0||G===void 0?1:G||0,W=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:VO,Y=(i=t.uriResolver)!==null&&i!==void 0?i:GG.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:L)!==null&&s!==void 0?s:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:L)!==null&&l!==void 0?l:!0,strictTypes:(u=(c=t.strictTypes)!==null&&c!==void 0?c:L)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:L)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:L)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:H,regExp:W}:{optimize:H,regExp:W},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:LO,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:LO,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(E=t.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(M=t.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(V=t.unicodeRegExp)!==null&&V!==void 0?V:!0,int32range:(R=t.int32range)!==null&&R!==void 0?R:!0,uriResolver:Y}}var dp=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...YG(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new BG.ValueScope({scope:{},prefixes:XG,es5:r,lines:n}),this.logger=iH(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,WG.getRules)(),UO.call(this,KG,e,"NOT SUPPORTED"),UO.call(this,JG,e,"DEPRECATED","warn"),this._metaOpts=rH.call(this),e.formats&&eH.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&tH.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),QG.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=DO;n==="id"&&(i={...DO},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,r);async function i(u,d){await o.call(this,u.$schema);let p=this._addSchema(u,d);return p.validate||s.call(this,p)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof FO.default))throw d;return a.call(this,d),await l.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 l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,up.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(e){let r;for(;typeof(r=ZO.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new cp.SchemaEnv({schema:{},schemaId:n});if(r=cp.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ZO.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,up.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(sH.call(this,n,r),!r)return(0,Gk.eachItem)(n,o=>Bk.call(this,o)),this;lH.call(this,r);let i={...r,type:(0,ky.getJSONTypes)(r.type),schemaType:(0,ky.getJSONTypes)(r.schemaType)};return(0,Gk.eachItem)(n,i.type.length===0?o=>Bk.call(this,o,i):o=>i.type.forEach(s=>Bk.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:c}=l.definition,u=s[a];c&&u&&(s[a]=qO(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,n,i=this.opts.validateSchema,o=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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,up.normalizeId)(s||n);let c=up.getSchemaRefs.call(this,e,n);return l=new cp.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),i&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):cp.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{cp.compileSchema.call(this,e)}finally{this.opts=r}}};br.default=dp;dp.ValidationError=qG.default;dp.MissingRefError=FO.default;function UO(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function ZO(t){return t=(0,up.normalizeId)(t),this.schemas[t]||this.refs[t]}function QG(){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 eH(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function tH(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function rH(){let t={...this.opts};for(let e of HG)delete t[e];return t}var nH={log(){},warn(){},error(){}};function iH(t){if(t===!1)return nH;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 oH=/^[a-z_$][a-z0-9_$:-]*$/i;function sH(t,e){let{RULES:r}=this;if((0,Gk.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!oH.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Bk(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:l})=>l===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ky.getJSONTypes)(e.type),schemaType:(0,ky.getJSONTypes)(e.schemaType)}};e.before?aH.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function aH(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function lH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=qO(e)),t.validateSchema=this.compile(e,!0))}var cH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qO(t){return{anyOf:[t,cH]}}});var BO=N(Hk=>{"use strict";Object.defineProperty(Hk,"__esModule",{value:!0});var uH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Hk.default=uH});var KO=N(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.callRef=qa.getValidate=void 0;var dH=by(),GO=Fn(),an=Ce(),_u=To(),HO=xy(),Sy=et(),fH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&i===c.baseId)return d();let u=HO.resolveRef.call(l,c,i,r);if(u===void 0)throw new dH.default(n.opts.uriResolver,i,r);if(u instanceof HO.SchemaEnv)return p(u);return f(u);function d(){if(o===c)return Iy(t,s,o,o.$async);let m=e.scopeValue("root",{ref:c});return Iy(t,(0,an._)`${m}.validate`,c,c.$async)}function p(m){let h=XO(t,m);Iy(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,an.stringify)(m)}:{ref:m}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:an.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function XO(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,an._)`${r.scopeValue("wrapper",{ref:e})}.validate`}qa.getValidate=XO;function Iy(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:l}=o,c=l.passContext?_u.default.this:an.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,an._)`await ${(0,GO.callValidateCode)(t,e,c)}`),f(e),s||i.assign(m,!0)},h=>{i.if((0,an._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),p(h),s||i.assign(m,!1)}),t.ok(m)}function d(){t.result((0,GO.callValidateCode)(t,e,c),()=>f(e),()=>p(e))}function p(m){let h=(0,an._)`${m}.errors`;i.assign(_u.default.vErrors,(0,an._)`${_u.default.vErrors} === null ? ${h} : ${_u.default.vErrors}.concat(${h})`),i.assign(_u.default.errors,(0,an._)`${_u.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Sy.mergeEvaluated.props(i,y.props,o.props));else{let g=i.var("props",(0,an._)`${m}.evaluated.props`);o.props=Sy.mergeEvaluated.props(i,g,o.props,an.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Sy.mergeEvaluated.items(i,y.items,o.items));else{let g=i.var("items",(0,an._)`${m}.evaluated.items`);o.items=Sy.mergeEvaluated.items(i,g,o.items,an.Name)}}}qa.callRef=Iy;qa.default=fH});var JO=N(Xk=>{"use strict";Object.defineProperty(Xk,"__esModule",{value:!0});var pH=BO(),mH=KO(),hH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",pH.default,mH.default];Xk.default=hH});var YO=N(Kk=>{"use strict";Object.defineProperty(Kk,"__esModule",{value:!0});var Ey=Ce(),Ps=Ey.operators,Py={maximum:{okStr:"<=",ok:Ps.LTE,fail:Ps.GT},minimum:{okStr:">=",ok:Ps.GTE,fail:Ps.LT},exclusiveMaximum:{okStr:"<",ok:Ps.LT,fail:Ps.GTE},exclusiveMinimum:{okStr:">",ok:Ps.GT,fail:Ps.LTE}},gH={message:({keyword:t,schemaCode:e})=>(0,Ey.str)`must be ${Py[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ey._)`{comparison: ${Py[t].okStr}, limit: ${e}}`},yH={keyword:Object.keys(Py),type:"number",schemaType:"number",$data:!0,error:gH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ey._)`${r} ${Py[e].fail} ${n} || isNaN(${r})`)}};Kk.default=yH});var QO=N(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0});var fp=Ce(),vH={message:({schemaCode:t})=>(0,fp.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,fp._)`{multipleOf: ${t}}`},_H={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vH,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,fp._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,fp._)`${s} !== parseInt(${s})`;t.fail$data((0,fp._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Jk.default=_H});var tR=N(Yk=>{"use strict";Object.defineProperty(Yk,"__esModule",{value:!0});function eR(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}Yk.default=eR;eR.code='require("ajv/dist/runtime/ucs2length").default'});var rR=N(Qk=>{"use strict";Object.defineProperty(Qk,"__esModule",{value:!0});var Wa=Ce(),bH=et(),wH=tR(),xH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wa.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wa._)`{limit: ${t}}`},$H={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xH,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Wa.operators.GT:Wa.operators.LT,s=i.opts.unicode===!1?(0,Wa._)`${r}.length`:(0,Wa._)`${(0,bH.useFunc)(t.gen,wH.default)}(${r})`;t.fail$data((0,Wa._)`${s} ${o} ${n}`)}};Qk.default=$H});var nR=N(eS=>{"use strict";Object.defineProperty(eS,"__esModule",{value:!0});var kH=Fn(),Ty=Ce(),SH={message:({schemaCode:t})=>(0,Ty.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ty._)`{pattern: ${t}}`},IH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:SH,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Ty._)`(new RegExp(${i}, ${s}))`:(0,kH.usePattern)(t,n);t.fail$data((0,Ty._)`!${a}.test(${e})`)}};eS.default=IH});var iR=N(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});var pp=Ce(),EH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,pp.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,pp._)`{limit: ${t}}`},PH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?pp.operators.GT:pp.operators.LT;t.fail$data((0,pp._)`Object.keys(${r}).length ${i} ${n}`)}};tS.default=PH});var oR=N(rS=>{"use strict";Object.defineProperty(rS,"__esModule",{value:!0});var mp=Fn(),hp=Ce(),TH=et(),AH={message:({params:{missingProperty:t}})=>(0,hp.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,hp._)`{missingProperty: ${t}}`},zH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AH,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(s.allErrors?c():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let y=s.schemaEnv.baseId+s.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,TH.checkStrictMode)(s,g,s.opts.strictRequired)}}function c(){if(l||o)t.block$data(hp.nil,d);else for(let f of r)(0,mp.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,mp.checkMissingProp)(t,r,f)),(0,mp.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,mp.noPropertyInData)(e,i,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,mp.propertyInData)(e,i,f,a.ownProperties)),e.if((0,hp.not)(m),()=>{t.error(),e.break()})},hp.nil)}}};rS.default=zH});var sR=N(nS=>{"use strict";Object.defineProperty(nS,"__esModule",{value:!0});var gp=Ce(),NH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,gp.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,gp._)`{limit: ${t}}`},CH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:NH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?gp.operators.GT:gp.operators.LT;t.fail$data((0,gp._)`${r}.length ${i} ${n}`)}};nS.default=CH});var Ay=N(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});var aR=Tf();aR.code='require("ajv/dist/runtime/equal").default';iS.default=aR});var lR=N(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});var oS=ip(),wr=Ce(),OH=et(),RH=Ay(),MH={message:({params:{i:t,j:e}})=>(0,wr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,wr._)`{i: ${t}, j: ${e}}`},jH={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:MH,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let l=e.let("valid"),c=o.items?(0,oS.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,wr._)`${s} === false`),t.ok(l);function u(){let m=e.let("i",(0,wr._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(l,!0),e.if((0,wr._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return c.length>0&&!c.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),g=(0,oS.checkDataTypes)(c,y,a.opts.strictNumbers,oS.DataType.Wrong),_=e.const("indices",(0,wr._)`{}`);e.for((0,wr._)`;${m}--;`,()=>{e.let(y,(0,wr._)`${r}[${m}]`),e.if(g,(0,wr._)`continue`),c.length>1&&e.if((0,wr._)`typeof ${y} == "string"`,(0,wr._)`${y} += "_"`),e.if((0,wr._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,wr._)`${_}[${y}]`),t.error(),e.assign(l,!1).break()}).code((0,wr._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,OH.useFunc)(e,RH.default),g=e.name("outer");e.label(g).for((0,wr._)`;${m}--;`,()=>e.for((0,wr._)`${h} = ${m}; ${h}--;`,()=>e.if((0,wr._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(l,!1).break(g)})))}}};sS.default=jH});var cR=N(lS=>{"use strict";Object.defineProperty(lS,"__esModule",{value:!0});var aS=Ce(),DH=et(),LH=Ay(),UH={message:"must be equal to constant",params:({schemaCode:t})=>(0,aS._)`{allowedValue: ${t}}`},ZH={keyword:"const",$data:!0,error:UH,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,aS._)`!${(0,DH.useFunc)(e,LH.default)}(${r}, ${i})`):t.fail((0,aS._)`${o} !== ${r}`)}};lS.default=ZH});var uR=N(cS=>{"use strict";Object.defineProperty(cS,"__esModule",{value:!0});var yp=Ce(),FH=et(),VH=Ay(),qH={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,yp._)`{allowedValues: ${t}}`},WH={keyword:"enum",schemaType:"array",$data:!0,error:qH,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,l,c=()=>l??(l=(0,FH.useFunc)(e,VH.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",o);u=(0,yp.or)(...i.map((m,h)=>p(f,h)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,f=>e.if((0,yp._)`${c()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function p(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,yp._)`${c()}(${r}, ${f}[${m}])`:(0,yp._)`${r} === ${h}`}}};cS.default=WH});var dR=N(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});var BH=YO(),GH=QO(),HH=rR(),XH=nR(),KH=iR(),JH=oR(),YH=sR(),QH=lR(),eX=cR(),tX=uR(),rX=[BH.default,GH.default,HH.default,XH.default,KH.default,JH.default,YH.default,QH.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eX.default,tX.default];uS.default=rX});var fS=N(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.validateAdditionalItems=void 0;var Ba=Ce(),dS=et(),nX={message:({params:{len:t}})=>(0,Ba.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ba._)`{limit: ${t}}`},iX={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:nX,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,dS.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}fR(t,n)}};function fR(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,Ba._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ba._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,dS.alwaysValidSchema)(s,n)){let c=r.var("valid",(0,Ba._)`${a} <= ${e.length}`);r.if((0,Ba.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:dS.Type.Num},c),s.allErrors||r.if((0,Ba.not)(c),()=>r.break())})}}vp.validateAdditionalItems=fR;vp.default=iX});var pS=N(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.validateTuple=void 0;var pR=Ce(),zy=et(),oX=Fn(),sX={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return mR(t,"additionalItems",e);r.items=!0,!(0,zy.alwaysValidSchema)(r,e)&&t.ok((0,oX.validateArray)(t))}};function mR(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=zy.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),c=n.const("len",(0,pR._)`${o}.length`);r.forEach((d,p)=>{(0,zy.alwaysValidSchema)(a,d)||(n.if((0,pR._)`${c} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},l)),t.ok(l))});function u(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,zy.checkStrictMode)(a,y,p.strictTuples)}}}_p.validateTuple=mR;_p.default=sX});var hR=N(mS=>{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});var aX=pS(),lX={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aX.validateTuple)(t,"items")};mS.default=lX});var yR=N(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});var gR=Ce(),cX=et(),uX=Fn(),dX=fS(),fX={message:({params:{len:t}})=>(0,gR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,gR._)`{limit: ${t}}`},pX={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:fX,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,cX.alwaysValidSchema)(n,e)&&(i?(0,dX.validateAdditionalItems)(t,i):t.ok((0,uX.validateArray)(t)))}};hS.default=pX});var vR=N(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});var qn=Ce(),Ny=et(),mX={message:({params:{min:t,max:e}})=>e===void 0?(0,qn.str)`must contain at least ${t} valid item(s)`:(0,qn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,qn._)`{minContains: ${t}}`:(0,qn._)`{minContains: ${t}, maxContains: ${e}}`},hX={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:mX,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:l,maxContains:c}=n;o.opts.next?(s=l===void 0?1:l,a=c):s=1;let u=e.const("len",(0,qn._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Ny.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Ny.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ny.alwaysValidSchema)(o,r)){let h=(0,qn._)`${u} >= ${s}`;a!==void 0&&(h=(0,qn._)`${h} && ${u} <= ${a}`),t.pass(h);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?f(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,qn._)`${i}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,u,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:Ny.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,qn._)`${h}++`),a===void 0?e.if((0,qn._)`${h} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,qn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,qn._)`${h} >= ${s}`,()=>e.assign(d,!0)))}}};gS.default=hX});var wR=N(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.validateSchemaDeps=Zi.validatePropertyDeps=Zi.error=void 0;var yS=Ce(),gX=et(),bp=Fn();Zi.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,yS.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,yS._)`{property: ${t},
13
+ missingProperty: ${n},
14
+ depsCount: ${e},
15
+ deps: ${r}}`};var yX={keyword:"dependencies",type:"object",schemaType:"object",error:Zi.error,code(t){let[e,r]=vX(t);_R(t,e),bR(t,r)}};function vX({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function _R(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let l=(0,bp.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(l,()=>{for(let c of a)(0,bp.checkReportMissingProp)(t,c)}):(r.if((0,yS._)`${l} && (${(0,bp.checkMissingProp)(t,a,o)})`),(0,bp.reportMissingProp)(t,o),r.else())}}Zi.validatePropertyDeps=_R;function bR(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,gX.alwaysValidSchema)(o,e[a])||(r.if((0,bp.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(l,s)},()=>r.var(s,!0)),t.ok(s))}Zi.validateSchemaDeps=bR;Zi.default=yX});var $R=N(vS=>{"use strict";Object.defineProperty(vS,"__esModule",{value:!0});var xR=Ce(),_X=et(),bX={message:"property name must be valid",params:({params:t})=>(0,xR._)`{propertyName: ${t.propertyName}}`},wX={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:bX,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,_X.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,xR.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};vS.default=wX});var bS=N(_S=>{"use strict";Object.defineProperty(_S,"__esModule",{value:!0});var Cy=Fn(),pi=Ce(),xX=To(),Oy=et(),$X={message:"must NOT have additional properties",params:({params:t})=>(0,pi._)`{additionalProperty: ${t.additionalProperty}}`},kX={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$X,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,Oy.alwaysValidSchema)(s,r))return;let c=(0,Cy.allSchemaProperties)(n.properties),u=(0,Cy.allSchemaProperties)(n.patternProperties);d(),t.ok((0,pi._)`${o} === ${xX.default.errors}`);function d(){e.forIn("key",i,y=>{!c.length&&!u.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(c.length>8){let _=(0,Oy.schemaRefOrVal)(s,n.properties,"properties");g=(0,Cy.isOwnProperty)(e,_,y)}else c.length?g=(0,pi.or)(...c.map(_=>(0,pi._)`${y} === ${_}`)):g=pi.nil;return u.length&&(g=(0,pi.or)(g,...u.map(_=>(0,pi._)`${(0,Cy.usePattern)(t,_)}.test(${y})`))),(0,pi.not)(g)}function f(y){e.code((0,pi._)`delete ${i}[${y}]`)}function m(y){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Oy.alwaysValidSchema)(s,r)){let g=e.name("valid");l.removeAdditional==="failing"?(h(y,g,!1),e.if((0,pi.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,pi.not)(g),()=>e.break()))}}function h(y,g,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:Oy.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,g)}}};_S.default=kX});var IR=N(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});var SX=lp(),kR=Fn(),wS=et(),SR=bS(),IX={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&SR.default.code(new SX.KeywordCxt(o,SR.default,"additionalProperties"));let s=(0,kR.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=wS.mergeEvaluated.props(e,(0,wS.toHash)(s),o.props));let a=s.filter(d=>!(0,wS.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let l=e.name("valid");for(let d of a)c(d)?u(d):(e.if((0,kR.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};xS.default=IX});var AR=N($S=>{"use strict";Object.defineProperty($S,"__esModule",{value:!0});var ER=Fn(),Ry=Ce(),PR=et(),TR=et(),EX={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,ER.allSchemaProperties)(r),l=a.filter(h=>(0,PR.alwaysValidSchema)(o,r[h]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let c=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Ry.Name)&&(o.props=(0,TR.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)c&&f(h),o.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function f(h){for(let y in c)new RegExp(h).test(y)&&(0,PR.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Ry._)`${(0,ER.usePattern)(t,h)}.test(${y})`,()=>{let g=l.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:TR.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,Ry._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,Ry.not)(u),()=>e.break())})})}}};$S.default=EX});var zR=N(kS=>{"use strict";Object.defineProperty(kS,"__esModule",{value:!0});var PX=et(),TX={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,PX.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};kS.default=TX});var NR=N(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});var AX=Fn(),zX={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:AX.validateUnion,error:{message:"must match a schema in anyOf"}};SS.default=zX});var CR=N(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});var My=Ce(),NX=et(),CX={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,My._)`{passingSchemas: ${t.passing}}`},OX={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:CX,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(c),t.result(s,()=>t.reset(),()=>t.error(!0));function c(){o.forEach((u,d)=>{let p;(0,NX.alwaysValidSchema)(i,u)?e.var(l,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&e.if((0,My._)`${l} && ${s}`).assign(s,!1).assign(a,(0,My._)`[${a}, ${d}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,My.Name)})})}}};IS.default=OX});var OR=N(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});var RX=et(),MX={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,RX.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};ES.default=MX});var jR=N(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});var jy=Ce(),MR=et(),jX={message:({params:t})=>(0,jy.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jy._)`{failingKeyword: ${t.ifClause}}`},DX={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:jX,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,MR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=RR(n,"then"),o=RR(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,c("then",u),c("else",u))}else i?e.if(a,c("then")):e.if((0,jy.not)(a),c("else"));t.pass(s,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function c(u,d){return()=>{let p=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,jy._)`${u}`):t.setParams({ifClause:u})}}}};function RR(t,e){let r=t.schema[e];return r!==void 0&&!(0,MR.alwaysValidSchema)(t,r)}PS.default=DX});var DR=N(TS=>{"use strict";Object.defineProperty(TS,"__esModule",{value:!0});var LX=et(),UX={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,LX.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};TS.default=UX});var LR=N(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});var ZX=fS(),FX=hR(),VX=pS(),qX=yR(),WX=vR(),BX=wR(),GX=$R(),HX=bS(),XX=IR(),KX=AR(),JX=zR(),YX=NR(),QX=CR(),eK=OR(),tK=jR(),rK=DR();function nK(t=!1){let e=[JX.default,YX.default,QX.default,eK.default,tK.default,rK.default,GX.default,HX.default,BX.default,XX.default,KX.default];return t?e.push(FX.default,qX.default):e.push(ZX.default,VX.default),e.push(WX.default),e}AS.default=nK});var UR=N(zS=>{"use strict";Object.defineProperty(zS,"__esModule",{value:!0});var Lt=Ce(),iK={message:({schemaCode:t})=>(0,Lt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Lt._)`{format: ${t}}`},oK={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iK,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=a;if(!l.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=r.const("fDef",(0,Lt._)`${m}[${s}]`),y=r.let("fType"),g=r.let("format");r.if((0,Lt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Lt._)`${h}.type || "string"`).assign(g,(0,Lt._)`${h}.validate`),()=>r.assign(y,(0,Lt._)`"string"`).assign(g,h)),t.fail$data((0,Lt.or)(_(),b()));function _(){return l.strictSchema===!1?Lt.nil:(0,Lt._)`${s} && !${g}`}function b(){let E=u.$async?(0,Lt._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Lt._)`${g}(${n})`,I=(0,Lt._)`(typeof ${g} == "function" ? ${E} : ${g}.test(${n}))`;return(0,Lt._)`${g} && ${g} !== true && ${y} === ${e} && !${I}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,g]=b(m);h===e&&t.pass(E());function _(){if(l.strictSchema===!1){d.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${o}" ignored in schema at path "${c}"`}}function b(I){let P=I instanceof RegExp?(0,Lt.regexpCode)(I):l.code.formats?(0,Lt._)`${l.code.formats}${(0,Lt.getProperty)(o)}`:void 0,M=r.scopeValue("formats",{key:o,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,Lt._)`${M}.validate`]:["string",I,M]}function E(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Lt._)`await ${g}(${n})`}return typeof y=="function"?(0,Lt._)`${g}(${n})`:(0,Lt._)`${g}.test(${n})`}}}};zS.default=oK});var ZR=N(NS=>{"use strict";Object.defineProperty(NS,"__esModule",{value:!0});var sK=UR(),aK=[sK.default];NS.default=aK});var FR=N(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.contentVocabulary=bu.metadataVocabulary=void 0;bu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];bu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var qR=N(CS=>{"use strict";Object.defineProperty(CS,"__esModule",{value:!0});var lK=JO(),cK=dR(),uK=LR(),dK=ZR(),VR=FR(),fK=[lK.default,cK.default,(0,uK.default)(),dK.default,VR.metadataVocabulary,VR.contentVocabulary];CS.default=fK});var WR=N(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.DiscrError=void 0;var pK;(function(t){t.Tag="tag",t.Mapping="mapping"})(pK=wp.DiscrError||(wp.DiscrError={}))});var GR=N(RS=>{"use strict";Object.defineProperty(RS,"__esModule",{value:!0});var wu=Ce(),OS=WR(),BR=xy(),mK=et(),hK={message:({params:{discrError:t,tagName:e}})=>t===OS.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,wu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},gK={keyword:"discriminator",type:"object",schemaType:"object",error:hK,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),c=e.const("tag",(0,wu._)`${r}${(0,wu.getProperty)(a)}`);e.if((0,wu._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:OS.DiscrError.Tag,tag:c,tagName:a})),t.ok(l);function u(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,wu._)`${c} === ${m}`),e.assign(l,d(f[m]));e.else(),t.error(!1,{discrError:OS.DiscrError.Mapping,tag:c,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,wu.Name),m}function p(){var f;let m={},h=g(i),y=!0;for(let E=0;E<s.length;E++){let I=s[E];I?.$ref&&!(0,mK.schemaHasRulesButRef)(I,o.self.RULES)&&(I=BR.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,I?.$ref),I instanceof BR.SchemaEnv&&(I=I.schema));let P=(f=I?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(I)),_(P,E)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:E}){return Array.isArray(E)&&E.includes(a)}function _(E,I){if(E.const)b(E.const,I);else if(E.enum)for(let P of E.enum)b(P,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,I){if(typeof E!="string"||E in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[E]=I}}}};RS.default=gK});var HR=N((_we,yK)=>{yK.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 JR=N((Nt,KR)=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.MissingRefError=Nt.ValidationError=Nt.CodeGen=Nt.Name=Nt.nil=Nt.stringify=Nt.str=Nt._=Nt.KeywordCxt=void 0;var vK=WO(),_K=qR(),bK=GR(),XR=HR(),wK=["/properties"],Dy="http://json-schema.org/draft-07/schema",Ly=class extends vK.default{_addVocabularies(){super._addVocabularies(),_K.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(bK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(XR,wK):XR;this.addMetaSchema(e,Dy,!1),this.refs["http://json-schema.org/schema"]=Dy}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Dy)?Dy:void 0)}};KR.exports=Nt=Ly;Object.defineProperty(Nt,"__esModule",{value:!0});Nt.default=Ly;var xK=lp();Object.defineProperty(Nt,"KeywordCxt",{enumerable:!0,get:function(){return xK.KeywordCxt}});var xu=Ce();Object.defineProperty(Nt,"_",{enumerable:!0,get:function(){return xu._}});Object.defineProperty(Nt,"str",{enumerable:!0,get:function(){return xu.str}});Object.defineProperty(Nt,"stringify",{enumerable:!0,get:function(){return xu.stringify}});Object.defineProperty(Nt,"nil",{enumerable:!0,get:function(){return xu.nil}});Object.defineProperty(Nt,"Name",{enumerable:!0,get:function(){return xu.Name}});Object.defineProperty(Nt,"CodeGen",{enumerable:!0,get:function(){return xu.CodeGen}});var $K=_y();Object.defineProperty(Nt,"ValidationError",{enumerable:!0,get:function(){return $K.default}});var kK=by();Object.defineProperty(Nt,"MissingRefError",{enumerable:!0,get:function(){return kK.default}})});var YR=N($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.formatLimitDefinition=void 0;var SK=JR(),mi=Ce(),Ts=mi.operators,Uy={formatMaximum:{okStr:"<=",ok:Ts.LTE,fail:Ts.GT},formatMinimum:{okStr:">=",ok:Ts.GTE,fail:Ts.LT},formatExclusiveMaximum:{okStr:"<",ok:Ts.LT,fail:Ts.GTE},formatExclusiveMinimum:{okStr:">",ok:Ts.GT,fail:Ts.LTE}},IK={message:({keyword:t,schemaCode:e})=>(0,mi.str)`should be ${Uy[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mi._)`{comparison: ${Uy[t].okStr}, limit: ${e}}`};$u.formatLimitDefinition={keyword:Object.keys(Uy),type:"string",schemaType:"string",$data:!0,error:IK,code(t){let{gen:e,data:r,schemaCode:n,keyword:i,it:o}=t,{opts:s,self:a}=o;if(!s.validateFormats)return;let l=new SK.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?c():u();function c(){let p=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=e.const("fmt",(0,mi._)`${p}[${l.schemaCode}]`);t.fail$data((0,mi.or)((0,mi._)`typeof ${f} != "object"`,(0,mi._)`${f} instanceof RegExp`,(0,mi._)`typeof ${f}.compare != "function"`,d(f)))}function u(){let p=l.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${i}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,mi._)`${s.code.formats}${(0,mi.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,mi._)`${p}.compare(${r}, ${n}) ${Uy[i].fail} 0`}},dependencies:["format"]};var EK=t=>(t.addKeyword($u.formatLimitDefinition),t);$u.default=EK});var rM=N((xp,tM)=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var ku=MC(),PK=YR(),MS=Ce(),QR=new MS.Name("fullFormats"),TK=new MS.Name("fastFormats"),jS=(t,e={keywords:!0})=>{if(Array.isArray(e))return eM(t,e,ku.fullFormats,QR),t;let[r,n]=e.mode==="fast"?[ku.fastFormats,TK]:[ku.fullFormats,QR],i=e.formats||ku.formatNames;return eM(t,i,r,n),e.keywords&&(0,PK.default)(t),t};jS.get=(t,e="full")=>{let n=(e==="fast"?ku.fastFormats:ku.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function eM(t,e,r,n){var i,o;(i=(o=t.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,MS._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)t.addFormat(s,r[s])}tM.exports=xp=jS;Object.defineProperty(xp,"__esModule",{value:!0});xp.default=jS});var AD=N((zTe,TD)=>{"use strict";var Rv=Object.prototype.hasOwnProperty,PD=Object.prototype.toString,xD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,kD=function(e){return typeof Array.isArray=="function"?Array.isArray(e):PD.call(e)==="[object Array]"},SD=function(e){if(!e||PD.call(e)!=="[object Object]")return!1;var r=Rv.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Rv.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var i;for(i in e);return typeof i>"u"||Rv.call(e,i)},ID=function(e,r){xD&&r.name==="__proto__"?xD(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},ED=function(e,r){if(r==="__proto__")if(Rv.call(e,r)){if($D)return $D(e,r).value}else return;return e[r]};TD.exports=function t(){var e,r,n,i,o,s,a=arguments[0],l=1,c=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},l=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});l<c;++l)if(e=arguments[l],e!=null)for(r in e)n=ED(a,r),i=ED(e,r),a!==i&&(u&&i&&(SD(i)||(o=kD(i)))?(o?(o=!1,s=n&&kD(n)?n:[]):s=n&&SD(n)?n:{},ID(a,{name:r,newValue:t(u,s,i)})):typeof i<"u"&&ID(a,{name:r,newValue:i}));return a}});function ue(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function T(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var r_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return r_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function ed(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var td=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var ee=class extends Error{},Jt=class t extends ee{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Lo({message:n,cause:td(r)});let o=r?.error;return e===400?new hl(e,o,n,i):e===401?new gl(e,o,n,i):e===403?new yl(e,o,n,i):e===404?new vl(e,o,n,i):e===409?new _l(e,o,n,i):e===422?new bl(e,o,n,i):e===429?new wl(e,o,n,i):e>=500?new xl(e,o,n,i):new t(e,o,n,i)}},Gt=class extends Jt{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Lo=class extends Jt{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Uo=class extends Lo{constructor({message:e}={}){super({message:e??"Request timed out."})}},hl=class extends Jt{},gl=class extends Jt{},yl=class extends Jt{},vl=class extends Jt{},_l=class extends Jt{},bl=class extends Jt{},wl=class extends Jt{},xl=class extends Jt{},$l=class extends ee{constructor(){super("Could not parse response content as the length limit was reached")}},kl=class extends ee{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},_i=class extends Error{constructor(e){super(e)}};var o4=/^[a-z][a-z0-9+.-]*:/i,yE=t=>o4.test(t),kr=t=>(kr=Array.isArray,kr(t)),n_=kr;function i_(t){return typeof t!="object"?{}:t??{}}function vE(t){if(!t)return!0;for(let e in t)return!1;return!0}function _E(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function rd(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var bE=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ee(`${t} must be an integer`);if(e<0)throw new ee(`${t} must be a positive integer`);return e};var wE=t=>{try{return JSON.parse(t)}catch{return}};var bi=t=>new Promise(e=>setTimeout(e,t));var Zo="6.10.0";var SE=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function s4(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var a4=()=>{let t=s4();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":$E(Deno.build.os),"X-Stainless-Arch":xE(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":$E(globalThis.process.platform??"unknown"),"X-Stainless-Arch":xE(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=l4();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function l4(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var xE=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$E=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),kE,IE=()=>kE??(kE=a4());function EE(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function o_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Sm(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return o_({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function s_(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function PE(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var TE=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Im="RFC3986",a_=t=>String(t),Em={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:a_},l_="RFC1738";var Pm=(t,e)=>(Pm=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Pm(t,e)),wi=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var c_=1024,AE=(t,e,r,n,i)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<o.length;a+=c_){let l=o.length>=c_?o.slice(a,a+c_):o,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===l_&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=wi[d];continue}if(d<2048){c[c.length]=wi[192|d>>6]+wi[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=wi[224|d>>12]+wi[128|d>>6&63]+wi[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=wi[240|d>>18]+wi[128|d>>12&63]+wi[128|d>>6&63]+wi[128|d&63]}s+=c.join("")}return s};function zE(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function u_(t,e){if(kr(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var CE={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},OE=function(t,e){Array.prototype.push.apply(t,kr(e)?e:[e])},NE,Yt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:AE,encodeValuesOnly:!1,format:Im,formatter:a_,indices:!1,serializeDate(t){return(NE??(NE=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function d4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var d_={};function RE(t,e,r,n,i,o,s,a,l,c,u,d,p,f,m,h,y,g){let _=t,b=g,E=0,I=!1;for(;(b=b.get(d_))!==void 0&&!I;){let L=b.get(t);if(E+=1,typeof L<"u"){if(L===E)throw new RangeError("Cyclic object value");I=!0}typeof b.get(d_)>"u"&&(E=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=p?.(_):r==="comma"&&kr(_)&&(_=u_(_,function(L){return L instanceof Date?p?.(L):L})),_===null){if(o)return l&&!h?l(e,Yt.encoder,y,"key",f):e;_=""}if(d4(_)||zE(_)){if(l){let L=h?e:l(e,Yt.encoder,y,"key",f);return[m?.(L)+"="+m?.(l(_,Yt.encoder,y,"value",f))]}return[m?.(e)+"="+m?.(String(_))]}let P=[];if(typeof _>"u")return P;let M;if(r==="comma"&&kr(_))h&&l&&(_=u_(_,l)),M=[{value:_.length>0?_.join(",")||null:void 0}];else if(kr(c))M=c;else{let L=Object.keys(_);M=u?L.sort(u):L}let V=a?String(e).replace(/\./g,"%2E"):String(e),R=n&&kr(_)&&_.length===1?V+"[]":V;if(i&&kr(_)&&_.length===0)return R+"[]";for(let L=0;L<M.length;++L){let G=M[L],H=typeof G=="object"&&typeof G.value<"u"?G.value:_[G];if(s&&H===null)continue;let W=d&&a?G.replace(/\./g,"%2E"):G,Y=kr(_)?typeof r=="function"?r(R,W):R:R+(d?"."+W:"["+W+"]");g.set(t,E);let ie=new WeakMap;ie.set(d_,g),OE(P,RE(H,Y,r,n,i,o,s,a,r==="comma"&&h&&kr(_)?null:l,c,u,d,p,f,m,h,y,ie))}return P}function f4(t=Yt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Yt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Im;if(typeof t.format<"u"){if(!Pm(Em,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Em[r],i=Yt.filter;(typeof t.filter=="function"||kr(t.filter))&&(i=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in CE?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=Yt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Yt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Yt.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Yt.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Yt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Yt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Yt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Yt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Yt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Yt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Yt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Yt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Yt.strictNullHandling}}function f_(t,e={}){let r=t,n=f4(e),i,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):kr(n.filter)&&(o=n.filter,i=o);let s=[];if(typeof r!="object"||r===null)return"";let a=CE[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let c=new WeakMap;for(let p=0;p<i.length;++p){let f=i[p];n.skipNulls&&r[f]===null||OE(s,RE(r[f],f,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}let u=s.join(n.delimiter),d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function DE(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var ME;function Sl(t){let e;return(ME??(e=new globalThis.TextEncoder,ME=e.encode.bind(e)))(t)}var jE;function p_(t){let e;return(jE??(e=new globalThis.TextDecoder,jE=e.decode.bind(e)))(t)}var mn,hn,Fs=class{constructor(){mn.set(this,void 0),hn.set(this,void 0),ue(this,mn,new Uint8Array,"f"),ue(this,hn,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Sl(e):e;ue(this,mn,DE([T(this,mn,"f"),r]),"f");let n=[],i;for(;(i=m4(T(this,mn,"f"),T(this,hn,"f")))!=null;){if(i.carriage&&T(this,hn,"f")==null){ue(this,hn,i.index,"f");continue}if(T(this,hn,"f")!=null&&(i.index!==T(this,hn,"f")+1||i.carriage)){n.push(p_(T(this,mn,"f").subarray(0,T(this,hn,"f")-1))),ue(this,mn,T(this,mn,"f").subarray(T(this,hn,"f")),"f"),ue(this,hn,null,"f");continue}let o=T(this,hn,"f")!==null?i.preceding-1:i.preceding,s=p_(T(this,mn,"f").subarray(0,o));n.push(s),ue(this,mn,T(this,mn,"f").subarray(i.index),"f"),ue(this,hn,null,"f")}return n}flush(){return T(this,mn,"f").length?this.decode(`
16
+ `):[]}};mn=new WeakMap,hn=new WeakMap;Fs.NEWLINE_CHARS=new Set([`
17
+ `,"\r"]);Fs.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function m4(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function LE(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Am={off:0,error:200,warn:300,info:400,debug:500},m_=(t,e,r)=>{if(t){if(_E(Am,t))return t;Mt(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Am))}`)}};function nd(){}function Tm(t,e,r){return!e||Am[t]>Am[r]?nd:e[t].bind(e)}var h4={error:nd,warn:nd,info:nd,debug:nd},UE=new WeakMap;function Mt(t){let e=t.logger,r=t.logLevel??"off";if(!e)return h4;let n=UE.get(e);if(n&&n[0]===r)return n[1];let i={error:Tm("error",e,r),warn:Tm("warn",e,r),info:Tm("info",e,r),debug:Tm("debug",e,r)};return UE.set(e,[r,i]),i}var Qi=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var id,xi=class t{constructor(e,r,n){this.iterator=e,id.set(this,void 0),this.controller=r,ue(this,id,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?Mt(n):console;async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of g4(e,r))if(!a){if(l.data.startsWith("[DONE]")){a=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(u){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),u}if(c&&c.error)throw new Jt(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(l.event=="error")throw new Jt(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}a=!0}catch(l){if(ed(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new Fs,l=s_(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of o())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(ed(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}[(id=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,T(this,id,"f")),new t(()=>i(r),this.controller,T(this,id,"f"))]}toReadableStream(){let e=this,r;return o_({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=Sl(JSON.stringify(i)+`
18
+ `);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*g4(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ee("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ee("Attempted to iterate over a response with no body");let r=new h_,n=new Fs,i=s_(t.body);for await(let o of y4(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*y4(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Sl(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=LE(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var h_=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
19
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=v4(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function v4(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function zm(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return Mt(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):xi.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){let d=await r.json();return g_(d,r)}return await r.text()})();return Mt(t).debug(`[${n}] response parsed`,Qi({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function g_(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var od,Vs=class t extends Promise{constructor(e,r,n=zm){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,od.set(this,void 0),ue(this,od,e,"f")}_thenUnwrap(e){return new t(T(this,od,"f"),this.responsePromise,async(r,n)=>g_(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(T(this,od,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};od=new WeakMap;var Nm,sd=class{constructor(e,r,n,i){Nm.set(this,void 0),ue(this,Nm,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await T(this,Nm,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Nm=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},ad=class extends Vs{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await zm(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},$i=class extends sd{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Ae=class extends sd{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...i_(this.options.query),after:r}}:null}},eo=class extends sd{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...i_(this.options.query),after:e}}:null}};var __=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Il(t,e,r){return __(),new File(t,e??"unknown_file",r)}function ld(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Cm=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",b_=async(t,e)=>y_(t.body)?{...t,body:await FE(t.body,e)}:t,gn=async(t,e)=>({...t,body:await FE(t.body,e)}),ZE=new WeakMap;function b4(t){let e=typeof t=="function"?t:t.fetch,r=ZE.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return ZE.set(e,n),n}var FE=async(t,e)=>{if(!await b4(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,i])=>v_(r,n,i))),r},VE=t=>t instanceof Blob&&"name"in t,w4=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Cm(t)||VE(t)),y_=t=>{if(w4(t))return!0;if(Array.isArray(t))return t.some(y_);if(t&&typeof t=="object"){for(let e in t)if(y_(t[e]))return!0}return!1},v_=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Il([await r.blob()],ld(r)));else if(Cm(r))t.append(e,Il([await new Response(Sm(r)).blob()],ld(r)));else if(VE(r))t.append(e,r,ld(r));else if(Array.isArray(r))await Promise.all(r.map(n=>v_(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>v_(t,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var qE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",x4=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&qE(t),$4=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Om(t,e,r){if(__(),t=await t,x4(t))return t instanceof File?t:Il([await t.arrayBuffer()],t.name);if($4(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Il(await w_(i),e,r)}let n=await w_(t);if(e||(e=ld(t)),!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return Il(n,e,r)}async function w_(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(qE(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Cm(t))for await(let r of t)e.push(...await w_(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${k4(t)}`)}return e}function k4(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var D=class{constructor(e){this._client=e}};function BE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var WE=Object.freeze(Object.create(null)),I4=(t=BE)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,p)=>{/[?#]/.test(d)&&(i=!0);let f=n[p],m=(i?encodeURIComponent:t)(""+f);return p!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??WE)??WE)?.toString)&&(m=f+"",o.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(p===n.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((p,f)=>{let m=" ".repeat(f.start-u),h="^".repeat(f.length);return u=f.start+f.length,p+m+h},"");throw new ee(`Path parameters result in path with invalid segments:
20
+ ${o.map(p=>p.error).join(`
21
+ `)}
22
+ ${s}
23
+ ${d}`)}return s},O=I4(BE);var qs=class extends D{list(e,r={},n){return this._client.getAPIList(O`/chat/completions/${e}/messages`,Ae,{query:r,...n})}};function cd(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ud(t){return t?.$brand==="auto-parseable-response-format"}function Ws(t){return t?.$brand==="auto-parseable-tool"}function GE(t,e){return!e||!x_(e)?{...t,choices:t.choices.map(r=>(XE(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:dd(t,e)}function dd(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new $l;if(n.finish_reason==="content_filter")throw new kl;return XE(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>A4(e,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?T4(e,n.message.content):null}}});return{...t,choices:r}}function T4(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function A4(t,e){let r=t.tools?.find(n=>cd(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ws(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function HE(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>cd(n)&&n.function?.name===e.function.name);return cd(r)&&(Ws(r)||r?.function.strict||!1)}function x_(t){return ud(t.response_format)?!0:t.tools?.some(e=>Ws(e)||e.type==="function"&&e.function.strict===!0)??!1}function XE(t){for(let e of t||[])if(e.type!=="function")throw new ee(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function KE(t){for(let e of t??[]){if(e.type!=="function")throw new ee(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new ee(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var El=t=>t?.role==="assistant",$_=t=>t?.role==="tool";var k_,Rm,Mm,fd,pd,jm,md,to,hd,Dm,Lm,Pl,JE,Fo=class{constructor(){k_.add(this),this.controller=new AbortController,Rm.set(this,void 0),Mm.set(this,()=>{}),fd.set(this,()=>{}),pd.set(this,void 0),jm.set(this,()=>{}),md.set(this,()=>{}),to.set(this,{}),hd.set(this,!1),Dm.set(this,!1),Lm.set(this,!1),Pl.set(this,!1),ue(this,Rm,new Promise((e,r)=>{ue(this,Mm,e,"f"),ue(this,fd,r,"f")}),"f"),ue(this,pd,new Promise((e,r)=>{ue(this,jm,e,"f"),ue(this,md,r,"f")}),"f"),T(this,Rm,"f").catch(()=>{}),T(this,pd,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},T(this,k_,"m",JE).bind(this))},0)}_connected(){this.ended||(T(this,Mm,"f").call(this),this._emit("connect"))}get ended(){return T(this,hd,"f")}get errored(){return T(this,Dm,"f")}get aborted(){return T(this,Lm,"f")}abort(){this.controller.abort()}on(e,r){return(T(this,to,"f")[e]||(T(this,to,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=T(this,to,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(T(this,to,"f")[e]||(T(this,to,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{ue(this,Pl,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){ue(this,Pl,!0,"f"),await T(this,pd,"f")}_emit(e,...r){if(T(this,hd,"f"))return;e==="end"&&(ue(this,hd,!0,"f"),T(this,jm,"f").call(this));let n=T(this,to,"f")[e];if(n&&(T(this,to,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!T(this,Pl,"f")&&!n?.length&&Promise.reject(i),T(this,fd,"f").call(this,i),T(this,md,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!T(this,Pl,"f")&&!n?.length&&Promise.reject(i),T(this,fd,"f").call(this,i),T(this,md,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Rm=new WeakMap,Mm=new WeakMap,fd=new WeakMap,pd=new WeakMap,jm=new WeakMap,md=new WeakMap,to=new WeakMap,hd=new WeakMap,Dm=new WeakMap,Lm=new WeakMap,Pl=new WeakMap,k_=new WeakSet,JE=function(e){if(ue(this,Dm,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Gt),e instanceof Gt)return ue(this,Lm,!0,"f"),this._emit("abort",e);if(e instanceof ee)return this._emit("error",e);if(e instanceof Error){let r=new ee(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new ee(String(e)))};function YE(t){return typeof t.parse=="function"}var Lr,S_,Um,I_,E_,P_,QE,e1,z4=10,Tl=class extends Fo{constructor(){super(...arguments),Lr.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),$_(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(El(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),T(this,Lr,"m",S_).call(this)}async finalMessage(){return await this.done(),T(this,Lr,"m",Um).call(this)}async finalFunctionToolCall(){return await this.done(),T(this,Lr,"m",I_).call(this)}async finalFunctionToolCallResult(){return await this.done(),T(this,Lr,"m",E_).call(this)}async totalUsage(){return await this.done(),T(this,Lr,"m",P_).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=T(this,Lr,"m",Um).call(this);r&&this._emit("finalMessage",r);let n=T(this,Lr,"m",S_).call(this);n&&this._emit("finalContent",n);let i=T(this,Lr,"m",I_).call(this);i&&this._emit("finalFunctionToolCall",i);let o=T(this,Lr,"m",E_).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",T(this,Lr,"m",P_).call(this))}async _createChatCompletion(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Lr,"m",QE).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(dd(o,r))}async _runChatCompletion(e,r,n){for(let i of r.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let i="tool",{tool_choice:o="auto",stream:s,...a}=r,l=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:c=z4}=n||{},u=r.tools.map(f=>{if(Ws(f)){if(!f.$callback)throw new ee("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(let f of u)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);let p="tools"in r?u.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of r.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){let h=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:p,messages:[...this.messages]},n)).choices[0]?.message;if(!h)throw new ee("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let y of h.tool_calls){if(y.type!=="function")continue;let g=y.id,{name:_,arguments:b}=y.function,E=d[_];if(E){if(l&&l!==_){let V=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:g,content:V});continue}}else{let V=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(d).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:g,content:V});continue}let I;try{I=YE(E)?await E.parse(b):b}catch(V){let R=V instanceof Error?V.message:String(V);this._addMessage({role:i,tool_call_id:g,content:R});continue}let P=await E.function(I,this),M=T(this,Lr,"m",e1).call(this,P);if(this._addMessage({role:i,tool_call_id:g,content:M}),l)return}}}};Lr=new WeakSet,S_=function(){return T(this,Lr,"m",Um).call(this).content??null},Um=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(El(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new ee("stream ended without producing a ChatCompletionMessage with role=assistant")},I_=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(El(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},E_=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if($_(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===r.tool_call_id)))return r.content}},P_=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},QE=function(e){if(e.n!=null&&e.n>1)throw new ee("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},e1=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var gd=class t extends Tl{static runTools(e,r,n){let i=new t,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}_addMessage(e,r=!0){super._addMessage(e,r),El(e)&&e.content&&this._emit("content",e.content)}};var rr={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},T_=class extends Error{},A_=class extends Error{};function N4(t,e=rr.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return C4(t.trim(),e)}var C4=(t,e)=>{let r=t.length,n=0,i=p=>{throw new T_(`${p} at position ${n}`)},o=p=>{throw new A_(`${p} at position ${n}`)},s=()=>(d(),n>=r&&i("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?l():t[n]==="["?c():t.substring(n,n+4)==="null"||rr.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||rr.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||rr.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||rr.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||rr.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||rr.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let p=n,f=!1;for(n++;n<r&&(t[n]!=='"'||f&&t[n-1]==="\\");)f=t[n]==="\\"?!f:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(p,++n-Number(f)))}catch(m){o(String(m))}else if(rr.STR&e)try{return JSON.parse(t.substring(p,n-Number(f))+'"')}catch{return JSON.parse(t.substring(p,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},l=()=>{n++,d();let p={};try{for(;t[n]!=="}";){if(d(),n>=r&&rr.OBJ&e)return p;let f=a();d(),n++;try{let m=s();Object.defineProperty(p,f,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(rr.OBJ&e)return p;throw m}d(),t[n]===","&&n++}}catch{if(rr.OBJ&e)return p;i("Expected '}' at end of object")}return n++,p},c=()=>{n++;let p=[];try{for(;t[n]!=="]";)p.push(s()),d(),t[n]===","&&n++}catch{if(rr.ARR&e)return p;i("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){t==="-"&&rr.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(rr.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(f))}}let p=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(rr.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(t.substring(p,n))}catch{t.substring(p,n)==="-"&&rr.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t.substring(p,t.lastIndexOf("e")))}catch(m){o(String(m))}}},d=()=>{for(;n<r&&`
24
+ \r `.includes(t[n]);)n++};return s()},z_=t=>N4(t,rr.ALL^rr.NUM);var Qt,ro,Al,Vo,N_,Zm,C_,O_,R_,Fm,M_,t1,Bs=class t extends Tl{constructor(e){super(),Qt.add(this),ro.set(this,void 0),Al.set(this,void 0),Vo.set(this,void 0),ue(this,ro,e,"f"),ue(this,Al,[],"f")}get currentChatCompletionSnapshot(){return T(this,Vo,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let i=new t(r);return i._run(()=>i._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,r,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Qt,"m",N_).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)T(this,Qt,"m",C_).call(this,s);if(o.controller.signal?.aborted)throw new Gt;return this._addChatCompletion(T(this,Qt,"m",Fm).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),T(this,Qt,"m",N_).call(this),this._connected();let i=xi.fromReadableStream(e,this.controller),o;for await(let s of i)o&&o!==s.id&&this._addChatCompletion(T(this,Qt,"m",Fm).call(this)),T(this,Qt,"m",C_).call(this,s),o=s.id;if(i.controller.signal?.aborted)throw new Gt;return this._addChatCompletion(T(this,Qt,"m",Fm).call(this))}[(ro=new WeakMap,Al=new WeakMap,Vo=new WeakMap,Qt=new WeakSet,N_=function(){this.ended||ue(this,Vo,void 0,"f")},Zm=function(r){let n=T(this,Al,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},T(this,Al,"f")[r.index]=n,n)},C_=function(r){if(this.ended)return;let n=T(this,Qt,"m",t1).call(this,r);this._emit("chunk",r,n);for(let i of r.choices){let o=n.choices[i.index];i.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",i.delta.content,o.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),i.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:o.message.refusal}),i.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:o.logprobs?.content??[]}),i.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let s=T(this,Qt,"m",Zm).call(this,o);o.finish_reason&&(T(this,Qt,"m",R_).call(this,o),s.current_tool_call_index!=null&&T(this,Qt,"m",O_).call(this,o,s.current_tool_call_index));for(let a of i.delta.tool_calls??[])s.current_tool_call_index!==a.index&&(T(this,Qt,"m",R_).call(this,o),s.current_tool_call_index!=null&&T(this,Qt,"m",O_).call(this,o,s.current_tool_call_index)),s.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let l=o.message.tool_calls?.[a.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:a.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(l?.type,void 0))}}},O_=function(r,n){if(T(this,Qt,"m",Zm).call(this,r).done_tool_calls.has(n))return;let o=r.message.tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let s=T(this,ro,"f")?.tools?.find(a=>cd(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:Ws(s)?s.$parseRaw(o.function.arguments):s?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},R_=function(r){let n=T(this,Qt,"m",Zm).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=T(this,Qt,"m",M_).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Fm=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=T(this,Vo,"f");if(!r)throw new ee("request ended without sending any chunks");return ue(this,Vo,void 0,"f"),ue(this,Al,[],"f"),O4(r,T(this,ro,"f"))},M_=function(){let r=T(this,ro,"f")?.response_format;return ud(r)?r:null},t1=function(r){var n,i,o,s;let a=T(this,Vo,"f"),{choices:l,...c}=r;a?Object.assign(a,c):a=ue(this,Vo,{...c,choices:[]},"f");for(let{delta:u,finish_reason:d,index:p,logprobs:f=null,...m}of r.choices){let h=a.choices[p];if(h||(h=a.choices[p]={finish_reason:d,index:p,message:{},logprobs:f,...m}),f)if(!h.logprobs)h.logprobs=Object.assign({},f);else{let{content:P,refusal:M,...V}=f;Object.assign(h.logprobs,V),P&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...P)),M&&((i=h.logprobs).refusal??(i.refusal=[]),h.logprobs.refusal.push(...M))}if(d&&(h.finish_reason=d,T(this,ro,"f")&&x_(T(this,ro,"f")))){if(d==="length")throw new $l;if(d==="content_filter")throw new kl}if(Object.assign(h,m),!u)continue;let{content:y,refusal:g,function_call:_,role:b,tool_calls:E,...I}=u;if(Object.assign(h.message,I),g&&(h.message.refusal=(h.message.refusal||"")+g),b&&(h.message.role=b),_&&(h.message.function_call?(_.name&&(h.message.function_call.name=_.name),_.arguments&&((o=h.message.function_call).arguments??(o.arguments=""),h.message.function_call.arguments+=_.arguments)):h.message.function_call=_),y&&(h.message.content=(h.message.content||"")+y,!h.message.refusal&&T(this,Qt,"m",M_).call(this)&&(h.message.parsed=z_(h.message.content))),E){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:P,id:M,type:V,function:R,...L}of E){let G=(s=h.message.tool_calls)[P]??(s[P]={});Object.assign(G,L),M&&(G.id=M),V&&(G.type=V),R&&(G.function??(G.function={name:R.name??"",arguments:""})),R?.name&&(G.function.name=R.name),R?.arguments&&(G.function.arguments+=R.arguments,HE(T(this,ro,"f"),G)&&(G.function.parsed_arguments=z_(G.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new xi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function O4(t,e){let{id:r,choices:n,created:i,model:o,system_fingerprint:s,...a}=t,l={...a,id:r,choices:n.map(({message:c,finish_reason:u,index:d,logprobs:p,...f})=>{if(!u)throw new ee(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=c,_=c.role;if(!_)throw new ee(`missing role for choice ${d}`);if(h){let{arguments:b,name:E}=h;if(b==null)throw new ee(`missing function_call.arguments for choice ${d}`);if(!E)throw new ee(`missing function_call.name for choice ${d}`);return{...f,message:{content:m,function_call:{arguments:b,name:E},role:_,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}return y?{...f,index:d,finish_reason:u,logprobs:p,message:{...g,role:_,content:m,refusal:c.refusal??null,tool_calls:y.map((b,E)=>{let{function:I,type:P,id:M,...V}=b,{arguments:R,name:L,...G}=I||{};if(M==null)throw new ee(`missing choices[${d}].tool_calls[${E}].id
25
+ ${Vm(t)}`);if(P==null)throw new ee(`missing choices[${d}].tool_calls[${E}].type
26
+ ${Vm(t)}`);if(L==null)throw new ee(`missing choices[${d}].tool_calls[${E}].function.name
27
+ ${Vm(t)}`);if(R==null)throw new ee(`missing choices[${d}].tool_calls[${E}].function.arguments
28
+ ${Vm(t)}`);return{...V,id:M,type:P,function:{...G,name:L,arguments:R}}})}}:{...f,message:{...g,content:m,role:_,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}),created:i,model:o,object:"chat.completion",...s?{system_fingerprint:s}:{}};return GE(l,e)}function Vm(t){return JSON.stringify(t)}var yd=class t extends Bs{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let i=new t(r),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}};var no=class extends D{constructor(){super(...arguments),this.messages=new qs(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1})}retrieve(e,r){return this._client.get(O`/chat/completions/${e}`,r)}update(e,r,n){return this._client.post(O`/chat/completions/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/chat/completions",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/chat/completions/${e}`,r)}parse(e,r){return KE(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>dd(n,e))}runTools(e,r){return e.stream?yd.runTools(this._client,e,r):gd.runTools(this._client,e,r)}stream(e,r){return Bs.createChatCompletion(this._client,e,r)}};no.Messages=qs;var qo=class extends D{constructor(){super(...arguments),this.completions=new no(this._client)}};qo.Completions=no;var r1=Symbol("brand.privateNullableHeaders");function*M4(t){if(!t)return;if(r1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():n_(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=n_(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var B=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of M4(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[r1]:!0,values:e,nulls:r}};var zl=class extends D{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:B([{Accept:"application/octet-stream"},r?.headers]),__binaryResponse:!0})}};var Nl=class extends D{create(e,r){return this._client.post("/audio/transcriptions",gn({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Cl=class extends D{create(e,r){return this._client.post("/audio/translations",gn({body:e,...r,__metadata:{model:e.model}},this._client))}};var ki=class extends D{constructor(){super(...arguments),this.transcriptions=new Nl(this._client),this.translations=new Cl(this._client),this.speech=new zl(this._client)}};ki.Transcriptions=Nl;ki.Translations=Cl;ki.Speech=zl;var Gs=class extends D{create(e,r){return this._client.post("/batches",{body:e,...r})}retrieve(e,r){return this._client.get(O`/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/batches",Ae,{query:e,...r})}cancel(e,r){return this._client.post(O`/batches/${e}/cancel`,r)}};var Ol=class extends D{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/assistants/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/assistants/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/assistants",Ae,{query:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(O`/assistants/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Rl=class extends D{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ml=class extends D{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Wo=class extends D{constructor(){super(...arguments),this.sessions=new Rl(this._client),this.transcriptionSessions=new Ml(this._client)}};Wo.Sessions=Rl;Wo.TranscriptionSessions=Ml;var jl=class extends D{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}cancel(e,r){return this._client.post(O`/chatkit/sessions/${e}/cancel`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Dl=class extends D{retrieve(e,r){return this._client.get(O`/chatkit/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}list(e={},r){return this._client.getAPIList("/chatkit/threads",eo,{query:e,...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}delete(e,r){return this._client.delete(O`/chatkit/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}listItems(e,r={},n){return this._client.getAPIList(O`/chatkit/threads/${e}/items`,eo,{query:r,...n,headers:B([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var Bo=class extends D{constructor(){super(...arguments),this.sessions=new jl(this._client),this.threads=new Dl(this._client)}};Bo.Sessions=jl;Bo.Threads=Dl;var Ll=class extends D{create(e,r,n){return this._client.post(O`/threads/${e}/messages`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(O`/threads/${i}/messages/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/messages/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/threads/${e}/messages`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{thread_id:i}=r;return this._client.delete(O`/threads/${i}/messages/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Ul=class extends D{retrieve(e,r,n){let{thread_id:i,run_id:o,...s}=r;return this._client.get(O`/threads/${i}/runs/${o}/steps/${e}`,{query:s,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r,n){let{thread_id:i,...o}=r;return this._client.getAPIList(O`/threads/${i}/runs/${e}/steps`,Ae,{query:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var n1=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Go=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var cr,Xs,j_,Si,qm,Kn,Ks,Zl,Hs,Gm,yn,Wm,Bm,bd,vd,_d,i1,o1,s1,a1,l1,c1,u1,io=class extends Fo{constructor(){super(...arguments),cr.add(this),j_.set(this,[]),Si.set(this,{}),qm.set(this,{}),Kn.set(this,void 0),Ks.set(this,void 0),Zl.set(this,void 0),Hs.set(this,void 0),Gm.set(this,void 0),yn.set(this,void 0),Wm.set(this,void 0),Bm.set(this,void 0),bd.set(this,void 0)}[(j_=new WeakMap,Si=new WeakMap,qm=new WeakMap,Kn=new WeakMap,Ks=new WeakMap,Zl=new WeakMap,Hs=new WeakMap,Gm=new WeakMap,yn=new WeakMap,Wm=new WeakMap,Bm=new WeakMap,bd=new WeakMap,cr=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Xs;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=xi.fromReadableStream(e,this.controller);for await(let o of i)T(this,cr,"m",vd).call(this,o);if(i.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",_d).call(this))}toReadableStream(){return new xi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,i){let o=new Xs;return o._run(()=>o._runToolAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...i,signal:this.controller.signal});this._connected();for await(let l of a)T(this,cr,"m",vd).call(this,l);if(a.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",_d).call(this))}static createThreadAssistantStream(e,r,n){let i=new Xs;return i._run(()=>i._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,r,n,i){let o=new Xs;return o._run(()=>o._runAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return T(this,Wm,"f")}currentRun(){return T(this,Bm,"f")}currentMessageSnapshot(){return T(this,Kn,"f")}currentRunStepSnapshot(){return T(this,bd,"f")}async finalRunSteps(){return await this.done(),Object.values(T(this,Si,"f"))}async finalMessages(){return await this.done(),Object.values(T(this,qm,"f"))}async finalRun(){if(await this.done(),!T(this,Ks,"f"))throw Error("Final run was not received.");return T(this,Ks,"f")}async _createThreadAssistantStream(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)T(this,cr,"m",vd).call(this,a);if(s.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",_d).call(this))}async _createAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.create(r,s,{...i,signal:this.controller.signal});this._connected();for await(let l of a)T(this,cr,"m",vd).call(this,l);if(a.controller.signal?.aborted)throw new Gt;return this._addRun(T(this,cr,"m",_d).call(this))}static accumulateDelta(e,r){for(let[n,i]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let o=e[n];if(o==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof o=="string"&&typeof i=="string")o+=i;else if(typeof o=="number"&&typeof i=="number")o+=i;else if(rd(o)&&rd(i))o=this.accumulateDelta(o,i);else if(Array.isArray(o)&&Array.isArray(i)){if(o.every(s=>typeof s=="string"||typeof s=="number")){o.push(...i);continue}for(let s of i){if(!rd(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let a=s.index;if(a==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let l=o[a];l==null?o.push(s):o[a]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,i){return await this._createAssistantStream(r,e,n,i)}async _runToolAssistantStream(e,r,n,i){return await this._createToolAssistantStream(r,e,n,i)}};Xs=io,vd=function(e){if(!this.ended)switch(ue(this,Wm,e,"f"),T(this,cr,"m",s1).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T(this,cr,"m",u1).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":T(this,cr,"m",o1).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":T(this,cr,"m",i1).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},_d=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");if(!T(this,Ks,"f"))throw Error("Final run has not been received");return T(this,Ks,"f")},i1=function(e){let[r,n]=T(this,cr,"m",l1).call(this,e,T(this,Kn,"f"));ue(this,Kn,r,"f"),T(this,qm,"f")[r.id]=r;for(let i of n){let o=r.content[i.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let o=i.text,s=r.content[i.index];if(s&&s.type=="text")this._emit("textDelta",o,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=T(this,Zl,"f")){if(T(this,Hs,"f"))switch(T(this,Hs,"f").type){case"text":this._emit("textDone",T(this,Hs,"f").text,T(this,Kn,"f"));break;case"image_file":this._emit("imageFileDone",T(this,Hs,"f").image_file,T(this,Kn,"f"));break}ue(this,Zl,i.index,"f")}ue(this,Hs,r.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(T(this,Zl,"f")!==void 0){let i=e.data.content[T(this,Zl,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,T(this,Kn,"f"));break;case"text":this._emit("textDone",i.text,T(this,Kn,"f"));break}}T(this,Kn,"f")&&this._emit("messageDone",e.data),ue(this,Kn,void 0,"f")}},o1=function(e){let r=T(this,cr,"m",a1).call(this,e);switch(ue(this,bd,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==T(this,Gm,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(T(this,yn,"f")&&this._emit("toolCallDone",T(this,yn,"f")),ue(this,Gm,o.index,"f"),ue(this,yn,r.step_details.tool_calls[o.index],"f"),T(this,yn,"f")&&this._emit("toolCallCreated",T(this,yn,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ue(this,bd,void 0,"f"),e.data.step_details.type=="tool_calls"&&T(this,yn,"f")&&(this._emit("toolCallDone",T(this,yn,"f")),ue(this,yn,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},s1=function(e){T(this,j_,"f").push(e),this._emit("event",e)},a1=function(e){switch(e.event){case"thread.run.step.created":return T(this,Si,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=T(this,Si,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=Xs.accumulateDelta(r,n.delta);T(this,Si,"f")[e.data.id]=i}return T(this,Si,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":T(this,Si,"f")[e.data.id]=e.data;break}if(T(this,Si,"f")[e.data.id])return T(this,Si,"f")[e.data.id];throw new Error("No snapshot available")},l1=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let o of i.delta.content)if(o.index in r.content){let s=r.content[o.index];r.content[o.index]=T(this,cr,"m",c1).call(this,o,s)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},c1=function(e,r){return Xs.accumulateDelta(r,e)},u1=function(e){switch(ue(this,Bm,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":ue(this,Ks,e.data,"f"),T(this,yn,"f")&&(this._emit("toolCallDone",T(this,yn,"f")),ue(this,yn,void 0,"f"));break;case"thread.run.cancelling":break}};var Js=class extends D{constructor(){super(...arguments),this.steps=new Ul(this._client)}create(e,r,n){let{include:i,...o}=r;return this._client.post(O`/threads/${e}/runs`,{query:{include:i},body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(O`/threads/${i}/runs/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/runs/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/threads/${e}/runs`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{thread_id:i}=r;return this._client.post(O`/threads/${i}/runs/${e}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,r,n){return io.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...i}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await bi(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,n){return io.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:i,...o}=r;return this._client.post(O`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}async submitToolOutputsAndPoll(e,r,n){let i=await this.submitToolOutputs(e,r,n);return await this.poll(i.id,r,n)}submitToolOutputsStream(e,r,n){return io.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Js.Steps=Ul;var Ho=class extends D{constructor(){super(...arguments),this.runs=new Js(this._client),this.messages=new Ll(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/threads/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r){return this._client.delete(O`/threads/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return io.createThreadAssistantStream(e,this._client.beta.threads,r)}};Ho.Runs=Js;Ho.Messages=Ll;var Jn=class extends D{constructor(){super(...arguments),this.realtime=new Wo(this._client),this.chatkit=new Bo(this._client),this.assistants=new Ol(this._client),this.threads=new Ho(this._client)}};Jn.Realtime=Wo;Jn.ChatKit=Bo;Jn.Assistants=Ol;Jn.Threads=Ho;var Ys=class extends D{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1})}};var Fl=class extends D{retrieve(e,r,n){let{container_id:i}=r;return this._client.get(O`/containers/${i}/files/${e}/content`,{...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Qs=class extends D{constructor(){super(...arguments),this.content=new Fl(this._client)}create(e,r,n){return this._client.post(O`/containers/${e}/files`,gn({body:r,...n},this._client))}retrieve(e,r,n){let{container_id:i}=r;return this._client.get(O`/containers/${i}/files/${e}`,n)}list(e,r={},n){return this._client.getAPIList(O`/containers/${e}/files`,Ae,{query:r,...n})}delete(e,r,n){let{container_id:i}=r;return this._client.delete(O`/containers/${i}/files/${e}`,{...n,headers:B([{Accept:"*/*"},n?.headers])})}};Qs.Content=Fl;var Xo=class extends D{constructor(){super(...arguments),this.files=new Qs(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r})}retrieve(e,r){return this._client.get(O`/containers/${e}`,r)}list(e={},r){return this._client.getAPIList("/containers",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/containers/${e}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}};Xo.Files=Qs;var Vl=class extends D{create(e,r,n){let{include:i,...o}=r;return this._client.post(O`/conversations/${e}/items`,{query:{include:i},body:o,...n})}retrieve(e,r,n){let{conversation_id:i,...o}=r;return this._client.get(O`/conversations/${i}/items/${e}`,{query:o,...n})}list(e,r={},n){return this._client.getAPIList(O`/conversations/${e}/items`,eo,{query:r,...n})}delete(e,r,n){let{conversation_id:i}=r;return this._client.delete(O`/conversations/${i}/items/${e}`,n)}};var Ko=class extends D{constructor(){super(...arguments),this.items=new Vl(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r})}retrieve(e,r){return this._client.get(O`/conversations/${e}`,r)}update(e,r,n){return this._client.post(O`/conversations/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(O`/conversations/${e}`,r)}};Ko.Items=Vl;var ea=class extends D{create(e,r){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&Mt(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:i},...r});return n?o:(Mt(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(s=>(s&&s.data&&s.data.forEach(a=>{let l=a.embedding;a.embedding=n1(l)}),s)))}};var ql=class extends D{retrieve(e,r,n){let{eval_id:i,run_id:o}=r;return this._client.get(O`/evals/${i}/runs/${o}/output_items/${e}`,n)}list(e,r,n){let{eval_id:i,...o}=r;return this._client.getAPIList(O`/evals/${i}/runs/${e}/output_items`,Ae,{query:o,...n})}};var ta=class extends D{constructor(){super(...arguments),this.outputItems=new ql(this._client)}create(e,r,n){return this._client.post(O`/evals/${e}/runs`,{body:r,...n})}retrieve(e,r,n){let{eval_id:i}=r;return this._client.get(O`/evals/${i}/runs/${e}`,n)}list(e,r={},n){return this._client.getAPIList(O`/evals/${e}/runs`,Ae,{query:r,...n})}delete(e,r,n){let{eval_id:i}=r;return this._client.delete(O`/evals/${i}/runs/${e}`,n)}cancel(e,r,n){let{eval_id:i}=r;return this._client.post(O`/evals/${i}/runs/${e}`,n)}};ta.OutputItems=ql;var Jo=class extends D{constructor(){super(...arguments),this.runs=new ta(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r})}retrieve(e,r){return this._client.get(O`/evals/${e}`,r)}update(e,r,n){return this._client.post(O`/evals/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/evals",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/evals/${e}`,r)}};Jo.Runs=ta;var ra=class extends D{create(e,r){return this._client.post("/files",gn({body:e,...r},this._client))}retrieve(e,r){return this._client.get(O`/files/${e}`,r)}list(e={},r){return this._client.getAPIList("/files",Ae,{query:e,...r})}delete(e,r){return this._client.delete(O`/files/${e}`,r)}content(e,r){return this._client.get(O`/files/${e}/content`,{...r,headers:B([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=30*60*1e3}={}){let i=new Set(["processed","error","deleted"]),o=Date.now(),s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await bi(r),s=await this.retrieve(e),Date.now()-o>n)throw new Uo({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return s}};var Wl=class extends D{};var Bl=class extends D{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r})}};var na=class extends D{constructor(){super(...arguments),this.graders=new Bl(this._client)}};na.Graders=Bl;var Gl=class extends D{create(e,r,n){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,$i,{body:r,method:"post",...n})}retrieve(e,r={},n){return this._client.get(O`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n})}delete(e,r,n){let{fine_tuned_model_checkpoint:i}=r;return this._client.delete(O`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var ia=class extends D{constructor(){super(...arguments),this.permissions=new Gl(this._client)}};ia.Permissions=Gl;var Hl=class extends D{list(e,r={},n){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/checkpoints`,Ae,{query:r,...n})}};var oa=class extends D{constructor(){super(...arguments),this.checkpoints=new Hl(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r})}retrieve(e,r){return this._client.get(O`/fine_tuning/jobs/${e}`,r)}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",Ae,{query:e,...r})}cancel(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/cancel`,r)}listEvents(e,r={},n){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/events`,Ae,{query:r,...n})}pause(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/pause`,r)}resume(e,r){return this._client.post(O`/fine_tuning/jobs/${e}/resume`,r)}};oa.Checkpoints=Hl;var Yn=class extends D{constructor(){super(...arguments),this.methods=new Wl(this._client),this.jobs=new oa(this._client),this.checkpoints=new ia(this._client),this.alpha=new na(this._client)}};Yn.Methods=Wl;Yn.Jobs=oa;Yn.Checkpoints=ia;Yn.Alpha=na;var Xl=class extends D{};var Yo=class extends D{constructor(){super(...arguments),this.graderModels=new Xl(this._client)}};Yo.GraderModels=Xl;var sa=class extends D{createVariation(e,r){return this._client.post("/images/variations",gn({body:e,...r},this._client))}edit(e,r){return this._client.post("/images/edits",gn({body:e,...r,stream:e.stream??!1},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1})}};var aa=class extends D{retrieve(e,r){return this._client.get(O`/models/${e}`,r)}list(e){return this._client.getAPIList("/models",$i,e)}delete(e,r){return this._client.delete(O`/models/${e}`,r)}};var la=class extends D{create(e,r){return this._client.post("/moderations",{body:e,...r})}};var Kl=class extends D{accept(e,r,n){return this._client.post(O`/realtime/calls/${e}/accept`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}hangup(e,r){return this._client.post(O`/realtime/calls/${e}/hangup`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}refer(e,r,n){return this._client.post(O`/realtime/calls/${e}/refer`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}reject(e,r={},n){return this._client.post(O`/realtime/calls/${e}/reject`,{body:r,...n,headers:B([{Accept:"*/*"},n?.headers])})}};var Jl=class extends D{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r})}};var oo=class extends D{constructor(){super(...arguments),this.clientSecrets=new Jl(this._client),this.calls=new Kl(this._client)}};oo.ClientSecrets=Jl;oo.Calls=Kl;function d1(t,e){return!e||!p2(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:D_(t,e)}function D_(t,e){let r=t.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:g2(e,i)};if(i.type==="message"){let o=i.content.map(s=>s.type==="output_text"?{...s,parsed:f2(e,s.text)}:s);return{...i,content:o}}return i}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||Hm(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let o of i.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function f2(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function p2(t){return!!ud(t.text?.format)}function m2(t){return t?.$brand==="auto-parseable-tool"}function h2(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function g2(t,e){let r=h2(t.tools??[],e.name);return{...e,...e,parsed_arguments:m2(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Hm(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Yl,Xm,Qo,Km,f1,p1,m1,h1,Jm=class t extends Fo{constructor(e){super(),Yl.add(this),Xm.set(this,void 0),Qo.set(this,void 0),Km.set(this,void 0),ue(this,Xm,e,"f")}static createResponse(e,r,n){let i=new t(r);return i._run(()=>i._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),T(this,Yl,"m",f1).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)T(this,Yl,"m",p1).call(this,a,s);if(o.controller.signal?.aborted)throw new Gt;return T(this,Yl,"m",m1).call(this)}[(Xm=new WeakMap,Qo=new WeakMap,Km=new WeakMap,Yl=new WeakSet,f1=function(){this.ended||ue(this,Qo,void 0,"f")},p1=function(r,n){if(this.ended)return;let i=(s,a)=>{(n==null||a.sequence_number>n)&&this._emit(s,a)},o=T(this,Yl,"m",h1).call(this,r);switch(i("event",r),r.type){case"response.output_text.delta":{let s=o.output[r.output_index];if(!s)throw new ee(`missing output at index ${r.output_index}`);if(s.type==="message"){let a=s.content[r.content_index];if(!a)throw new ee(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new ee(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let s=o.output[r.output_index];if(!s)throw new ee(`missing output at index ${r.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...r,snapshot:s.arguments});break}default:i(r.type,r);break}},m1=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=T(this,Qo,"f");if(!r)throw new ee("request ended without sending any events");ue(this,Qo,void 0,"f");let n=y2(r,T(this,Xm,"f"));return ue(this,Km,n,"f"),n},h1=function(r){let n=T(this,Qo,"f");if(!n){if(r.type!=="response.created")throw new ee(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=ue(this,Qo,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);let o=i.type,s=r.part;o==="message"&&s.type!=="reasoning_text"?i.content.push(s):o==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);if(i.type==="message"){let o=i.content[r.content_index];if(!o)throw new ee(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new ee(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);i.type==="function_call"&&(i.arguments+=r.delta);break}case"response.reasoning_text.delta":{let i=n.output[r.output_index];if(!i)throw new ee(`missing output at index ${r.output_index}`);if(i.type==="reasoning"){let o=i.content?.[r.content_index];if(!o)throw new ee(`missing content at index ${r.content_index}`);if(o.type!=="reasoning_text")throw new ee(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=r.delta}break}case"response.completed":{ue(this,Qo,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=T(this,Km,"f");if(!e)throw new ee("stream ended without producing a ChatCompletion");return e}};function y2(t,e){return d1(t,e)}var Ql=class extends D{list(e,r={},n){return this._client.getAPIList(O`/responses/${e}/input_items`,Ae,{query:r,...n})}};var ec=class extends D{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r})}};var so=class extends D{constructor(){super(...arguments),this.inputItems=new Ql(this._client),this.inputTokens=new ec(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Hm(n),n))}retrieve(e,r={},n){return this._client.get(O`/responses/${e}`,{query:r,...n,stream:r?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&Hm(i),i))}delete(e,r){return this._client.delete(O`/responses/${e}`,{...r,headers:B([{Accept:"*/*"},r?.headers])})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>D_(n,e))}stream(e,r){return Jm.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(O`/responses/${e}/cancel`,r)}compact(e={},r){return this._client.post("/responses/compact",{body:e,...r})}};so.InputItems=Ql;so.InputTokens=ec;var tc=class extends D{create(e,r,n){return this._client.post(O`/uploads/${e}/parts`,gn({body:r,...n},this._client))}};var es=class extends D{constructor(){super(...arguments),this.parts=new tc(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r})}cancel(e,r){return this._client.post(O`/uploads/${e}/cancel`,r)}complete(e,r,n){return this._client.post(O`/uploads/${e}/complete`,{body:r,...n})}};es.Parts=tc;var g1=async t=>{let e=await Promise.allSettled(t),r=e.filter(i=>i.status==="rejected");if(r.length){for(let i of r)console.error(i.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var rc=class extends D{create(e,r,n){return this._client.post(O`/vector_stores/${e}/file_batches`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(O`/vector_stores/${i}/file_batches/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{vector_store_id:i}=r;return this._client.post(O`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r);return await this.poll(e,i.id,n)}listFiles(e,r,n){let{vector_store_id:i,...o}=r;return this._client.getAPIList(O`/vector_stores/${i}/file_batches/${e}/files`,Ae,{query:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await bi(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},i){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=i?.maxConcurrency??5,s=Math.min(o,r.length),a=this._client,l=r.values(),c=[...n];async function u(p){for(let f of p){let m=await a.files.create({file:f,purpose:"assistants"},i);c.push(m.id)}}let d=Array(s).fill(l).map(u);return await g1(d),await this.createAndPoll(e,{file_ids:c})}};var nc=class extends D{create(e,r,n){return this._client.post(O`/vector_stores/${e}/files`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(O`/vector_stores/${i}/files/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{vector_store_id:i,...o}=r;return this._client.post(O`/vector_stores/${i}/files/${e}`,{body:o,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(O`/vector_stores/${e}/files`,Ae,{query:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{vector_store_id:i}=r;return this._client.delete(O`/vector_stores/${i}/files/${e}`,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(e,i.id,n)}async poll(e,r,n){let i=B([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse(),s=o.data;switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let l=o.response.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await bi(a);break;case"failed":case"completed":return s}}}async upload(e,r,n){let i=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,r,n){let i=await this.upload(e,r,n);return await this.poll(e,i.id,n)}content(e,r,n){let{vector_store_id:i}=r;return this._client.getAPIList(O`/vector_stores/${i}/files/${e}/content`,$i,{...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var ao=class extends D{constructor(){super(...arguments),this.files=new nc(this._client),this.fileBatches=new rc(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(O`/vector_stores/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(O`/vector_stores/${e}`,{body:r,...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/vector_stores",Ae,{query:e,...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(O`/vector_stores/${e}`,{...r,headers:B([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}search(e,r,n){return this._client.getAPIList(O`/vector_stores/${e}/search`,$i,{body:r,method:"post",...n,headers:B([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};ao.Files=nc;ao.FileBatches=rc;var ca=class extends D{create(e,r){return this._client.post("/videos",b_({body:e,...r},this._client))}retrieve(e,r){return this._client.get(O`/videos/${e}`,r)}list(e={},r){return this._client.getAPIList("/videos",eo,{query:e,...r})}delete(e,r){return this._client.delete(O`/videos/${e}`,r)}downloadContent(e,r={},n){return this._client.get(O`/videos/${e}/content`,{query:r,...n,headers:B([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,r,n){return this._client.post(O`/videos/${e}/remix`,b_({body:r,...n},this._client))}};var ic,y1,Ym,ua=class extends D{constructor(){super(...arguments),ic.add(this)}async unwrap(e,r,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,r,n,i),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");T(this,ic,"m",y1).call(this,n);let o=B([r]).values,s=T(this,ic,"m",Ym).call(this,o,"webhook-signature"),a=T(this,ic,"m",Ym).call(this,o,"webhook-timestamp"),l=T(this,ic,"m",Ym).call(this,o,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new _i("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-c>i)throw new _i("Webhook timestamp is too old");if(c>u+i)throw new _i("Webhook timestamp is too new");let d=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=l?`${l}.${a}.${e}`:`${a}.${e}`,m=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of d)try{let y=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,y,new TextEncoder().encode(f)))return}catch{continue}throw new _i("The given webhook signature does not match the expected signature")}};ic=new WeakSet,y1=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ym=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var L_,U_,Qm,v1,be=class{constructor({baseURL:e=Go("OPENAI_BASE_URL"),apiKey:r=Go("OPENAI_API_KEY"),organization:n=Go("OPENAI_ORG_ID")??null,project:i=Go("OPENAI_PROJECT_ID")??null,webhookSecret:o=Go("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(L_.add(this),Qm.set(this,void 0),this.completions=new Ys(this),this.chat=new qo(this),this.embeddings=new ea(this),this.files=new ra(this),this.images=new sa(this),this.audio=new ki(this),this.moderations=new la(this),this.models=new aa(this),this.fineTuning=new Yn(this),this.graders=new Yo(this),this.vectorStores=new ao(this),this.webhooks=new ua(this),this.beta=new Jn(this),this.batches=new Gs(this),this.uploads=new es(this),this.responses=new so(this),this.realtime=new oo(this),this.conversations=new Ko(this),this.evals=new Jo(this),this.containers=new Xo(this),this.videos=new ca(this),r===void 0)throw new ee("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:r,organization:n,project:i,webhookSecret:o,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&SE())throw new ee(`It looks like you're running in a browser-like environment.
29
+
30
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
31
+ If you understand the risks and have appropriate mitigations in place,
32
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
33
+
34
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
35
+
36
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
37
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??U_.DEFAULT_TIMEOUT,this.logger=a.logger??console;let l="warn";this.logLevel=l,this.logLevel=m_(a.logLevel,"ClientOptions.logLevel",this)??m_(Go("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??EE(),ue(this,Qm,TE,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return B([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return f_(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zo}`}defaultIdempotencyKey(){return`stainless-node-retry-${r_()}`}makeStatusError(e,r,n,i){return Jt.generate(e,r,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof ee?n:new ee(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new ee(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let i=!T(this,L_,"m",v1).call(this)&&n||this.baseURL,o=yE(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return vE(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new Vs(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:l}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Mt(this).debug(`[${c}] sending request`,Qi({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new Gt;let p=new AbortController,f=await this.fetchWithTimeout(a,s,l,p).catch(td),m=Date.now();if(f instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Gt;let _=ed(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return Mt(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${g}`),Mt(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${g})`,Qi({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),this.retryRequest(i,r,n??c);throw Mt(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),Mt(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Qi({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),_?new Uo:new Lo({cause:f})}let h=[...f.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,_])=>", "+g+": "+JSON.stringify(_)).join(""),y=`[${c}${u}${h}] ${s.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){let g=await this.shouldRetry(f);if(r&&g){let M=`retrying, ${r} attempts remaining`;return await PE(f.body),Mt(this).info(`${y} - ${M}`),Mt(this).debug(`[${c}] response error (${M})`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(i,r,n??c,f.headers)}let _=g?"error; no more retries left":"error; not retryable";Mt(this).info(`${y} - ${_}`);let b=await f.text().catch(M=>td(M).message),E=wE(b),I=E?void 0:b;throw Mt(this).debug(`[${c}] response error (${_})`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:I,durationMs:Date.now()-d})),this.makeStatusError(f.status,E,I,f.headers)}return Mt(this).info(y),Mt(this).debug(`[${c}] response start`,Qi({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:i,controller:p,requestLogID:c,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new ad(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{};o&&o.addEventListener("abort",()=>i.abort());let l=setTimeout(()=>i.abort(),n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,u={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...a};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(o=l)}let a=i?.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await bi(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,l=this.buildURL(o,s,a);"timeout"in n&&bE("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=B([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...IE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=B([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Sm(e)}:T(this,Qm,"f").call(this,{body:e,headers:n})}};U_=be,Qm=new WeakMap,L_=new WeakSet,v1=function(){return this.baseURL!=="https://api.openai.com/v1"};be.OpenAI=U_;be.DEFAULT_TIMEOUT=6e5;be.OpenAIError=ee;be.APIError=Jt;be.APIConnectionError=Lo;be.APIConnectionTimeoutError=Uo;be.APIUserAbortError=Gt;be.NotFoundError=vl;be.ConflictError=_l;be.RateLimitError=wl;be.BadRequestError=hl;be.AuthenticationError=gl;be.InternalServerError=xl;be.PermissionDeniedError=yl;be.UnprocessableEntityError=bl;be.InvalidWebhookSignatureError=_i;be.toFile=Om;be.Completions=Ys;be.Chat=qo;be.Embeddings=ea;be.Files=ra;be.Images=sa;be.Audio=ki;be.Moderations=la;be.Models=aa;be.FineTuning=Yn;be.Graders=Yo;be.VectorStores=ao;be.Webhooks=ua;be.Beta=Jn;be.Batches=Gs;be.Uploads=es;be.Responses=so;be.Realtime=oo;be.Conversations=Ko;be.Evals=Jo;be.Containers=Xo;be.Videos=ca;var ur=[];for(eh=0;eh<256;++eh)ur.push((eh+256).toString(16).slice(1));var eh;function _1(t,e=0){return(ur[t[e+0]]+ur[t[e+1]]+ur[t[e+2]]+ur[t[e+3]]+"-"+ur[t[e+4]]+ur[t[e+5]]+"-"+ur[t[e+6]]+ur[t[e+7]]+"-"+ur[t[e+8]]+ur[t[e+9]]+"-"+ur[t[e+10]]+ur[t[e+11]]+ur[t[e+12]]+ur[t[e+13]]+ur[t[e+14]]+ur[t[e+15]]).toLowerCase()}var th,k2=new Uint8Array(16);function Z_(){if(!th&&(th=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!th))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return th(k2)}var S2=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),F_={randomUUID:S2};function I2(t,e,r){if(F_.randomUUID&&!e&&!t)return F_.randomUUID();t=t||{};var n=t.random||(t.rng||Z_)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return _1(n)}var dr=I2;var ts=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let r=new V_;return r.id=e,this.groups.push(r),r}group(e){return this.groups.find(r=>r.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,r)=>e+r.tokenCount,0)}removeOverflow(){let e=this.countTokens(),r=this.groups.reduce((n,i)=>n+i.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/r*this.size),l=Math.floor(s.weight/r*this.size),c=o.tokenCount-a;return s.tokenCount-l-c}),i=this.removeOneItem(n);if(!i)throw new Error("Too many items in the token window that cannot be removed.");e-=i.tokenCount}}removeOneItem(e){for(let r of e){let n=r.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let i=r.items[n];return r.items.splice(n,1),r.tokenCount-=i.tokenCount,i}return null}},V_=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
38
+ `;this.itemPadding=0;this.sortFunction=(e,r)=>e.sortOrder!==r.sortOrder?e.sortOrder-r.sortOrder:e.dateAdded!==r.dateAdded?e.dateAdded-r.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,r)=>(r.tokenCount=ts.countTokensInText(typeof r.data=="string"?r.data:JSON.stringify(r.data))+ts.countTokensInText(this.separator)+this.itemPadding,e+r.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let r=e;r.id===void 0&&(r.id=dr()),!r.sections?.length&&typeof r.data=="string"?r.text=r.data:r.text=r.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
39
+
40
+ `)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:ts.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+ts.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function rh(t){let e=(t||"").split(`
41
+ `);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let r=1/0;for(let n of e){let i=n.match(/^\s*/)?.[0].length||0;r=Math.min(r,i)}return r>0&&r<1/0&&(e=e.map(n=>n.substring(r))),e.join(`
42
+ `)}var E2={};function rs(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:E2}function bt(){return rs().intelliweave=rs().intelliweave||rs().webWeaver||{},rs().intelliweave}function b1(){if(bt().userID)return bt().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let t=localStorage.getItem("intelliweave.uid")||"";return t||(t=dr(),localStorage.setItem("intelliweave.uid",t),t)}else return dr()}function w1(t){let e=t;if(e?.type=="object"&&e.properties)return t;let r={type:"object",properties:{},required:[]};if(t&&Array.isArray(t)){let n=t;for(let i of n)r.properties[i.name]={type:i.type||"string",description:i.description||""}}return r}var nh=class nh{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return nh.debug?!0:typeof window<"u"&&bt().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...r){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...r),(...i)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...i)}};nh.debug=!1;var Ve=nh;var x1=new Ve("ChatBase"),oc=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new ts;return e.createGroup("context").setSeparator(`
43
+
44
+ `),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,r){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,r,n){this.messageGroup.add({id:"msg-"+dr(),source:r,data:n,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(r=>r.id==e||r.data?.kbItem?.name==e)?.data}async executeTool(e,r){if(!e)throw new Error("Tool not found");x1.debug(`Executing tool '${e.name}'`,r,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,r);let n;try{n=await e.callback(r)}catch(i){throw x1.error(`Error executing tool '${e.name}'`,i),i}return typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),n}};var q_=new Ve("ChatGPT"),ih=class extends oc{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new be({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,r){this.addUserMessage(e);let n=this.createOpenAIClient(),i=!0,o=[];for(;i;){let s="msg-"+dr();i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),q_.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let a=this.toolGroup.getAll().filter(d=>!!d?.data).map(d=>({type:"function",function:{name:d.data.name,description:d.data.description||"",parameters:{type:"object",...d.data?.params}}})),l,c;if(this.config.stream){let d=n.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let p of d){let f=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!f)continue;let m=this.parseMessageBlock(s,f,void 0,!0);this.config.onAIMessage?.([...o,m],!0),r?.([...o,m])}l=await d.finalMessage(),c=await d.totalUsage()}else{let d=await n.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(p=>p.data)],tools:a,parallel_tool_calls:!0});l=d.choices[0].message,c=d.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),q_.debug("Message received",l);let u=this.messageGroup.add(this.parseMessageBlock(s,l,c,!1));o.push(u),await Promise.all((l.tool_calls||[]).map(async d=>{if(d.type!="function")return;let p=this.findToolBySafeName(d.function.name);try{let f=null;try{f=d.function.arguments?JSON.parse(d.function.arguments):null}catch(y){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${y.message}`)}let m=await this.executeTool(p,f),h=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolSuccessResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:m}});o.push(h)}catch(f){let m=f?.message||"An unknown error occurred",h=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:p?.kbItem?.id,toolKbName:p?.kbItem?.name,toolErrorResponse:m,toolCallInstanceID:d.id,toolCallHiddenInUI:p?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${m}`}});o.push(h)}i=!0,this.config.onAIMessage?.(o,!0),r?.(o)})),this.stats.tokensUsed+=c?.total_tokens||0}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e,r,n,i){let o=[];r.reasoning&&o.push({type:"thinking",text:r.reasoning});for(let s of r.tool_calls||[]){if(s.type!="function")continue;let a=this.findToolBySafeName(s.function.name),l=null;if(s.function.arguments)try{l=JSON.parse(s.function.arguments)}catch(c){i||q_.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,c)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:l})}return typeof r.content=="string"&&o.push({type:"text",text:r.content||""}),{id:e,data:r,sections:o,source:"assistant",usage:{inputTokens:n?.prompt_tokens||0,outputTokens:n?.completion_tokens||0,cachedInputTokens:0,totalTokens:(n?.prompt_tokens||0)+(n?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};function he(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function U(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var W_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return W_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function lo(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var xd=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var pe=class extends Error{},nr=class t extends pe{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("request-id"),this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new ns({message:n,cause:xd(r)});let o=r;return e===400?new ac(e,o,n,i):e===401?new lc(e,o,n,i):e===403?new cc(e,o,n,i):e===404?new uc(e,o,n,i):e===409?new dc(e,o,n,i):e===422?new fc(e,o,n,i):e===429?new pc(e,o,n,i):e>=500?new mc(e,o,n,i):new t(e,o,n,i)}},fr=class extends nr{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ns=class extends nr{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},sc=class extends ns{constructor({message:e}={}){super({message:e??"Request timed out."})}},ac=class extends nr{},lc=class extends nr{},cc=class extends nr{},uc=class extends nr{},dc=class extends nr{},fc=class extends nr{},pc=class extends nr{},mc=class extends nr{};var T2=/^[a-z][a-z0-9+.-]*:/i,$1=t=>T2.test(t),B_=t=>(B_=Array.isArray,B_(t)),G_=B_;function H_(t){return typeof t!="object"?{}:t??{}}function k1(t){if(!t)return!0;for(let e in t)return!1;return!0}function S1(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var I1=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new pe(`${t} must be an integer`);if(e<0)throw new pe(`${t} must be a positive integer`);return e};var oh=t=>{try{return JSON.parse(t)}catch{return}};var E1=t=>new Promise(e=>setTimeout(e,t));var is="0.60.0";var z1=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function A2(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var z2=()=>{let t=A2();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":T1(Deno.build.os),"X-Stainless-Arch":P1(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":T1(globalThis.process.platform??"unknown"),"X-Stainless-Arch":P1(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=N2();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":is,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function N2(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var P1=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",T1=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),A1,N1=()=>A1??(A1=z2());function C1(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function X_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function sh(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return X_({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function $d(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function O1(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var R1=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function D1(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var M1;function kd(t){let e;return(M1??(e=new globalThis.TextEncoder,M1=e.encode.bind(e)))(t)}var j1;function K_(t){let e;return(j1??(e=new globalThis.TextDecoder,j1=e.decode.bind(e)))(t)}var vn,_n,co=class{constructor(){vn.set(this,void 0),_n.set(this,void 0),he(this,vn,new Uint8Array,"f"),he(this,_n,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kd(e):e;he(this,vn,D1([U(this,vn,"f"),r]),"f");let n=[],i;for(;(i=R2(U(this,vn,"f"),U(this,_n,"f")))!=null;){if(i.carriage&&U(this,_n,"f")==null){he(this,_n,i.index,"f");continue}if(U(this,_n,"f")!=null&&(i.index!==U(this,_n,"f")+1||i.carriage)){n.push(K_(U(this,vn,"f").subarray(0,U(this,_n,"f")-1))),he(this,vn,U(this,vn,"f").subarray(U(this,_n,"f")),"f"),he(this,_n,null,"f");continue}let o=U(this,_n,"f")!==null?i.preceding-1:i.preceding,s=K_(U(this,vn,"f").subarray(0,o));n.push(s),he(this,vn,U(this,vn,"f").subarray(i.index),"f"),he(this,_n,null,"f")}return n}flush(){return U(this,vn,"f").length?this.decode(`
45
+ `):[]}};vn=new WeakMap,_n=new WeakMap;co.NEWLINE_CHARS=new Set([`
46
+ `,"\r"]);co.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function R2(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function L1(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var lh={off:0,error:200,warn:300,info:400,debug:500},J_=(t,e,r)=>{if(t){if(S1(lh,t))return t;ir(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(lh))}`)}};function Sd(){}function ah(t,e,r){return!e||lh[t]>lh[r]?Sd:e[t].bind(e)}var M2={error:Sd,warn:Sd,info:Sd,debug:Sd},U1=new WeakMap;function ir(t){let e=t.logger,r=t.logLevel??"off";if(!e)return M2;let n=U1.get(e);if(n&&n[0]===r)return n[1];let i={error:ah("error",e,r),warn:ah("warn",e,r),info:ah("info",e,r),debug:ah("debug",e,r)};return U1.set(e,[r,i]),i}var uo=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Id,Ii=class t{constructor(e,r,n){this.iterator=e,Id.set(this,void 0),this.controller=r,he(this,Id,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?ir(n):console;async function*s(){if(i)throw new pe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of j2(e,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(c){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error")throw new nr(void 0,oh(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(lo(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new co,l=$d(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(i)throw new pe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let l of o())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(lo(l))return;throw l}finally{a||r.abort()}}return new t(s,r,n)}[(Id=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,U(this,Id,"f")),new t(()=>i(r),this.controller,U(this,Id,"f"))]}toReadableStream(){let e=this,r;return X_({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=kd(JSON.stringify(i)+`
47
+ `);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*j2(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pe("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pe("Attempted to iterate over a response with no body");let r=new Y_,n=new co,i=$d(t.body);for await(let o of D2(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*D2(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?kd(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=L1(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Y_=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
48
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=L2(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function L2(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function ch(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return ir(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):Ii.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){let d=await r.json();return Q_(d,r)}return await r.text()})();return ir(t).debug(`[${n}] response parsed`,uo({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function Q_(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ed,da=class t extends Promise{constructor(e,r,n=ch){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,Ed.set(this,void 0),he(this,Ed,e,"f")}_thenUnwrap(e){return new t(U(this,Ed,"f"),this.responsePromise,async(r,n)=>Q_(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(U(this,Ed,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Ed=new WeakMap;var uh,eb=class{constructor(e,r,n,i){uh.set(this,void 0),he(this,uh,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new pe("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,uh,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(uh=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Pd=class extends da{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await ch(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Nn=class extends eb{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...H_(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...H_(this.options.query),after_id:e}}:null}};var rb=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function fa(t,e,r){return rb(),new File(t,e??"unknown_file",r)}function Td(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var nb=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var F1=async(t,e)=>({...t,body:await F2(t.body,e)}),Z1=new WeakMap;function Z2(t){let e=typeof t=="function"?t:t.fetch,r=Z1.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return Z1.set(e,n),n}var F2=async(t,e)=>{if(!await Z2(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,i])=>tb(r,n,i))),r},V2=t=>t instanceof Blob&&"name"in t;var tb=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let n={},i=r.headers.get("Content-Type");i&&(n={type:i}),t.append(e,fa([await r.blob()],Td(r),n))}else if(nb(r))t.append(e,fa([await new Response(sh(r)).blob()],Td(r)));else if(V2(r))t.append(e,fa([r],Td(r),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>tb(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>tb(t,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var V1=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",q2=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&V1(t),W2=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function dh(t,e,r){if(rb(),t=await t,e||(e=Td(t)),q2(t))return t instanceof File&&e==null&&r==null?t:fa([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...r});if(W2(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),fa(await ib(i),e,r)}let n=await ib(t);if(!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return fa(n,e,r)}async function ib(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(V1(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(nb(t))for await(let r of t)e.push(...await ib(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${B2(t)}`)}return e}function B2(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var Ht=class{constructor(e){this._client=e}};var q1=Symbol.for("brand.privateNullableHeaders");function*H2(t){if(!t)return;if(q1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():G_(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=G_(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var rt=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of H2(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[q1]:!0,values:e,nulls:r}};function B1(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var W1=Object.freeze(Object.create(null)),X2=(t=B1)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,p)=>{/[?#]/.test(d)&&(i=!0);let f=n[p],m=(i?encodeURIComponent:t)(""+f);return p!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??W1)??W1)?.toString)&&(m=f+"",o.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),u+d+(p===n.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((p,f)=>{let m=" ".repeat(f.start-u),h="^".repeat(f.length);return u=f.start+f.length,p+m+h},"");throw new pe(`Path parameters result in path with invalid segments:
49
+ ${o.map(p=>p.error).join(`
50
+ `)}
51
+ ${s}
52
+ ${d}`)}return s},Sr=X2(B1);var hc=class extends Ht{list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/files",Nn,{query:i,...r,headers:rt([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(Sr`/v1/files/${e}`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/files/${e}/content`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/files/${e}`,{...n,headers:rt([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...i}=e;return this._client.post("/v1/files",F1({body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}};var gc=class extends Ht{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/models/${e}?beta=true`,{...n,headers:rt([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models?beta=true",Nn,{query:i,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var yc=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new co;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pe("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pe("Attempted to iterate over a response with no body");return new t($d(e.body),r)}};var vc=class extends Ht{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/messages/batches/${e}?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Nn,{query:i,...r,headers:rt([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(Sr`/v1/messages/batches/${e}?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:i}=r??{};return this._client.post(Sr`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:rt([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let i=await this.retrieve(e);if(!i.results_url)throw new pe(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);let{betas:o}=r??{};return this._client.get(i.results_url,{...n,headers:rt([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>yc.fromResponse(a.response,a.controller))}};var Q2=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e++;continue}if(n==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(n===":"){r.push({type:"separator",value:":"}),e++;continue}if(n===","){r.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=t[++e];n!=='"';){if(e===t.length){l=!0;break}if(n==="\\"){if(e++,e===t.length){l=!0;break}a+=n+t[e],n=t[++e]}else a+=n,n=t[++e]}n=t[++e],l||r.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=t[++e]);n&&o.test(n)||n===".";)a+=n,n=t[++e];r.push({type:"number",value:a});continue}let s=/[a-z]/i;if(n&&s.test(n)){let a="";for(;n&&s.test(n)&&e!==t.length;)a+=n,n=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},_c=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),_c(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),_c(t);case"string":let n=t[t.length-2];if(n?.type==="delimiter")return t=t.slice(0,t.length-1),_c(t);if(n?.type==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),_c(t);break;case"delimiter":return t=t.slice(0,t.length-1),_c(t);break}return t},eL=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},tL=t=>{let e="";return t.map(r=>{switch(r.type){case"string":e+='"'+r.value+'"';break;default:e+=r.value;break}}),e},fh=t=>JSON.parse(tL(eL(_c(Q2(t)))));var Cn,os,Ad,ph,zd,Nd,mh,Cd,fo,Od,hh,gh,bc,yh,vh,ob,G1,_h,sb,ab,lb,H1,X1="__json_buf";function K1(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var bh=class t{constructor(){Cn.add(this),this.messages=[],this.receivedMessages=[],os.set(this,void 0),this.controller=new AbortController,Ad.set(this,void 0),ph.set(this,()=>{}),zd.set(this,()=>{}),Nd.set(this,void 0),mh.set(this,()=>{}),Cd.set(this,()=>{}),fo.set(this,{}),Od.set(this,!1),hh.set(this,!1),gh.set(this,!1),bc.set(this,!1),yh.set(this,void 0),vh.set(this,void 0),_h.set(this,e=>{if(he(this,hh,!0,"f"),lo(e)&&(e=new fr),e instanceof fr)return he(this,gh,!0,"f"),this._emit("abort",e);if(e instanceof pe)return this._emit("error",e);if(e instanceof Error){let r=new pe(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new pe(String(e)))}),he(this,Ad,new Promise((e,r)=>{he(this,ph,e,"f"),he(this,zd,r,"f")}),"f"),he(this,Nd,new Promise((e,r)=>{he(this,mh,e,"f"),he(this,Cd,r,"f")}),"f"),U(this,Ad,"f").catch(()=>{}),U(this,Nd,"f").catch(()=>{})}get response(){return U(this,yh,"f")}get request_id(){return U(this,vh,"f")}async withResponse(){let e=await U(this,Ad,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let i=new t;for(let o of r.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},U(this,_h,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{U(this,Cn,"m",sb).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)U(this,Cn,"m",ab).call(this,l);if(a.controller.signal?.aborted)throw new fr;U(this,Cn,"m",lb).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(he(this,yh,e,"f"),he(this,vh,e?.headers.get("request-id"),"f"),U(this,ph,"f").call(this,e),this._emit("connect"))}get ended(){return U(this,Od,"f")}get errored(){return U(this,hh,"f")}get aborted(){return U(this,gh,"f")}abort(){this.controller.abort()}on(e,r){return(U(this,fo,"f")[e]||(U(this,fo,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=U(this,fo,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(U(this,fo,"f")[e]||(U(this,fo,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{he(this,bc,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){he(this,bc,!0,"f"),await U(this,Nd,"f")}get currentMessage(){return U(this,os,"f")}async finalMessage(){return await this.done(),U(this,Cn,"m",ob).call(this)}async finalText(){return await this.done(),U(this,Cn,"m",G1).call(this)}_emit(e,...r){if(U(this,Od,"f"))return;e==="end"&&(he(this,Od,!0,"f"),U(this,mh,"f").call(this));let n=U(this,fo,"f")[e];if(n&&(U(this,fo,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!U(this,bc,"f")&&!n?.length&&Promise.reject(i),U(this,zd,"f").call(this,i),U(this,Cd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!U(this,bc,"f")&&!n?.length&&Promise.reject(i),U(this,zd,"f").call(this,i),U(this,Cd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",U(this,Cn,"m",ob).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{U(this,Cn,"m",sb).call(this),this._connected(null);let o=Ii.fromReadableStream(e,this.controller);for await(let s of o)U(this,Cn,"m",ab).call(this,s);if(o.controller.signal?.aborted)throw new fr;U(this,Cn,"m",lb).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(os=new WeakMap,Ad=new WeakMap,ph=new WeakMap,zd=new WeakMap,Nd=new WeakMap,mh=new WeakMap,Cd=new WeakMap,fo=new WeakMap,Od=new WeakMap,hh=new WeakMap,gh=new WeakMap,bc=new WeakMap,yh=new WeakMap,vh=new WeakMap,_h=new WeakMap,Cn=new WeakSet,ob=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},G1=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new pe("stream ended without producing a content block with type=text");return r.join(" ")},sb=function(){this.ended||he(this,os,void 0,"f")},ab=function(r){if(this.ended)return;let n=U(this,Cn,"m",H1).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{K1(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{he(this,os,n,"f");break}case"content_block_start":case"message_delta":break}},lb=function(){if(this.ended)throw new pe("stream has ended, this shouldn't happen");let r=U(this,os,"f");if(!r)throw new pe("request ended without sending any chunks");return he(this,os,void 0,"f"),r},H1=function(r){let n=U(this,os,"f");if(r.type==="message_start"){if(n)throw new pe(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new pe(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.container=r.delta.container,n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push(r.content_block),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&K1(i)){let o=i[X1]||"";o+=r.delta.partial_json;let s={...i};if(Object.defineProperty(s,X1,{value:o,enumerable:!1,writable:!0}),o)try{s.input=fh(o)}catch(a){let l=new pe(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);U(this,_h,"f").call(this,l)}n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ii(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var wh={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var J1={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"},pa=class extends Ht{constructor(){super(...arguments),this.batches=new vc(this._client)}create(e,r){let{betas:n,...i}=e;i.model in J1&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${J1[i.model]}
53
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let o=this._client._options.timeout;if(!i.stream&&o==null){let s=wh[i.model]??void 0;o=this._client.calculateNonstreamingTimeout(i.max_tokens,s)}return this._client.post("/v1/messages?beta=true",{body:i,timeout:o??6e5,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return bh.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...i}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...r,headers:rt([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}};pa.Batches=vc;var Ei=class extends Ht{constructor(){super(...arguments),this.models=new gc(this._client),this.messages=new pa(this._client),this.files=new hc(this._client)}};Ei.Models=gc;Ei.Messages=pa;Ei.Files=hc;var ma=class extends Ht{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}};var On,ss,Rd,xh,Md,jd,$h,Dd,po,Ld,kh,Sh,wc,Ih,Eh,cb,Y1,ub,db,fb,pb,Q1,eP="__json_buf";function tP(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Ph=class t{constructor(){On.add(this),this.messages=[],this.receivedMessages=[],ss.set(this,void 0),this.controller=new AbortController,Rd.set(this,void 0),xh.set(this,()=>{}),Md.set(this,()=>{}),jd.set(this,void 0),$h.set(this,()=>{}),Dd.set(this,()=>{}),po.set(this,{}),Ld.set(this,!1),kh.set(this,!1),Sh.set(this,!1),wc.set(this,!1),Ih.set(this,void 0),Eh.set(this,void 0),ub.set(this,e=>{if(he(this,kh,!0,"f"),lo(e)&&(e=new fr),e instanceof fr)return he(this,Sh,!0,"f"),this._emit("abort",e);if(e instanceof pe)return this._emit("error",e);if(e instanceof Error){let r=new pe(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new pe(String(e)))}),he(this,Rd,new Promise((e,r)=>{he(this,xh,e,"f"),he(this,Md,r,"f")}),"f"),he(this,jd,new Promise((e,r)=>{he(this,$h,e,"f"),he(this,Dd,r,"f")}),"f"),U(this,Rd,"f").catch(()=>{}),U(this,jd,"f").catch(()=>{})}get response(){return U(this,Ih,"f")}get request_id(){return U(this,Eh,"f")}async withResponse(){let e=await U(this,Rd,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let i=new t;for(let o of r.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},U(this,ub,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{U(this,On,"m",db).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)U(this,On,"m",fb).call(this,l);if(a.controller.signal?.aborted)throw new fr;U(this,On,"m",pb).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(he(this,Ih,e,"f"),he(this,Eh,e?.headers.get("request-id"),"f"),U(this,xh,"f").call(this,e),this._emit("connect"))}get ended(){return U(this,Ld,"f")}get errored(){return U(this,kh,"f")}get aborted(){return U(this,Sh,"f")}abort(){this.controller.abort()}on(e,r){return(U(this,po,"f")[e]||(U(this,po,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=U(this,po,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(U(this,po,"f")[e]||(U(this,po,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{he(this,wc,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){he(this,wc,!0,"f"),await U(this,jd,"f")}get currentMessage(){return U(this,ss,"f")}async finalMessage(){return await this.done(),U(this,On,"m",cb).call(this)}async finalText(){return await this.done(),U(this,On,"m",Y1).call(this)}_emit(e,...r){if(U(this,Ld,"f"))return;e==="end"&&(he(this,Ld,!0,"f"),U(this,$h,"f").call(this));let n=U(this,po,"f")[e];if(n&&(U(this,po,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!U(this,wc,"f")&&!n?.length&&Promise.reject(i),U(this,Md,"f").call(this,i),U(this,Dd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!U(this,wc,"f")&&!n?.length&&Promise.reject(i),U(this,Md,"f").call(this,i),U(this,Dd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",U(this,On,"m",cb).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{U(this,On,"m",db).call(this),this._connected(null);let o=Ii.fromReadableStream(e,this.controller);for await(let s of o)U(this,On,"m",fb).call(this,s);if(o.controller.signal?.aborted)throw new fr;U(this,On,"m",pb).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(ss=new WeakMap,Rd=new WeakMap,xh=new WeakMap,Md=new WeakMap,jd=new WeakMap,$h=new WeakMap,Dd=new WeakMap,po=new WeakMap,Ld=new WeakMap,kh=new WeakMap,Sh=new WeakMap,wc=new WeakMap,Ih=new WeakMap,Eh=new WeakMap,ub=new WeakMap,On=new WeakSet,cb=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Y1=function(){if(this.receivedMessages.length===0)throw new pe("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new pe("stream ended without producing a content block with type=text");return r.join(" ")},db=function(){this.ended||he(this,ss,void 0,"f")},fb=function(r){if(this.ended)return;let n=U(this,On,"m",Q1).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{tP(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{he(this,ss,n,"f");break}case"content_block_start":case"message_delta":break}},pb=function(){if(this.ended)throw new pe("stream has ended, this shouldn't happen");let r=U(this,ss,"f");if(!r)throw new pe("request ended without sending any chunks");return he(this,ss,void 0,"f"),r},Q1=function(r){let n=U(this,ss,"f");if(r.type==="message_start"){if(n)throw new pe(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new pe(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push({...r.content_block}),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&tP(i)){let o=i[eP]||"";o+=r.delta.partial_json;let s={...i};Object.defineProperty(s,eP,{value:o,enumerable:!1,writable:!0}),o&&(s.input=fh(o)),n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ii(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var xc=class extends Ht{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(Sr`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",Nn,{query:e,...r})}delete(e,r){return this._client.delete(Sr`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(Sr`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new pe(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:rt([{Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,o)=>yc.fromResponse(o.response,o.controller))}};var as=class extends Ht{constructor(){super(...arguments),this.batches=new xc(this._client)}create(e,r){e.model in rP&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${rP[e.model]}
54
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let i=wh[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,stream:e.stream??!1})}stream(e,r){return Ph.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},rP={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};as.Batches=xc;var ha=class extends Ht{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(Sr`/v1/models/${e}`,{...n,headers:rt([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models",Nn,{query:i,...r,headers:rt([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var Ud=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var mb,hb,Th,nP,zt=class{constructor({baseURL:e=Ud("ANTHROPIC_BASE_URL"),apiKey:r=Ud("ANTHROPIC_API_KEY")??null,authToken:n=Ud("ANTHROPIC_AUTH_TOKEN")??null,...i}={}){mb.add(this),Th.set(this,void 0);let o={apiKey:r,authToken:n,...i,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&z1())throw new pe(`It looks like you're running in a browser-like environment.
3
55
 
4
- `)||"";let i=this.items.find(o=>o.id===e.id);return i?(this.tokenCount-=i.tokenCount,Object.assign(i,e),e=i):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.source===void 0&&(e.source="user"),e.sections===void 0&&(e.sections=[]),e.tokenCount=e.disabled?0:k.countTokensInText(typeof t.data=="string"?t.data:JSON.stringify(t.data))+k.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(t=>t.text).join(this.separator)}getAll(){return this.items.filter(t=>!t.disabled)}empty(){this.items=[],this.tokenCount=0}};import{v4 as et}from"uuid";import{v4 as Ge}from"uuid";function Q(u){let t=(u||"").split(`
5
- `);for(;t.length>0&&t[0].trim()=="";)t.shift();for(;t.length>0&&t[t.length-1].trim()=="";)t.pop();let e=1/0;for(let i of t){let o=i.match(/^\s*/)?.[0].length||0;e=Math.min(e,o)}return e>0&&e<1/0&&(t=t.map(i=>i.substring(e))),t.join(`
6
- `)}var qe={};function C(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:qe}function m(){return C().intelliweave=C().intelliweave||C().webWeaver||{},C().intelliweave}function Ae(){if(m().userID)return m().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let u=localStorage.getItem("intelliweave.uid")||"";return u||(u=Ge(),localStorage.setItem("intelliweave.uid",u),u)}else return Ge()}function Le(u){let t=u;if(t?.type=="object"&&t.properties)return u;let e={type:"object",properties:{},required:[]};if(u&&Array.isArray(u)){let i=u;for(let o of i)e.properties[o.name]={type:o.type||"string",description:o.description||""}}return e}var $=class ${constructor(t){this.module="IntelliWeave";this.module=t}get debugEnabled(){return $.debug?!0:typeof window<"u"&&m().debug}log(...t){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...t)}debug(...t){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...t)}info(...t){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...t)}warn(...t){console.warn(`[IntelliWeave > ${this.module}]`,...t)}error(...t){console.error(`[IntelliWeave > ${this.module}]`,...t)}timer(t,...e){let i=Date.now();return this.debug(`[${t} 0ms] Started`,...e),(...o)=>this.debug(`[${t} ${Math.floor(Date.now()-i)}ms]`,...o)}};$.debug=!1;var p=$;var Ze=new p("ChatBase"),Z=class{constructor(t){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let t=new k;return t.createGroup("context").setSeparator(`
56
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
57
+ If you understand the risks and have appropriate mitigations in place,
58
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
7
59
 
8
- `),t.createGroup("actions").setItemPadding(25),t.createGroup("messages").setItemPadding(10),t})();this.config=t,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let t=this.config.endpoint;return t.endsWith("/chat/completions")&&(t=t.substring(0,t.length-17)),t}async sendMessage(t,e){throw new Error("Not implemented")}addUserMessage(t){throw new Error("Not implemented")}addAssistantMessage(t){throw new Error("Not implemented")}addTextMessage(t,e,i){this.messageGroup.add({id:"msg-"+et(),source:e,data:i,sections:[{type:"text",text:t}]})}onBeforeIncomingMessage(t){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(t){return this.toolGroup.add({id:t.name,data:t,cannotRemove:!t.canRemove,sortOrder:101,disabled:!!t.kbItem?.disabled})}findToolBySafeName(t){return this.toolGroup.getAll().find(e=>e.id==t||e.data?.kbItem?.name==t)?.data}async executeTool(t,e){if(!t)throw new Error("Tool not found");Ze.debug(`Executing tool '${t.name}'`,e,t),this.config.onAIToolStart?.(t.kbItem?.name||t.name,e);let i;try{i=await t.callback(e)}catch(o){throw Ze.error(`Error executing tool '${t.name}'`,o),o}return typeof i!="string"&&(i=JSON.stringify(i)||""),(i===""||i==="undefined")&&(i="success"),i}};import{v4 as it}from"uuid";var Ie=new p("ChatGPT"),q=class extends Z{addUserMessage(t){this.addTextMessage(t,"user",{role:"user",content:t||""})}addAssistantMessage(t){this.addTextMessage(t,"assistant",{role:"assistant",content:t||""})}createOpenAIClient(){return new tt({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(t,e){this.addUserMessage(t);let i=this.createOpenAIClient(),o=!0,s=[];for(;o;){let n="msg-"+it();o=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Ie.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let a=this.toolGroup.getAll().filter(d=>!!d?.data).map(d=>({type:"function",function:{name:d.data.name,description:d.data.description||"",parameters:{type:"object",...d.data?.params}}})),l,c;if(this.config.stream){let d=i.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(h=>h.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let h of d){let g=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!g)continue;let v=this.parseMessageBlock(n,g,void 0,!0);this.config.onAIMessage?.([...s,v],!0),e?.([...s,v])}l=await d.finalMessage(),c=await d.totalUsage()}else{let d=await i.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(h=>h.data)],tools:a,parallel_tool_calls:!0});l=d.choices[0].message,c=d.usage}l.role=="assistant"&&!l.content&&!l.tool_calls?.length&&(l.content=""),Ie.debug("Message received",l);let r=this.messageGroup.add(this.parseMessageBlock(n,l,c,!1));s.push(r),await Promise.all((l.tool_calls||[]).map(async d=>{if(d.type!="function")return;let h=this.findToolBySafeName(d.function.name);try{let g=null;try{g=d.function.arguments?JSON.parse(d.function.arguments):null}catch(L){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${L.message}`)}let v=await this.executeTool(h,g),x=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolSuccessResponse:v,toolCallInstanceID:d.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:v}});s.push(x)}catch(g){let v=g?.message||"An unknown error occurred",x=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:h?.kbItem?.id,toolKbName:h?.kbItem?.name,toolErrorResponse:v,toolCallInstanceID:d.id,toolCallHiddenInUI:h?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${v}`}});s.push(x)}o=!0,this.config.onAIMessage?.(s,!0),e?.(s)})),this.stats.tokensUsed+=c?.total_tokens||0}return this.config.onAIMessage?.(s,!1),e?.(s),s}parseMessageBlock(t,e,i,o){let s=[];e.reasoning&&s.push({type:"thinking",text:e.reasoning});for(let n of e.tool_calls||[]){if(n.type!="function")continue;let a=this.findToolBySafeName(n.function.name),l=null;if(n.function.arguments)try{l=JSON.parse(n.function.arguments)}catch(c){o||Ie.error(`Failed to parse tool parameters for tool call ${n.function.name}:`,c)}s.push({type:"tool_call",toolName:n.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:n.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:l})}return typeof e.content=="string"&&s.push({type:"text",text:e.content||""}),{id:t,data:e,sections:s,source:"assistant",usage:{inputTokens:i?.prompt_tokens||0,outputTokens:i?.completion_tokens||0,cachedInputTokens:0,totalTokens:(i?.prompt_tokens||0)+(i?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};import ot from"@anthropic-ai/sdk";import{v4 as st}from"uuid";var Ee=new p("AnthropicChat"),ee=class extends Z{addUserMessage(t){this.addTextMessage(t,"user",{role:"user",content:t||""})}addAssistantMessage(t){this.addTextMessage(t,"assistant",{role:"assistant",content:t||""})}async sendMessage(t,e){this.addUserMessage(t);let i=new ot({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),o=!0,s=[];for(;o;){o=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Ee.debug("Before processing state",{messages:this.messageGroup.getAll().map(r=>r.data),tools:this.toolGroup.getAll().map(r=>r.data),context:this.contextGroup.getAll().map(r=>r.text)});let n=this.toolGroup.getAll().map(r=>({name:r.data?.name||"",description:r.data?.description||"",input_schema:{...r.data?.params,type:"object"}})),a;if(this.config.stream){let r=i.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:n,stream:!0});r.on("streamEvent",(d,h)=>{let g=this.parseMessageBlock(h);this.config.onAIMessage?.([...s,g],!0),e?.([...s,g])});try{a=await r.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await i.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(r=>r.data),tools:n})}catch(r){throw r?.error?.error?.message?r.error.error:r}if(Ee.debug("Message received",a),a.content?.length){let r=this.messageGroup.add(this.parseMessageBlock(a));s.push(r)}let l=[],c=[];if(await Promise.all(a.content.map(async r=>{if(r.type!="tool_use")return;let d=this.findToolBySafeName(r.name);try{let h=await this.executeTool(d,r.input);c.push({type:"tool_result",tool_use_id:r.id,content:h}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:r.name,toolSuccessResponse:h,toolCallInstanceID:r.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(h){let g=h?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:r.id,content:`Error performing tool call ${r.name}: ${g}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:r.name,toolErrorResponse:g,toolCallInstanceID:r.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),c.length>0){let r=this.messageGroup.add({id:"msg-"+st(),sections:l,data:{role:"user",content:c}});s.push(r),o=!0,this.config.onAIMessage?.(s,!0),e?.(s)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(s,!1),e?.(s),s}parseMessageBlock(t){let e=[];for(let i of t.content)if(i.type=="thinking")e.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")e.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);e.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:t.id,data:{role:t.role,content:t.content},sections:e,source:"assistant",usage:{inputTokens:t.usage?.input_tokens||0,outputTokens:t.usage?.output_tokens||0,cachedInputTokens:t.usage?.cache_read_input_tokens||0,totalTokens:(t.usage?.input_tokens||0)+(t.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as Xe}from"uuid";import pt from"minisearch";var We=u=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(t,e)=>{let i=await e.knowledgeBase.search(t.query),o=e;o._lastKBsearch=t.query,o._nextRequestUseKBitems=i;let s=i.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
9
- `)||"- (none)",n=i.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
60
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
61
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??hb.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s="warn";this.logLevel=s,this.logLevel=J_(o.logLevel,"ClientOptions.logLevel",this)??J_(Ud("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??C1(),he(this,Th,R1,"f"),this._options=o,this.apiKey=r,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return rt([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return rt([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return rt([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new pe(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${is}`}defaultIdempotencyKey(){return`stainless-node-retry-${W_()}`}makeStatusError(e,r,n,i){return nr.generate(e,r,n,i)}buildURL(e,r,n){let i=!U(this,mb,"m",nP).call(this)&&n||this.baseURL,o=$1(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return k1(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new pe("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new da(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:l}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(ir(this).debug(`[${c}] sending request`,uo({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new fr;let p=new AbortController,f=await this.fetchWithTimeout(a,s,l,p).catch(xd),m=Date.now();if(f instanceof Error){let g=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new fr;let _=lo(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return ir(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${g}`),ir(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${g})`,uo({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),this.retryRequest(i,r,n??c);throw ir(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),ir(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,uo({retryOfRequestLogID:n,url:a,durationMs:m-d,message:f.message})),_?new sc:new ns({cause:f})}let h=[...f.headers.entries()].filter(([g])=>g==="request-id").map(([g,_])=>", "+g+": "+JSON.stringify(_)).join(""),y=`[${c}${u}${h}] ${s.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${m-d}ms`;if(!f.ok){let g=await this.shouldRetry(f);if(r&&g){let M=`retrying, ${r} attempts remaining`;return await O1(f.body),ir(this).info(`${y} - ${M}`),ir(this).debug(`[${c}] response error (${M})`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),this.retryRequest(i,r,n??c,f.headers)}let _=g?"error; no more retries left":"error; not retryable";ir(this).info(`${y} - ${_}`);let b=await f.text().catch(M=>xd(M).message),E=oh(b),I=E?void 0:b;throw ir(this).debug(`[${c}] response error (${_})`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:I,durationMs:Date.now()-d})),this.makeStatusError(f.status,E,I,f.headers)}return ir(this).info(y),ir(this).debug(`[${c}] response start`,uo({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:m-d})),{response:f,options:i,controller:p,requestLogID:c,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Pd(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{};o&&o.addEventListener("abort",()=>i.abort());let l=setTimeout(()=>i.abort(),n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,u={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...a};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(o=l)}let a=i?.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await E1(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new pe("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,l=this.buildURL(o,s,a);"timeout"in n&&I1("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=rt([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...N1(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=rt([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:sh(e)}:U(this,Th,"f").call(this,{body:e,headers:n})}};hb=zt,Th=new WeakMap,mb=new WeakSet,nP=function(){return this.baseURL!=="https://api.anthropic.com"};zt.Anthropic=hb;zt.HUMAN_PROMPT=`
62
+
63
+ Human:`;zt.AI_PROMPT=`
64
+
65
+ Assistant:`;zt.DEFAULT_TIMEOUT=6e5;zt.AnthropicError=pe;zt.APIError=nr;zt.APIConnectionError=ns;zt.APIConnectionTimeoutError=sc;zt.APIUserAbortError=fr;zt.NotFoundError=uc;zt.ConflictError=dc;zt.RateLimitError=pc;zt.BadRequestError=ac;zt.AuthenticationError=lc;zt.InternalServerError=mc;zt.PermissionDeniedError=cc;zt.UnprocessableEntityError=fc;zt.toFile=dh;var Qn=class extends zt{constructor(){super(...arguments),this.completions=new ma(this),this.messages=new as(this),this.models=new ha(this),this.beta=new Ei(this)}};Qn.Completions=ma;Qn.Messages=as;Qn.Models=ha;Qn.Beta=Ei;var{HUMAN_PROMPT:oL,AI_PROMPT:sL}=Qn;var iP=new Ve("AnthropicChat"),Ah=class extends oc{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,r){this.addUserMessage(e);let n=new Qn({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),iP.debug("Before processing state",{messages:this.messageGroup.getAll().map(u=>u.data),tools:this.toolGroup.getAll().map(u=>u.data),context:this.contextGroup.getAll().map(u=>u.text)});let s=this.toolGroup.getAll().map(u=>({name:u.data?.name||"",description:u.data?.description||"",input_schema:{...u.data?.params,type:"object"}})),a;if(this.config.stream){let u=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:s,stream:!0});u.on("streamEvent",(d,p)=>{let f=this.parseMessageBlock(p);this.config.onAIMessage?.([...o,f],!0),r?.([...o,f])});try{a=await u.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(u=>u.data),tools:s})}catch(u){throw u?.error?.error?.message?u.error.error:u}if(iP.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a));o.push(u)}let l=[],c=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let p=await this.executeTool(d,u.input);c.push({type:"tool_result",tool_use_id:u.id,content:p}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(p){let f=p?.message||"An unknown error occurred";c.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${f}`}),l.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),c.length>0){let u=this.messageGroup.add({id:"msg-"+dr(),sections:l,data:{role:"user",content:c}});o.push(u),i=!0,this.config.onAIMessage?.(o,!0),r?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e){let r=[];for(let n of e.content)if(n.type=="thinking")r.push({type:"thinking",text:n.thinking||""});else if(n.type=="text")r.push({type:"text",text:n.text||""});else if(n.type=="tool_use"){let i=this.findToolBySafeName(n.name);r.push({type:"tool_call",toolName:n.name,toolKbID:i?.kbItem?.id,toolKbName:i?.kbItem?.name,toolParameters:n.input,toolCallInstanceID:n.id,toolCallHiddenInUI:i?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:r,source:"assistant",usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};var gt=function(){return gt=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},gt.apply(this,arguments)};function aL(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function a(u){try{c(n.next(u))}catch(d){s(d)}}function l(u){try{c(n.throw(u))}catch(d){s(d)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function lL(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(r=0)),r;)try{if(n=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,i=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){r.label=c[1];break}if(c[0]===6&&r.label<o[1]){r.label=o[1],o=c;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(c);break}o[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(u){c=[6,u],i=0}finally{n=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Oe(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jt(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}var cL="ENTRIES",cP="KEYS",uP="VALUES",pr="",gb=function(){function t(e,r){var n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}return t.prototype.next=function(){var e=this.dive();return this.backtrack(),e},t.prototype.dive=function(){if(this._path.length===0)return{done:!0,value:void 0};var e=$c(this._path),r=e.node,n=e.keys;if($c(n)===pr)return{done:!1,value:this.result()};var i=r.get($c(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()},t.prototype.backtrack=function(){if(this._path.length!==0){var e=$c(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}},t.prototype.key=function(){return this.set._prefix+this._path.map(function(e){var r=e.keys;return $c(r)}).filter(function(e){return e!==pr}).join("")},t.prototype.value=function(){return $c(this._path).node.get(pr)},t.prototype.result=function(){switch(this._type){case uP:return this.value();case cP:return this.key();default:return[this.key(),this.value()]}},t.prototype[Symbol.iterator]=function(){return this},t}(),$c=function(t){return t[t.length-1]},uL=function(t,e,r){var n=new Map;if(e===void 0)return n;for(var i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1),a=0;a<i;++a)s[a]=a;for(var l=1;l<o;++l)s[l*i]=l;return dP(t,e,r,n,s,1,i,""),n},dP=function(t,e,r,n,i,o,s,a){var l,c,u=o*s;try{e:for(var d=Oe(t.keys()),p=d.next();!p.done;p=d.next()){var f=p.value;if(f===pr){var m=i[u-1];m<=r&&n.set(a,[t.get(f),m])}else{for(var h=o,y=0;y<f.length;++y,++h){for(var g=f[y],_=s*h,b=_-s,E=i[_],I=Math.max(0,h-r-1),P=Math.min(s-1,h+r),M=I;M<P;++M){var V=g!==e[M],R=i[b+M]+ +V,L=i[b+M+1]+1,G=i[_+M]+1,H=i[_+M+1]=Math.min(R,L,G);H<E&&(E=H)}if(E>r)continue e}dP(t.get(f),e,r,n,i,h,s,a+f)}}}catch(W){l={error:W}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}},yb=function(){function t(e,r){e===void 0&&(e=new Map),r===void 0&&(r=""),this._size=void 0,this._tree=e,this._prefix=r}return t.prototype.atPrefix=function(e){var r,n;if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");var i=jt(Nh(this._tree,e.slice(this._prefix.length)),2),o=i[0],s=i[1];if(o===void 0){var a=jt(Sb(s),2),l=a[0],c=a[1];try{for(var u=Oe(l.keys()),d=u.next();!d.done;d=u.next()){var p=d.value;if(p!==pr&&p.startsWith(c)){var f=new Map;return f.set(p.slice(c.length),l.get(p)),new t(f,e)}}}catch(m){r={error:m}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}return new t(o,e)},t.prototype.clear=function(){this._size=void 0,this._tree.clear()},t.prototype.delete=function(e){return this._size=void 0,dL(this._tree,e)},t.prototype.entries=function(){return new gb(this,cL)},t.prototype.forEach=function(e){var r,n;try{for(var i=Oe(this),o=i.next();!o.done;o=i.next()){var s=jt(o.value,2),a=s[0],l=s[1];e(a,l,this)}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.fuzzyGet=function(e,r){return uL(this._tree,e,r)},t.prototype.get=function(e){var r=xb(this._tree,e);return r!==void 0?r.get(pr):void 0},t.prototype.has=function(e){var r=xb(this._tree,e);return r!==void 0&&r.has(pr)},t.prototype.keys=function(){return new gb(this,cP)},t.prototype.set=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=vb(this._tree,e);return n.set(pr,r),this},Object.defineProperty(t.prototype,"size",{get:function(){if(this._size)return this._size;this._size=0;for(var e=this.entries();!e.next().done;)this._size+=1;return this._size},enumerable:!1,configurable:!0}),t.prototype.update=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=vb(this._tree,e);return n.set(pr,r(n.get(pr))),this},t.prototype.fetch=function(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;var n=vb(this._tree,e),i=n.get(pr);return i===void 0&&n.set(pr,i=r()),i},t.prototype.values=function(){return new gb(this,uP)},t.prototype[Symbol.iterator]=function(){return this.entries()},t.from=function(e){var r,n,i=new t;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=jt(s.value,2),l=a[0],c=a[1];i.set(l,c)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},t.fromObject=function(e){return t.from(Object.entries(e))},t}(),Nh=function(t,e,r){var n,i;if(r===void 0&&(r=[]),e.length===0||t==null)return[t,r];try{for(var o=Oe(t.keys()),s=o.next();!s.done;s=o.next()){var a=s.value;if(a!==pr&&e.startsWith(a))return r.push([t,a]),Nh(t.get(a),e.slice(a.length),r)}}catch(l){n={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return r.push([t,e]),Nh(void 0,"",r)},xb=function(t,e){var r,n;if(e.length===0||t==null)return t;try{for(var i=Oe(t.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;if(s!==pr&&e.startsWith(s))return xb(t.get(s),e.slice(s.length))}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},vb=function(t,e){var r,n,i=e.length;e:for(var o=0;t&&o<i;){try{for(var s=(r=void 0,Oe(t.keys())),a=s.next();!a.done;a=s.next()){var l=a.value;if(l!==pr&&e[o]===l[0]){for(var c=Math.min(i-o,l.length),u=1;u<c&&e[o+u]===l[u];)++u;var d=t.get(l);if(u===l.length)t=d;else{var p=new Map;p.set(l.slice(u),d),t.set(e.slice(o,o+u),p),t.delete(l),t=p}o+=u;continue e}}}catch(m){r={error:m}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}var f=new Map;return t.set(e.slice(o),f),f}return t},dL=function(t,e){var r=jt(Nh(t,e),2),n=r[0],i=r[1];if(n!==void 0){if(n.delete(pr),n.size===0)fP(i);else if(n.size===1){var o=jt(n.entries().next().value,2),s=o[0],a=o[1];pP(i,s,a)}}},fP=function(t){if(t.length!==0){var e=jt(Sb(t),2),r=e[0],n=e[1];if(r.delete(n),r.size===0)fP(t.slice(0,-1));else if(r.size===1){var i=jt(r.entries().next().value,2),o=i[0],s=i[1];o!==pr&&pP(t.slice(0,-1),o,s)}}},pP=function(t,e,r){if(t.length!==0){var n=jt(Sb(t),2),i=n[0],o=n[1];i.set(o+e,r),i.delete(o)}},Sb=function(t){return t[t.length-1]},Zd,Ib="or",mP="and",fL="and_not",hP=function(){function t(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');var r=e.autoVacuum==null||e.autoVacuum===!0?wb:e.autoVacuum;this._options=gt(gt(gt({},bb),e),{autoVacuum:r,searchOptions:gt(gt({},oP),e.searchOptions||{}),autoSuggestOptions:gt(gt({},yL),e.autoSuggestOptions||{})}),this._index=new yb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=kb,this.addFields(this._options.fields)}return t.prototype.add=function(e){var r,n,i,o,s,a,l=this._options,c=l.extractField,u=l.tokenize,d=l.processTerm,p=l.fields,f=l.idField,m=c(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));if(this._idToShortId.has(m))throw new Error("MiniSearch: duplicate ID ".concat(m));var h=this.addDocumentId(m);this.saveStoredFields(h,e);try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=c(e,_);if(b!=null){var E=u(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.addFieldLength(h,I,this._documentCount-1,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=d(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.addTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.addTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}},t.prototype.addAll=function(e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.add(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.addAllAsync=function(e,r){var n=this;r===void 0&&(r={});var i=r.chunkSize,o=i===void 0?10:i,s={chunk:[],promise:Promise.resolve()},a=e.reduce(function(u,d,p){var f=u.chunk,m=u.promise;return f.push(d),(p+1)%o===0?{chunk:[],promise:m.then(function(){return new Promise(function(h){return setTimeout(h,0)})}).then(function(){return n.addAll(f)})}:{chunk:f,promise:m}},s),l=a.chunk,c=a.promise;return c.then(function(){return n.addAll(l)})},t.prototype.remove=function(e){var r,n,i,o,s,a,l=this._options,c=l.tokenize,u=l.processTerm,d=l.extractField,p=l.fields,f=l.idField,m=d(e,f);if(m==null)throw new Error('MiniSearch: document does not have ID field "'.concat(f,'"'));var h=this._idToShortId.get(m);if(h==null)throw new Error("MiniSearch: cannot remove document with ID ".concat(m,": it is not in the index"));try{for(var y=Oe(p),g=y.next();!g.done;g=y.next()){var _=g.value,b=d(e,_);if(b!=null){var E=c(b.toString(),_),I=this._fieldIds[_],P=new Set(E).size;this.removeFieldLength(h,I,this._documentCount,P);try{for(var M=(i=void 0,Oe(E)),V=M.next();!V.done;V=M.next()){var R=V.value,L=u(R,_);if(Array.isArray(L))try{for(var G=(s=void 0,Oe(L)),H=G.next();!H.done;H=G.next()){var W=H.value;this.removeTerm(I,h,W)}}catch(Y){s={error:Y}}finally{try{H&&!H.done&&(a=G.return)&&a.call(G)}finally{if(s)throw s.error}}else L&&this.removeTerm(I,h,L)}}catch(Y){i={error:Y}}finally{try{V&&!V.done&&(o=M.return)&&o.call(M)}finally{if(i)throw i.error}}}}}catch(Y){r={error:Y}}finally{try{g&&!g.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}this._storedFields.delete(h),this._documentIds.delete(h),this._idToShortId.delete(m),this._fieldLength.delete(h),this._documentCount-=1},t.prototype.removeAll=function(e){var r,n;if(e)try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;this.remove(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new yb,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}},t.prototype.discard=function(e){var r=this,n=this._idToShortId.get(e);if(n==null)throw new Error("MiniSearch: cannot discard document with ID ".concat(e,": it is not in the index"));this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach(function(i,o){r.removeFieldLength(n,o,r._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()},t.prototype.maybeAutoVacuum=function(){if(this._options.autoVacuum!==!1){var e=this._options.autoVacuum,r=e.minDirtFactor,n=e.minDirtCount,i=e.batchSize,o=e.batchWait;this.conditionalVacuum({batchSize:i,batchWait:o},{minDirtCount:n,minDirtFactor:r})}},t.prototype.discardAll=function(e){var r,n,i=this._options.autoVacuum;try{this._options.autoVacuum=!1;try{for(var o=Oe(e),s=o.next();!s.done;s=o.next()){var a=s.value;this.discard(a)}}catch(l){r={error:l}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}}finally{this._options.autoVacuum=i}this.maybeAutoVacuum()},t.prototype.replace=function(e){var r=this._options,n=r.idField,i=r.extractField,o=i(e,n);this.discard(o),this.add(e)},t.prototype.vacuum=function(e){return e===void 0&&(e={}),this.conditionalVacuum(e)},t.prototype.conditionalVacuum=function(e,r){var n=this;return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(function(){var i=n._enqueuedVacuumConditions;return n._enqueuedVacuumConditions=kb,n.performVacuuming(e,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)},t.prototype.performVacuuming=function(e,r){return aL(this,void 0,void 0,function(){var n,i,o,s,a,l,c,u,d,p,f,m,h,y,g,_,b,E,I,P,M,V,R,L,G;return lL(this,function(H){switch(H.label){case 0:if(n=this._dirtCount,!this.vacuumConditionsMet(r))return[3,10];i=e.batchSize||$b.batchSize,o=e.batchWait||$b.batchWait,s=1,H.label=1;case 1:H.trys.push([1,7,8,9]),a=Oe(this._index),l=a.next(),H.label=2;case 2:if(l.done)return[3,6];c=jt(l.value,2),u=c[0],d=c[1];try{for(p=(V=void 0,Oe(d)),f=p.next();!f.done;f=p.next()){m=jt(f.value,2),h=m[0],y=m[1];try{for(g=(L=void 0,Oe(y)),_=g.next();!_.done;_=g.next())b=jt(_.value,1),E=b[0],!this._documentIds.has(E)&&(y.size<=1?d.delete(h):y.delete(E))}catch(W){L={error:W}}finally{try{_&&!_.done&&(G=g.return)&&G.call(g)}finally{if(L)throw L.error}}}}catch(W){V={error:W}}finally{try{f&&!f.done&&(R=p.return)&&R.call(p)}finally{if(V)throw V.error}}return this._index.get(u).size===0&&this._index.delete(u),s%i!==0?[3,4]:[4,new Promise(function(W){return setTimeout(W,o)})];case 3:H.sent(),H.label=4;case 4:s+=1,H.label=5;case 5:return l=a.next(),[3,2];case 6:return[3,9];case 7:return I=H.sent(),P={error:I},[3,9];case 8:try{l&&!l.done&&(M=a.return)&&M.call(a)}finally{if(P)throw P.error}return[7];case 9:this._dirtCount-=n,H.label=10;case 10:return[4,null];case 11:return H.sent(),this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null,[2]}})})},t.prototype.vacuumConditionsMet=function(e){if(e==null)return!0;var r=e.minDirtCount,n=e.minDirtFactor;return r=r||wb.minDirtCount,n=n||wb.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n},Object.defineProperty(t.prototype,"isVacuuming",{get:function(){return this._currentVacuum!=null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtCount",{get:function(){return this._dirtCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dirtFactor",{get:function(){return this._dirtCount/(1+this._documentCount+this._dirtCount)},enumerable:!1,configurable:!0}),t.prototype.has=function(e){return this._idToShortId.has(e)},t.prototype.getStoredFields=function(e){var r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)},t.prototype.search=function(e,r){var n,i;r===void 0&&(r={});var o=this.executeQuery(e,r),s=[];try{for(var a=Oe(o),l=a.next();!l.done;l=a.next()){var c=jt(l.value,2),u=c[0],d=c[1],p=d.score,f=d.terms,m=d.match,h=f.length||1,y={id:this._documentIds.get(u),score:p*h,terms:Object.keys(m),queryTerms:f,match:m};Object.assign(y,this._storedFields.get(u)),(r.filter==null||r.filter(y))&&s.push(y)}}catch(g){n={error:g}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return e===t.wildcard&&r.boostDocument==null&&this._options.searchOptions.boostDocument==null||s.sort(aP),s},t.prototype.autoSuggest=function(e,r){var n,i,o,s;r===void 0&&(r={}),r=gt(gt({},this._options.autoSuggestOptions),r);var a=new Map;try{for(var l=Oe(this.search(e,r)),c=l.next();!c.done;c=l.next()){var u=c.value,d=u.score,p=u.terms,f=p.join(" "),m=a.get(f);m!=null?(m.score+=d,m.count+=1):a.set(f,{score:d,terms:p,count:1})}}catch(I){n={error:I}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}var h=[];try{for(var y=Oe(a),g=y.next();!g.done;g=y.next()){var _=jt(g.value,2),m=_[0],b=_[1],d=b.score,p=b.terms,E=b.count;h.push({suggestion:m,terms:p,score:d/E})}}catch(I){o={error:I}}finally{try{g&&!g.done&&(s=y.return)&&s.call(y)}finally{if(o)throw o.error}}return h.sort(aP),h},Object.defineProperty(t.prototype,"documentCount",{get:function(){return this._documentCount},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"termCount",{get:function(){return this._index.size},enumerable:!1,configurable:!0}),t.loadJSON=function(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),r)},t.getDefault=function(e){if(bb.hasOwnProperty(e))return _b(bb,e);throw new Error('MiniSearch: unknown option "'.concat(e,'"'))},t.loadJS=function(e,r){var n,i,o,s,a,l,c=e.index,u=e.documentCount,d=e.nextId,p=e.documentIds,f=e.fieldIds,m=e.fieldLength,h=e.averageFieldLength,y=e.storedFields,g=e.dirtCount,_=e.serializationVersion;if(_!==1&&_!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");var b=new t(r);b._documentCount=u,b._nextId=d,b._documentIds=zh(p),b._idToShortId=new Map,b._fieldIds=f,b._fieldLength=zh(m),b._avgFieldLength=h,b._storedFields=zh(y),b._dirtCount=g||0,b._index=new yb;try{for(var E=Oe(b._documentIds),I=E.next();!I.done;I=E.next()){var P=jt(I.value,2),M=P[0],V=P[1];b._idToShortId.set(V,M)}}catch(Pt){n={error:Pt}}finally{try{I&&!I.done&&(i=E.return)&&i.call(E)}finally{if(n)throw n.error}}try{for(var R=Oe(c),L=R.next();!L.done;L=R.next()){var G=jt(L.value,2),H=G[0],W=G[1],Y=new Map;try{for(var ie=(a=void 0,Oe(Object.keys(W))),Fe=ie.next();!Fe.done;Fe=ie.next()){var it=Fe.value,Ot=W[it];_===1&&(Ot=Ot.ds),Y.set(parseInt(it,10),zh(Ot))}}catch(Pt){a={error:Pt}}finally{try{Fe&&!Fe.done&&(l=ie.return)&&l.call(ie)}finally{if(a)throw a.error}}b._index.set(H,Y)}}catch(Pt){o={error:Pt}}finally{try{L&&!L.done&&(s=R.return)&&s.call(R)}finally{if(o)throw o.error}}return b},t.prototype.executeQuery=function(e,r){var n=this;if(r===void 0&&(r={}),e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){var i=gt(gt(gt({},r),e),{queries:void 0}),o=e.queries.map(function(y){return n.executeQuery(y,i)});return this.combineResults(o,i.combineWith)}var s=this._options,a=s.tokenize,l=s.processTerm,c=s.searchOptions,u=gt(gt({tokenize:a,processTerm:l},c),r),d=u.tokenize,p=u.processTerm,f=d(e).flatMap(function(y){return p(y)}).filter(function(y){return!!y}),m=f.map(gL(u)),h=m.map(function(y){return n.executeQuerySpec(y,u)});return this.combineResults(h,u.combineWith)},t.prototype.executeQuerySpec=function(e,r){var n,i,o,s,a=gt(gt({},this._options.searchOptions),r),l=(a.fields||this._options.fields).reduce(function(it,Ot){var Pt;return gt(gt({},it),(Pt={},Pt[Ot]=_b(a.boost,Ot)||1,Pt))},{}),c=a.boostDocument,u=a.weights,d=a.maxFuzzy,p=a.bm25,f=gt(gt({},oP.weights),u),m=f.fuzzy,h=f.prefix,y=this._index.get(e.term),g=this.termResults(e.term,e.term,1,y,l,c,p),_,b;if(e.prefix&&(_=this._index.atPrefix(e.term)),e.fuzzy){var E=e.fuzzy===!0?.2:e.fuzzy,I=E<1?Math.min(d,Math.round(e.term.length*E)):E;I&&(b=this._index.fuzzyGet(e.term,I))}if(_)try{for(var P=Oe(_),M=P.next();!M.done;M=P.next()){var V=jt(M.value,2),R=V[0],L=V[1],G=R.length-e.term.length;if(G){b?.delete(R);var H=h*R.length/(R.length+.3*G);this.termResults(e.term,R,H,L,l,c,p,g)}}}catch(it){n={error:it}}finally{try{M&&!M.done&&(i=P.return)&&i.call(P)}finally{if(n)throw n.error}}if(b)try{for(var W=Oe(b.keys()),Y=W.next();!Y.done;Y=W.next()){var R=Y.value,ie=jt(b.get(R),2),Fe=ie[0],G=ie[1];if(G){var H=m*R.length/(R.length+G);this.termResults(e.term,R,H,Fe,l,c,p,g)}}}catch(it){o={error:it}}finally{try{Y&&!Y.done&&(s=W.return)&&s.call(W)}finally{if(o)throw o.error}}return g},t.prototype.executeWildcardQuery=function(e){var r,n,i=new Map,o=gt(gt({},this._options.searchOptions),e);try{for(var s=Oe(this._documentIds),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d=o.boostDocument?o.boostDocument(u,"",this._storedFields.get(c)):1;i.set(c,{score:d,terms:[],match:{}})}}catch(p){r={error:p}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i},t.prototype.combineResults=function(e,r){if(r===void 0&&(r=Ib),e.length===0)return new Map;var n=r.toLowerCase();return e.reduce(pL[n])||new Map},t.prototype.toJSON=function(){var e,r,n,i,o=[];try{for(var s=Oe(this._index),a=s.next();!a.done;a=s.next()){var l=jt(a.value,2),c=l[0],u=l[1],d={};try{for(var p=(n=void 0,Oe(u)),f=p.next();!f.done;f=p.next()){var m=jt(f.value,2),h=m[0],y=m[1];d[h]=Object.fromEntries(y)}}catch(g){n={error:g}}finally{try{f&&!f.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}o.push([c,d])}}catch(g){e={error:g}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:o,serializationVersion:2}},t.prototype.termResults=function(e,r,n,i,o,s,a,l){var c,u,d,p,f;if(l===void 0&&(l=new Map),i==null)return l;try{for(var m=Oe(Object.keys(o)),h=m.next();!h.done;h=m.next()){var y=h.value,g=o[y],_=this._fieldIds[y],b=i.get(_);if(b!=null){var E=b.size,I=this._avgFieldLength[_];try{for(var P=(d=void 0,Oe(b.keys())),M=P.next();!M.done;M=P.next()){var V=M.value;if(!this._documentIds.has(V)){this.removeTerm(_,V,r),E-=1;continue}var R=s?s(this._documentIds.get(V),r,this._storedFields.get(V)):1;if(R){var L=b.get(V),G=this._fieldLength.get(V)[_],H=hL(L,E,this._documentCount,G,I,a),W=n*g*R*H,Y=l.get(V);if(Y){Y.score+=W,vL(Y.terms,e);var ie=_b(Y.match,r);ie?ie.push(y):Y.match[r]=[y]}else l.set(V,{score:W,terms:[e],match:(f={},f[r]=[y],f)})}}}catch(Fe){d={error:Fe}}finally{try{M&&!M.done&&(p=P.return)&&p.call(P)}finally{if(d)throw d.error}}}}}catch(Fe){c={error:Fe}}finally{try{h&&!h.done&&(u=m.return)&&u.call(m)}finally{if(c)throw c.error}}return l},t.prototype.addTerm=function(e,r,n){var i=this._index.fetch(n,lP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{var s=o.get(r);o.set(r,(s||0)+1)}},t.prototype.removeTerm=function(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}var i=this._index.fetch(n,lP),o=i.get(e);o==null||o.get(r)==null?this.warnDocumentChanged(r,e,n):o.get(r)<=1?o.size<=1?i.delete(e):o.delete(r):o.set(r,o.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)},t.prototype.warnDocumentChanged=function(e,r,n){var i,o;try{for(var s=Oe(Object.keys(this._fieldIds)),a=s.next();!a.done;a=s.next()){var l=a.value;if(this._fieldIds[l]===r){this._options.logger("warn","MiniSearch: document with ID ".concat(this._documentIds.get(e),' has changed before removal: term "').concat(n,'" was not present in field "').concat(l,'". Removing a document after it has changed can corrupt the index!'),"version_conflict");return}}}catch(c){i={error:c}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}},t.prototype.addDocumentId=function(e){var r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r},t.prototype.addFields=function(e){for(var r=0;r<e.length;r++)this._fieldIds[e[r]]=r},t.prototype.addFieldLength=function(e,r,n,i){var o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;var s=this._avgFieldLength[r]||0,a=s*n+i;this._avgFieldLength[r]=a/(n+1)},t.prototype.removeFieldLength=function(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}var o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)},t.prototype.saveStoredFields=function(e,r){var n,i,o=this._options,s=o.storeFields,a=o.extractField;if(!(s==null||s.length===0)){var l=this._storedFields.get(e);l==null&&this._storedFields.set(e,l={});try{for(var c=Oe(s),u=c.next();!u.done;u=c.next()){var d=u.value,p=a(r,d);p!==void 0&&(l[d]=p)}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}},t.wildcard=Symbol("*"),t}(),_b=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0},pL=(Zd={},Zd[Ib]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value,a=t.get(s);if(a==null)t.set(s,e.get(s));else{var l=e.get(s),c=l.score,u=l.terms,d=l.match;a.score=a.score+c,a.match=Object.assign(a.match,d),sP(a.terms,u)}}}catch(p){r={error:p}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Zd[mP]=function(t,e){var r,n,i=new Map;try{for(var o=Oe(e.keys()),s=o.next();!s.done;s=o.next()){var a=s.value,l=t.get(a);if(l!=null){var c=e.get(a),u=c.score,d=c.terms,p=c.match;sP(l.terms,d),i.set(a,{score:l.score+u,terms:l.terms,match:Object.assign(l.match,p)})}}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i},Zd[fL]=function(t,e){var r,n;try{for(var i=Oe(e.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;t.delete(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return t},Zd),mL={k:1.2,b:.7,d:.5},hL=function(t,e,r,n,i,o){var s=o.k,a=o.b,l=o.d,c=Math.log(1+(r-e+.5)/(e+.5));return c*(l+t*(s+1)/(t+s*(1-a+a*n/i)))},gL=function(t){return function(e,r,n){var i=typeof t.fuzzy=="function"?t.fuzzy(e,r,n):t.fuzzy||!1,o=typeof t.prefix=="function"?t.prefix(e,r,n):t.prefix===!0;return{term:e,fuzzy:i,prefix:o}}},bb={idField:"id",extractField:function(t,e){return t[e]},tokenize:function(t){return t.split(_L)},processTerm:function(t){return t.toLowerCase()},fields:void 0,searchOptions:void 0,storeFields:[],logger:function(t,e){typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},oP={combineWith:Ib,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:mL},yL={combineWith:mP,prefix:function(t,e,r){return e===r.length-1}},$b={batchSize:1e3,batchWait:10},kb={minDirtFactor:.1,minDirtCount:20},wb=gt(gt({},$b),kb),vL=function(t,e){t.includes(e)||t.push(e)},sP=function(t,e){var r,n;try{for(var i=Oe(e),o=i.next();!o.done;o=i.next()){var s=o.value;t.includes(s)||t.push(s)}}catch(a){r={error:a}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},aP=function(t,e){var r=t.score,n=e.score;return n-r},lP=function(){return new Map},zh=function(t){var e,r,n=new Map;try{for(var i=Oe(Object.keys(t)),o=i.next();!o.done;o=i.next()){var s=o.value;n.set(parseInt(s,10),t[s])}}catch(a){e={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n},_L=/[\n\r -#%-*,-/:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]+/u;var gP=t=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,r)=>{let n=await r.knowledgeBase.search(e.query),i=r;i._lastKBsearch=e.query,i._nextRequestUseKBitems=n;let o=n.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
66
+ `)||"- (none)",s=n.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
10
67
  `)||"- (none)";return`Search complete, context has been updated.
11
68
  New information found:
12
- ${s}
69
+ ${o}
13
70
 
14
71
  New tools available:
15
- ${n}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!t.url||typeof t.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(t.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${t.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!t.path||typeof t.path!="string")throw new Error("Path parameter is required and must be a string.");let i=new URL(t.path,window.location.origin).pathname;return window.location.href=i,`Changed route to: ${i}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!u?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(t,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!t.email_address||typeof t.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!t.subject||typeof t.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!t.body||typeof t.body!="string")throw new Error("Body parameter is required and must be a string.");let i=encodeURIComponent(t.email_address),o=encodeURIComponent(t.subject),s=encodeURIComponent(t.body),n=`mailto:${i}?subject=${o}&body=${s}`;try{window.location.href=n}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${t.email_address}, Subject: ${t.subject}`}}];import{Client as De}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as at}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as rt}from"@modelcontextprotocol/sdk/client/sse.js";var I={name:"@intelliweave/embedded",version:"2.0.72-beta.6",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as lt,ToolListChangedNotificationSchema as ct}from"@modelcontextprotocol/sdk/types.js";var f=new p("MCPKnowledgeClient"),te=class{constructor(t){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=t}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){f.debug("Connecting to MCP client");let t=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new De({name:I.name,version:I.version}),i=new at(new URL(this.config.baseURL));return await e.connect(i),f.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let i=new De({name:I.name,version:I.version}),o=new rt(new URL(this.config.baseURL));return await i.connect(o),f.debug("Connected with SSE mode"),i});return await this.disconnect(),this.client=t,t.onerror=e=>{f.error(`MCP client error: ${e.message}`)},t.onclose=()=>{f.debug("MCP client connection closed"),this.client=void 0},t.setNotificationHandler(lt,e=>{e.params.level=="critical"?f.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?f.error(`[Server] ${e.params.data}`):e.params.level=="error"?f.error(`[Server] ${e.params.data}`):e.params.level=="warning"?f.warn(`[Server] ${e.params.data}`):e.params.level=="info"?f.info(`[Server] ${e.params.data}`):e.params.level=="debug"?f.debug(`[Server] ${e.params.data}`):f.log(`[Server] ${e.params.data}`)}),t.setNotificationHandler(ct,e=>{f.debug("Tool list changed",e),this.fetchTools()}),f.debug("Fetching tools from MCP server..."),await this.fetchTools(),t}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let t=[],e;for(;;){let o=await this.client.listTools({cursor:e});e=o.nextCursor;for(let s of o.tools||[])t.push(s);if(!o?.tools?.length||!e)break}let i=[];for(let o of t){let s=!!(this.config.searchToolName&&o.name==this.config.searchToolName&&!this.config.searchToolVisible);i.push({id:o.name,name:o.name,content:o.description||"",type:"action",isContext:!0,parameters:o.inputSchema,action:n=>this.performToolCall(o.name,n),disabled:s})}f.debug(`Fetched ${t.length} tools from MCP server.`),this.tools=t,this.iwActions=i}async search(t){if(t==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),i=await this.performSearchCall(t);return e=e.concat(i),this.lastSearchQuery=t,this.lastSearchResults=e,f.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(t){let e=[];if(!this.config.searchToolName)return e;let i=this.tools.find(s=>s.name==this.config.searchToolName);if(!i)return f.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let o;if(i.inputSchema.required?.length==1){let s=i.inputSchema.required[0];o=await this.performToolCall(this.config.searchToolName,{[s]:t})}else if(i.inputSchema.properties&&Object.keys(i.inputSchema.properties).length==1){let s=Object.keys(i.inputSchema.properties)[0];o=await this.performToolCall(this.config.searchToolName,{[s]:t})}else o=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(o))for(let s=0;s<o.length;s++){let n=o[s];e.push({id:this.config.id+":"+this.config.searchToolName+":"+s,name:`Search result ${s+1} in ${this.config.searchToolName}`,type:"info",content:typeof n=="string"?n:JSON.stringify(n)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)});return e}async performToolCall(t,e){await this.connect(),f.debug(`Performing tool call for ${t} with params:`,e),this.stats.toolsCalled+=1;let i=await this.client.callTool({name:t,arguments:e});if(i.isError){let o=i.content?.[0]?.text||"Unknown error";throw f.error(`Error calling tool ${t}: ${o}`),new Error(`Error calling tool ${t}: ${o}`)}if(Array.isArray(i.content)&&i.content.length==1&&i.content[0].type=="text")try{return JSON.parse(i.content[0].text)}catch{}return i.content||[]}};import{v4 as dt}from"uuid";var ut=new p("Statistics"),O=[];async function y(u,t){let e={...t,event_id:dt(),event_date:new Date().toISOString(),sdk_version:I.version,conversation_id:u?.conversationID||"",api_key:u?.apiKey||"",user_id:u?.userID||""};if(O.push(e),!u||(await new Promise(o=>setTimeout(o,5e3)),O.length===0))return;let i=O.slice();O.length=0;try{let o=await fetch(u.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:i})});if(!o.ok)throw new Error(`Analytics submission failed: ${o.status} ${o.statusText}`)}catch(o){ut.warn("Failed to submit analytics event:",o),O.push(...i);return}}var N=new p("KnowledgeBase"),Te=1,ie=class u{constructor(t){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=t,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(t=>t.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>We(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(t,e){let i=t;return typeof t=="function"&&(e=t,i=`source.${Te++}`),this._sources.push({id:i,query:e}),i}removeSource(t){this._sources=this.sources.filter(e=>e.id!==t&&e.query!==t)}addEntry(t){this.manualEntries.push(t)}removeEntry(t){this.manualEntries=this.manualEntries.filter(e=>e.id!==t)}get sources(){let t=this._sources;return this.allowGlobalConfigSources&&m().knowledgeBaseSources&&(t=t.concat(m().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(t=t.concat(this._windowSources)),t=t.filter(e=>!e.disabled),t}async search(t){N.debug(`Searching knowledge base for: ${t}`);let e=Date.now(),i=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});i.query=t,i.entries=[],i.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(i),this._windowSources=i.sources):this._windowSources=[];let s=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),d=await c.query(t);return N.debug(`Source '${c.id}' took ${Date.now()-r}ms`),d||[]}catch(r){return N.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();s=s.concat(i.entries),s=s.concat(this.manualEntries),this.allowGlobalConfigSources&&m().knowledgeBase&&(s=s.concat(m().knowledgeBase)),s=s.filter(c=>c&&!c.disabled);for(let c=0;c<s.length;c++){let r=s[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let n=new pt({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});n.addAll(s);let l=n.search(t).map(c=>s.find(r=>r.id==c.id));for(let c of s)c.isContext&&(l.find(r=>r.id===c.id)||l.push(c));return this.lastResults=l,y(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),N.debug("Found results:",l),l}getCachedEntry(t){return this.lastResults.find(e=>e.id==t||e._functionID==t)}registerSourceFromURL(t,e){e||(e=`external.${Te++}`),N.debug(`Registering remote knowledge base source: ${t}`);let i=[],o=[],s=!0,n=async(l,c)=>{N.debug(`Calling remote knowledge base action: ${l.id}`);let r={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let h=await d.json();return a(h.updateItems||[]),h.response},a=l=>{for(let c of l){if(!c.id){N.warn("KB item skipped since it has no ID.",c);continue}let r=i.find(d=>d.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}i.push({...c,action:d=>n(c,d)})}};this.registerSource(e,async l=>{if(s&&o.includes(l))return i;let c={type:"search",userID:this.ai?.userID||"",query:l},r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let d=await r.json();return s=!d.noCache,o.includes(l)||o.push(l),a(d.items),i})}clone(){let t=new u(this.ai);return t._sources=this._sources,t._windowSources=this._windowSources,t.manualEntries=this.manualEntries,t.ensureInternalKnowledge(),t}registerMCPSource(t){t.id||(t.id=`external.${Te++}`);let e=new te(t);return this.registerSource(t.id,i=>e.search(i)),e}};var oe=class{constructor(t){this.ai=t}async boolean(t){let e=await this.instruct({...t,instruction:`${t.instruction}
16
-
17
- Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(t){let e=await this.instruct({...t,instruction:`${t.instruction}
72
+ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),i=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),s=`mailto:${n}?subject=${i}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];var qe;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(qe||(qe={}));var yP;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(yP||(yP={}));var te=qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mo=t=>{switch(typeof t){case"undefined":return te.undefined;case"string":return te.string;case"number":return Number.isNaN(t)?te.nan:te.number;case"boolean":return te.boolean;case"function":return te.function;case"bigint":return te.bigint;case"symbol":return te.symbol;case"object":return Array.isArray(t)?te.array:t===null?te.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?te.promise:typeof Map<"u"&&t instanceof Map?te.map:typeof Set<"u"&&t instanceof Set?te.set:typeof Date<"u"&&t instanceof Date?te.date:te.object;default:return te.unknown}};var Z=qe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var bn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,qe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bn.create=t=>new bn(t);var bL=(t,e)=>{let r;switch(t.code){case Z.invalid_type:t.received===te.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,qe.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:r=`Unrecognized key(s) in object: ${qe.joinValues(t.keys,", ")}`;break;case Z.invalid_union:r="Invalid input";break;case Z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${qe.joinValues(t.options)}`;break;case Z.invalid_enum_value:r=`Invalid enum value. Expected ${qe.joinValues(t.options)}, received '${t.received}'`;break;case Z.invalid_arguments:r="Invalid function arguments";break;case Z.invalid_return_type:r="Invalid function return type";break;case Z.invalid_date:r="Invalid date";break;case Z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:qe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Z.custom:r="Invalid input";break;case Z.invalid_intersection_types:r="Intersection results could not be merged";break;case Z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Z.not_finite:r="Number must be finite";break;default:r=e.defaultError,qe.assertNever(t)}return{message:r}},ls=bL;var wL=ls;function Fd(){return wL}var Ch=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function Q(t,e){let r=Fd(),n=Ch({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ls?void 0:ls].filter(i=>!!i)});t.common.issues.push(n)}var Ir=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return ye;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return ye;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},ye=Object.freeze({status:"aborted"}),kc=t=>({status:"dirty",value:t}),Ur=t=>({status:"valid",value:t}),Eb=t=>t.status==="aborted",Pb=t=>t.status==="dirty",ga=t=>t.status==="valid",Vd=t=>typeof Promise<"u"&&t instanceof Promise;var oe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(oe||(oe={}));var Rn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},vP=(t,e)=>{if(ga(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bn(t.common.issues);return this._error=r,this._error}}};function Ee(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:i}}var Re=class{get description(){return this._def.description}_getType(e){return mo(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:mo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ir,ctx:{common:e.parent.common,data:e.data,parsedType:mo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Vd(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)},i=this._parseSync({data:e,path:n.path,parent:n});return vP(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ga(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ga(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mo(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Vd(i)?i:Promise.resolve(i));return vP(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:Z.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ti({schema:this,typeName:ge.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ei.create(this,this._def)}nullable(){return yo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return us.create(this)}promise(){return ya.create(this,this._def)}or(e){return Tc.create([this,e],this._def)}and(e){return Ac.create(this,e,this._def)}transform(e){return new ti({...Ee(this._def),schema:this,typeName:ge.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Rc({...Ee(this._def),innerType:this,defaultValue:r,typeName:ge.ZodDefault})}brand(){return new Oh({typeName:ge.ZodBranded,type:this,...Ee(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Mc({...Ee(this._def),innerType:this,catchValue:r,typeName:ge.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Rh.create(this,e)}readonly(){return jc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xL=/^c[^\s-]{8,}$/i,$L=/^[0-9a-z]+$/,kL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,SL=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,IL=/^[a-z0-9_-]{21}$/i,EL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,TL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,AL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tb,zL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,NL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,CL=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,OL=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,RL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ML=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_P="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jL=new RegExp(`^${_P}$`);function bP(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function DL(t){return new RegExp(`^${bP(t)}$`)}function LL(t){let e=`${_P}T${bP(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function UL(t,e){return!!((e==="v4"||!e)&&zL.test(t)||(e==="v6"||!e)&&CL.test(t))}function ZL(t,e){if(!EL.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function FL(t,e){return!!((e==="v4"||!e)&&NL.test(t)||(e==="v6"||!e)&&OL.test(t))}var Ic=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==te.string){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.string,received:o.parsedType}),ye}let n=new Ir,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?Q(i,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Q(i,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")TL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"email",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Tb||(Tb=new RegExp(AL,"u")),Tb.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"emoji",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")SL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"uuid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")IL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"nanoid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")xL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cuid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")$L.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cuid2",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")kL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"ulid",code:Z.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),Q(i,{validation:"url",code:Z.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"regex",code:Z.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?LL(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?jL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?DL(o).test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?PL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"duration",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?UL(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"ip",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?ZL(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"jwt",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?FL(e.data,o.version)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"cidr",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?RL.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"base64",code:Z.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?ML.test(e.data)||(i=this._getOrReturnCtx(e,i),Q(i,{validation:"base64url",code:Z.invalid_string,message:o.message}),n.dirty()):qe.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:Z.invalid_string,...oe.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...oe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...oe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...oe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...oe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...oe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...oe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...oe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...oe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...oe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...oe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...oe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...oe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...oe.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...oe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...oe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...oe.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...oe.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...oe.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...oe.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...oe.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...oe.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...oe.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...oe.errToObj(r)})}nonempty(e){return this.min(1,oe.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ic.create=t=>new Ic({checks:[],typeName:ge.ZodString,coerce:t?.coerce??!1,...Ee(t)});function VL(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var qd=class t extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==te.number){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.number,received:o.parsedType}),ye}let n,i=new Ir;for(let o of this._def.checks)o.kind==="int"?qe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?VL(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.not_finite,message:o.message}),i.dirty()):qe.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,oe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,oe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,oe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,oe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:oe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:oe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:oe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:oe.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:oe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:oe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:oe.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&qe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};qd.create=t=>new qd({checks:[],typeName:ge.ZodNumber,coerce:t?.coerce||!1,...Ee(t)});var Wd=class t extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==te.bigint)return this._getInvalidInput(e);let n,i=new Ir;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):qe.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Q(r,{code:Z.invalid_type,expected:te.bigint,received:r.parsedType}),ye}gte(e,r){return this.setLimit("min",e,!0,oe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,oe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,oe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,oe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:oe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:oe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:oe.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Wd.create=t=>new Wd({checks:[],typeName:ge.ZodBigInt,coerce:t?.coerce??!1,...Ee(t)});var Bd=class extends Re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==te.boolean){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.boolean,received:n.parsedType}),ye}return Ur(e.data)}};Bd.create=t=>new Bd({typeName:ge.ZodBoolean,coerce:t?.coerce||!1,...Ee(t)});var Gd=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==te.date){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_type,expected:te.date,received:o.parsedType}),ye}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return Q(o,{code:Z.invalid_date}),ye}let n=new Ir,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:Z.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):qe.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:oe.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:oe.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Gd.create=t=>new Gd({checks:[],coerce:t?.coerce||!1,typeName:ge.ZodDate,...Ee(t)});var Hd=class extends Re{_parse(e){if(this._getType(e)!==te.symbol){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.symbol,received:n.parsedType}),ye}return Ur(e.data)}};Hd.create=t=>new Hd({typeName:ge.ZodSymbol,...Ee(t)});var Ec=class extends Re{_parse(e){if(this._getType(e)!==te.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.undefined,received:n.parsedType}),ye}return Ur(e.data)}};Ec.create=t=>new Ec({typeName:ge.ZodUndefined,...Ee(t)});var Pc=class extends Re{_parse(e){if(this._getType(e)!==te.null){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.null,received:n.parsedType}),ye}return Ur(e.data)}};Pc.create=t=>new Pc({typeName:ge.ZodNull,...Ee(t)});var Xd=class extends Re{constructor(){super(...arguments),this._any=!0}_parse(e){return Ur(e.data)}};Xd.create=t=>new Xd({typeName:ge.ZodAny,...Ee(t)});var cs=class extends Re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ur(e.data)}};cs.create=t=>new cs({typeName:ge.ZodUnknown,...Ee(t)});var Pi=class extends Re{_parse(e){let r=this._getOrReturnCtx(e);return Q(r,{code:Z.invalid_type,expected:te.never,received:r.parsedType}),ye}};Pi.create=t=>new Pi({typeName:ge.ZodNever,...Ee(t)});var Kd=class extends Re{_parse(e){if(this._getType(e)!==te.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.void,received:n.parsedType}),ye}return Ur(e.data)}};Kd.create=t=>new Kd({typeName:ge.ZodVoid,...Ee(t)});var us=class t extends Re{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==te.array)return Q(r,{code:Z.invalid_type,expected:te.array,received:r.parsedType}),ye;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Q(r,{code:s?Z.too_big:Z.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Q(r,{code:Z.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Q(r,{code:Z.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Rn(r,s,r.path,a)))).then(s=>Ir.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Rn(r,s,r.path,a)));return Ir.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:oe.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:oe.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:oe.toString(r)}})}nonempty(e){return this.min(1,e)}};us.create=(t,e)=>new us({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ge.ZodArray,...Ee(e)});function Sc(t){if(t instanceof wn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ei.create(Sc(n))}return new wn({...t._def,shape:()=>e})}else return t instanceof us?new us({...t._def,type:Sc(t.element)}):t instanceof ei?ei.create(Sc(t.unwrap())):t instanceof yo?yo.create(Sc(t.unwrap())):t instanceof go?go.create(t.items.map(e=>Sc(e))):t}var wn=class t extends Re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=qe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==te.object){let c=this._getOrReturnCtx(e);return Q(c,{code:Z.invalid_type,expected:te.object,received:c.parsedType}),ye}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Pi&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let u=o[c],d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Rn(i,d,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Pi){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(c==="strict")a.length>0&&(Q(i,{code:Z.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Rn(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,p=await u.value;c.push({key:d,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Ir.mergeObjectSync(n,c)):Ir.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return oe.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:oe.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ge.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of qe.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of qe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Sc(this)}partial(e){let r={};for(let n of qe.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of qe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ei;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return wP(qe.objectKeys(this.shape))}};wn.create=(t,e)=>new wn({shape:()=>t,unknownKeys:"strip",catchall:Pi.create(),typeName:ge.ZodObject,...Ee(e)});wn.strictCreate=(t,e)=>new wn({shape:()=>t,unknownKeys:"strict",catchall:Pi.create(),typeName:ge.ZodObject,...Ee(e)});wn.lazycreate=(t,e)=>new wn({shape:t,unknownKeys:"strip",catchall:Pi.create(),typeName:ge.ZodObject,...Ee(e)});var Tc=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new bn(a.ctx.common.issues));return Q(r,{code:Z.invalid_union,unionErrors:s}),ye}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new bn(l));return Q(r,{code:Z.invalid_union,unionErrors:a}),ye}}get options(){return this._def.options}};Tc.create=(t,e)=>new Tc({options:t,typeName:ge.ZodUnion,...Ee(e)});var ho=t=>t instanceof zc?ho(t.schema):t instanceof ti?ho(t.innerType()):t instanceof Nc?[t.value]:t instanceof Cc?t.options:t instanceof Oc?qe.objectValues(t.enum):t instanceof Rc?ho(t._def.innerType):t instanceof Ec?[void 0]:t instanceof Pc?[null]:t instanceof ei?[void 0,...ho(t.unwrap())]:t instanceof yo?[null,...ho(t.unwrap())]:t instanceof Oh||t instanceof jc?ho(t.unwrap()):t instanceof Mc?ho(t._def.innerType):[],Ab=class t extends Re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.object)return Q(r,{code:Z.invalid_type,expected:te.object,received:r.parsedType}),ye;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Q(r,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=ho(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:ge.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ee(n)})}};function zb(t,e){let r=mo(t),n=mo(e);if(t===e)return{valid:!0,data:t};if(r===te.object&&n===te.object){let i=qe.objectKeys(e),o=qe.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let l=zb(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(r===te.array&&n===te.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],l=zb(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return r===te.date&&n===te.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ac=class extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Eb(o)||Eb(s))return ye;let a=zb(o.value,s.value);return a.valid?((Pb(o)||Pb(s))&&r.dirty(),{status:r.value,value:a.data}):(Q(n,{code:Z.invalid_intersection_types}),ye)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ac.create=(t,e,r)=>new Ac({left:t,right:e,typeName:ge.ZodIntersection,...Ee(r)});var go=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.array)return Q(n,{code:Z.invalid_type,expected:te.array,received:n.parsedType}),ye;if(n.data.length<this._def.items.length)return Q(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&n.data.length>this._def.items.length&&(Q(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Rn(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Ir.mergeArray(r,s)):Ir.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};go.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new go({items:t,typeName:ge.ZodTuple,rest:null,...Ee(e)})};var Nb=class t extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.object)return Q(n,{code:Z.invalid_type,expected:te.object,received:n.parsedType}),ye;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Rn(n,a,n.path,a)),value:s._parse(new Rn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ir.mergeObjectAsync(r,i):Ir.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Re?new t({keyType:e,valueType:r,typeName:ge.ZodRecord,...Ee(n)}):new t({keyType:Ic.create(),valueType:e,typeName:ge.ZodRecord,...Ee(r)})}},Jd=class extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.map)return Q(n,{code:Z.invalid_type,expected:te.map,received:n.parsedType}),ye;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,l],c)=>({key:i._parse(new Rn(n,a,n.path,[c,"key"])),value:o._parse(new Rn(n,l,n.path,[c,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return ye;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return ye;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(c.value,u.value)}return{status:r.value,value:a}}}};Jd.create=(t,e,r)=>new Jd({valueType:e,keyType:t,typeName:ge.ZodMap,...Ee(r)});var Yd=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==te.set)return Q(n,{code:Z.invalid_type,expected:te.set,received:n.parsedType}),ye;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Q(n,{code:Z.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Q(n,{code:Z.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return ye;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}let a=[...n.data.values()].map((l,c)=>o._parse(new Rn(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:oe.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:oe.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Yd.create=(t,e)=>new Yd({valueType:t,minSize:null,maxSize:null,typeName:ge.ZodSet,...Ee(e)});var Cb=class t extends Re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.function)return Q(r,{code:Z.invalid_type,expected:te.function,received:r.parsedType}),ye;function n(a,l){return Ch({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fd(),ls].filter(c=>!!c),issueData:{code:Z.invalid_arguments,argumentsError:l}})}function i(a,l){return Ch({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Fd(),ls].filter(c=>!!c),issueData:{code:Z.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof ya){let a=this;return Ur(async function(...l){let c=new bn([]),u=await a._def.args.parseAsync(l,o).catch(f=>{throw c.addIssue(n(l,f)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw c.addIssue(i(d,f)),c})})}else{let a=this;return Ur(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new bn([n(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new bn([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:go.create(e).rest(cs.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||go.create([]).rest(cs.create()),returns:r||cs.create(),typeName:ge.ZodFunction,...Ee(n)})}},zc=class extends Re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};zc.create=(t,e)=>new zc({getter:t,typeName:ge.ZodLazy,...Ee(e)});var Nc=class extends Re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Q(r,{received:r.data,code:Z.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nc.create=(t,e)=>new Nc({value:t,typeName:ge.ZodLiteral,...Ee(e)});function wP(t,e){return new Cc({values:t,typeName:ge.ZodEnum,...Ee(e)})}var Cc=class t extends Re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{expected:qe.joinValues(n),received:r.parsedType,code:Z.invalid_type}),ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{received:r.data,code:Z.invalid_enum_value,options:n}),ye}return Ur(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Cc.create=wP;var Oc=class extends Re{_parse(e){let r=qe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==te.string&&n.parsedType!==te.number){let i=qe.objectValues(r);return Q(n,{expected:qe.joinValues(i),received:n.parsedType,code:Z.invalid_type}),ye}if(this._cache||(this._cache=new Set(qe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=qe.objectValues(r);return Q(n,{received:n.data,code:Z.invalid_enum_value,options:i}),ye}return Ur(e.data)}get enum(){return this._def.values}};Oc.create=(t,e)=>new Oc({values:t,typeName:ge.ZodNativeEnum,...Ee(e)});var ya=class extends Re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==te.promise&&r.common.async===!1)return Q(r,{code:Z.invalid_type,expected:te.promise,received:r.parsedType}),ye;let n=r.parsedType===te.promise?r.data:Promise.resolve(r.data);return Ur(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ya.create=(t,e)=>new ya({type:t,typeName:ge.ZodPromise,...Ee(e)});var ti=class extends Re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ge.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{Q(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return ye;let l=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return l.status==="aborted"?ye:l.status==="dirty"?kc(l.value):r.value==="dirty"?kc(l.value):l});{if(r.value==="aborted")return ye;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ye:a.status==="dirty"?kc(a.value):r.value==="dirty"?kc(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?ye:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?ye:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ga(s))return ye;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>ga(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ye);qe.assertNever(i)}};ti.create=(t,e,r)=>new ti({schema:t,typeName:ge.ZodEffects,effect:e,...Ee(r)});ti.createWithPreprocess=(t,e,r)=>new ti({schema:e,effect:{type:"preprocess",transform:t},typeName:ge.ZodEffects,...Ee(r)});var ei=class extends Re{_parse(e){return this._getType(e)===te.undefined?Ur(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ei.create=(t,e)=>new ei({innerType:t,typeName:ge.ZodOptional,...Ee(e)});var yo=class extends Re{_parse(e){return this._getType(e)===te.null?Ur(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yo.create=(t,e)=>new yo({innerType:t,typeName:ge.ZodNullable,...Ee(e)});var Rc=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===te.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Rc.create=(t,e)=>new Rc({innerType:t,typeName:ge.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ee(e)});var Mc=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Vd(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Mc.create=(t,e)=>new Mc({innerType:t,typeName:ge.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ee(e)});var Qd=class extends Re{_parse(e){if(this._getType(e)!==te.nan){let n=this._getOrReturnCtx(e);return Q(n,{code:Z.invalid_type,expected:te.nan,received:n.parsedType}),ye}return{status:"valid",value:e.data}}};Qd.create=t=>new Qd({typeName:ge.ZodNaN,...Ee(t)});var mue=Symbol("zod_brand"),Oh=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Rh=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ye:o.status==="dirty"?(r.dirty(),kc(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ye:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ge.ZodPipeline})}},jc=class extends Re{_parse(e){let r=this._def.innerType._parse(e),n=i=>(ga(i)&&(i.value=Object.freeze(i.value)),i);return Vd(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};jc.create=(t,e)=>new jc({innerType:t,typeName:ge.ZodReadonly,...Ee(e)});var hue={object:wn.lazycreate},ge;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ge||(ge={}));var gue=Ic.create,yue=qd.create,vue=Qd.create,_ue=Wd.create,bue=Bd.create,wue=Gd.create,xue=Hd.create,$ue=Ec.create,kue=Pc.create,Sue=Xd.create,Iue=cs.create,Eue=Pi.create,Pue=Kd.create,Tue=us.create,qL=wn.create,Aue=wn.strictCreate,zue=Tc.create,Nue=Ab.create,Cue=Ac.create,Oue=go.create,Rue=Nb.create,Mue=Jd.create,jue=Yd.create,Due=Cb.create,Lue=zc.create,Uue=Nc.create,Zue=Cc.create,Fue=Oc.create,Vue=ya.create,que=ti.create,Wue=ei.create,Bue=yo.create,Gue=ti.createWithPreprocess,Hue=Rh.create;var jh=Object.freeze({status:"aborted"});function C(t,e,r){function n(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=c[p].bind(a))}}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var l;let c=r?.Parent?new o:this;n(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Ob=Symbol("zod_brand"),Ti=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Dc=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},Mh={};function Er(t){return t&&Object.assign(Mh,t),Mh}var X={};Qu(X,{BIGINT_FORMAT_RANGES:()=>SP,Class:()=>Mb,NUMBER_FORMAT_RANGES:()=>Fb,aborted:()=>ms,allowsEval:()=>Lb,assert:()=>JL,assertEqual:()=>GL,assertIs:()=>XL,assertNever:()=>KL,assertNotEqual:()=>HL,assignProp:()=>ds,base64ToUint8Array:()=>EP,base64urlToUint8Array:()=>mU,cached:()=>Uc,captureStackTrace:()=>Uh,cleanEnum:()=>pU,cleanRegex:()=>rf,clone:()=>Yr,cloneDef:()=>QL,createTransparentProxy:()=>oU,defineLazy:()=>ut,esc:()=>Lh,escapeRegex:()=>Ai,extend:()=>lU,finalizeIssue:()=>ri,floatSafeRemainder:()=>jb,getElementAtPath:()=>eU,getEnumValues:()=>Dh,getLengthableOrigin:()=>nf,getParsedType:()=>iU,getSizableOrigin:()=>IP,hexToUint8Array:()=>gU,isObject:()=>va,isPlainObject:()=>ps,issue:()=>Zc,joinValues:()=>ve,jsonStringifyReplacer:()=>Lc,merge:()=>uU,mergeDefs:()=>fs,normalizeParams:()=>de,nullish:()=>tf,numKeys:()=>nU,objectClone:()=>YL,omit:()=>aU,optionalKeys:()=>Zb,partial:()=>dU,pick:()=>sU,prefixIssues:()=>vo,primitiveTypes:()=>kP,promiseAllObject:()=>tU,propertyKeyTypes:()=>Ub,randomString:()=>rU,required:()=>fU,safeExtend:()=>cU,shallowClone:()=>$P,slugify:()=>Db,stringifyPrimitive:()=>_e,uint8ArrayToBase64:()=>PP,uint8ArrayToBase64url:()=>hU,uint8ArrayToHex:()=>yU,unwrapMessage:()=>ef});function GL(t){return t}function HL(t){return t}function XL(t){}function KL(t){throw new Error}function JL(t){}function Dh(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function ve(t,e="|"){return t.map(r=>_e(r)).join(e)}function Lc(t,e){return typeof e=="bigint"?e.toString():e}function Uc(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function tf(t){return t==null}function rf(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function jb(t,e){let r=(t.toString().split(".")[1]||"").length,n=e.toString(),i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){let l=n.match(/\d?e-(\d?)/);l?.[1]&&(i=Number.parseInt(l[1]))}let o=r>i?r:i,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}var xP=Symbol("evaluating");function ut(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==xP)return n===void 0&&(n=xP,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function YL(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ds(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function fs(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function QL(t){return fs(t._zod.def)}function eU(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function tU(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function rU(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Lh(t){return JSON.stringify(t)}function Db(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Uh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function va(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Lb=Uc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ps(t){if(va(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(va(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function $P(t){return ps(t)?{...t}:Array.isArray(t)?[...t]:t}function nU(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var iU=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ub=new Set(["string","number","symbol"]),kP=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ai(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function de(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function oU(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,o){return e??(e=t()),Reflect.set(e,n,i,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function _e(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Zb(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Fb={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},SP={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sU(t,e){let r=t._zod.def,n=fs(t._zod.def,{get shape(){let i={};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(i[o]=r.shape[o])}return ds(this,"shape",i),i},checks:[]});return Yr(t,n)}function aU(t,e){let r=t._zod.def,n=fs(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete i[o]}return ds(this,"shape",i),i},checks:[]});return Yr(t,n)}function lU(t,e){if(!ps(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let i=fs(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ds(this,"shape",o),o},checks:[]});return Yr(t,i)}function cU(t,e){if(!ps(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ds(this,"shape",n),n},checks:t._zod.def.checks};return Yr(t,r)}function uU(t,e){let r=fs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ds(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Yr(t,r)}function dU(t,e,r){let n=fs(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:i[s]}):i[s])}else for(let s in i)o[s]=t?new t({type:"optional",innerType:i[s]}):i[s];return ds(this,"shape",o),o},checks:[]});return Yr(e,n)}function fU(t,e,r){let n=fs(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new t({type:"nonoptional",innerType:i[s]});return ds(this,"shape",o),o},checks:[]});return Yr(e,n)}function ms(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vo(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ef(t){return typeof t=="string"?t:t?.message}function ri(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=ef(t.inst?._zod.def?.error?.(t))??ef(e?.error?.(t))??ef(r.customError?.(t))??ef(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function IP(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function nf(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function pU(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function EP(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function PP(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function mU(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return EP(e+r)}function hU(t){return PP(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gU(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function yU(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Mb=class{constructor(...e){}};var TP=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Lc,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Zh=C("$ZodError",TP),Vb=C("$ZodError",TP,{Parent:Error});function Fh(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Vh(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>n({issues:s}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)r._errors.push(e(o));else{let s=r,a=0;for(;a<o.path.length;){let l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(e(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return n(t),r}var qh=t=>(e,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ti;if(s.issues.length){let a=new(i?.Err??t)(s.issues.map(l=>ri(l,o,Er())));throw Uh(a,i?.callee),a}return s.value};var Wh=t=>async(e,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??t)(s.issues.map(l=>ri(l,o,Er())));throw Uh(a,i?.callee),a}return s.value};var of=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Ti;return o.issues.length?{success:!1,error:new(t??Zh)(o.issues.map(s=>ri(s,i,Er())))}:{success:!0,data:o.value}},Fc=of(Vb),sf=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>ri(s,i,Er())))}:{success:!0,data:o.value}},af=sf(Vb),AP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return qh(t)(e,r,i)};var zP=t=>(e,r,n)=>qh(t)(e,r,n);var NP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Wh(t)(e,r,i)};var CP=t=>async(e,r,n)=>Wh(t)(e,r,n);var OP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return of(t)(e,r,i)};var RP=t=>(e,r,n)=>of(t)(e,r,n);var MP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return sf(t)(e,r,i)};var jP=t=>async(e,r,n)=>sf(t)(e,r,n);var DP=/^[cC][^\s-]{8,}$/,LP=/^[0-9a-z]+$/,UP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ZP=/^[0-9a-vA-V]{20}$/,FP=/^[A-Za-z0-9]{27}$/,VP=/^[a-zA-Z0-9_-]{21}$/,qP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var WP=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qb=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var BP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var _U="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function GP(){return new RegExp(_U,"u")}var HP=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,XP=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var KP=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,JP=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YP=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wb=/^[A-Za-z0-9_-]*$/;var QP=/^\+(?:[0-9]){6,14}[0-9]$/,eT="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",tT=new RegExp(`^${eT}$`);function rT(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function nT(t){return new RegExp(`^${rT(t)}$`)}function iT(t){let e=rT({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${eT}T(?:${n})$`)}var oT=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},sT=/^-?\d+n?$/,aT=/^-?\d+$/,lT=/^-?\d+(?:\.\d+)?/,cT=/^(?:true|false)$/i,uT=/^null$/i;var dT=/^[^A-Z]*$/,fT=/^[^a-z]*$/;var or=C("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),pT={number:"number",bigint:"bigint",object:"date"},Bb=C("$ZodCheckLessThan",(t,e)=>{or.init(t,e);let r=pT[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gb=C("$ZodCheckGreaterThan",(t,e)=>{or.init(t,e);let r=pT[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),mT=C("$ZodCheckMultipleOf",(t,e)=>{or.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):jb(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),hT=C("$ZodCheckNumberFormat",(t,e)=>{or.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,o]=Fb[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,r&&(a.pattern=aT)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}});var gT=C("$ZodCheckMaxLength",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=nf(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),yT=C("$ZodCheckMinLength",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=nf(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),vT=C("$ZodCheckLengthEquals",(t,e)=>{var r;or.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!tf(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=nf(i),a=o>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),lf=C("$ZodCheckStringFormat",(t,e)=>{var r,n;or.init(t,e),t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),_T=C("$ZodCheckRegex",(t,e)=>{lf.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),bT=C("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=dT),lf.init(t,e)}),wT=C("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=fT),lf.init(t,e)}),xT=C("$ZodCheckIncludes",(t,e)=>{or.init(t,e);let r=Ai(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),$T=C("$ZodCheckStartsWith",(t,e)=>{or.init(t,e);let r=new RegExp(`^${Ai(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),kT=C("$ZodCheckEndsWith",(t,e)=>{or.init(t,e);let r=new RegExp(`.*${Ai(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var ST=C("$ZodCheckOverwrite",(t,e)=>{or.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Bh=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
73
+ `).filter(s=>s),i=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,i.join(`
74
+ `))}};var ET={major:4,minor:1,patch:13};var st=C("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ET;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let o of i._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(s,a,l)=>{let c=ms(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,f=d._zod.check(s);if(f instanceof Promise&&l?.async===!1)throw new Ti;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=ms(s,p)))});else{if(s.issues.length===p)continue;c||(c=ms(s,p))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(ms(s))return s.aborted=!0,s;let c=i(a,n,l);if(c instanceof Promise){if(l.async===!1)throw new Ti;return c.then(u=>t._zod.parse(u,l))}return t._zod.parse(c,l)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let c=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=t._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Ti;return l.then(c=>i(c,n,a))}return i(l,n,a)}}t["~standard"]={validate:i=>{try{let o=Fc(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return af(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Vc=C("$ZodString",(t,e)=>{st.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??oT(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),yt=C("$ZodStringFormat",(t,e)=>{lf.init(t,e),Vc.init(t,e)}),Xb=C("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=WP),yt.init(t,e)}),Kb=C("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=qb(n))}else e.pattern??(e.pattern=qb());yt.init(t,e)}),Jb=C("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=BP),yt.init(t,e)}),Yb=C("$ZodURL",(t,e)=>{yt.init(t,e),t._zod.check=r=>{try{let n=r.value.trim(),i=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Qb=C("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=GP()),yt.init(t,e)}),ew=C("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=VP),yt.init(t,e)}),tw=C("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=DP),yt.init(t,e)}),rw=C("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=LP),yt.init(t,e)}),nw=C("$ZodULID",(t,e)=>{e.pattern??(e.pattern=UP),yt.init(t,e)}),iw=C("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ZP),yt.init(t,e)}),ow=C("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=FP),yt.init(t,e)}),sw=C("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=iT(e)),yt.init(t,e)}),aw=C("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=tT),yt.init(t,e)}),lw=C("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=nT(e)),yt.init(t,e)}),cw=C("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=qP),yt.init(t,e)}),uw=C("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=HP),yt.init(t,e),t._zod.bag.format="ipv4"}),dw=C("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=XP),yt.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var fw=C("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=KP),yt.init(t,e)}),pw=C("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=JP),yt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,o]=n;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function DT(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var mw=C("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=YP),yt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{DT(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function bU(t){if(!Wb.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return DT(r)}var hw=C("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Wb),yt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{bU(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),gw=C("$ZodE164",(t,e)=>{e.pattern??(e.pattern=QP),yt.init(t,e)});function wU(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}var yw=C("$ZodJWT",(t,e)=>{yt.init(t,e),t._zod.check=r=>{wU(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Xh=C("$ZodNumber",(t,e)=>{st.init(t,e),t._zod.pattern=t._zod.bag.pattern??lT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),r}}),vw=C("$ZodNumberFormat",(t,e)=>{hT.init(t,e),Xh.init(t,e)}),Kh=C("$ZodBoolean",(t,e)=>{st.init(t,e),t._zod.pattern=cT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),_w=C("$ZodBigInt",(t,e)=>{st.init(t,e),t._zod.pattern=sT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var bw=C("$ZodNull",(t,e)=>{st.init(t,e),t._zod.pattern=uT,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}}),ww=C("$ZodAny",(t,e)=>{st.init(t,e),t._zod.parse=r=>r}),xw=C("$ZodUnknown",(t,e)=>{st.init(t,e),t._zod.parse=r=>r}),$w=C("$ZodNever",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var kw=C("$ZodDate",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:t}),r}});function PT(t,e,r){t.issues.length&&e.issues.push(...vo(r,t.issues)),e.value[r]=t.value}var Sw=C("$ZodArray",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=e.element._zod.run({value:a,issues:[]},n);l instanceof Promise?o.push(l.then(c=>PT(c,r,s))):PT(l,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Hh(t,e,r,n){t.issues.length&&e.issues.push(...vo(r,t.issues)),t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function LT(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Zb(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function UT(t,e,r,n,i,o){let s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type;for(let u in e){if(a.has(u))continue;if(c==="never"){s.push(u);continue}let d=l.run({value:e[u],issues:[]},n);d instanceof Promise?t.push(d.then(p=>Hh(p,r,u,e))):Hh(d,r,u,e)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}var ZT=C("$ZodObject",(t,e)=>{if(st.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}let n=Uc(()=>LT(e));ut(t._zod,"propValues",()=>{let a=e.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let i=va,o=e.catchall,s;t._zod.parse=(a,l)=>{s??(s=n.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};let u=[],d=s.shape;for(let p of s.keys){let m=d[p]._zod.run({value:c[p],issues:[]},l);m instanceof Promise?u.push(m.then(h=>Hh(h,a,p,c))):Hh(m,a,p,c)}return o?UT(u,c,a,l,n.value,t):u.length?Promise.all(u).then(()=>a):a}}),FT=C("$ZodObjectJIT",(t,e)=>{ZT.init(t,e);let r=t._zod.parse,n=Uc(()=>LT(e)),i=p=>{let f=new Bh(["shape","payload","ctx"]),m=n.value,h=b=>{let E=Lh(b);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),g=0;for(let b of m.keys)y[b]=`key_${g++}`;f.write("const newResult = {};");for(let b of m.keys){let E=y[b],I=Lh(b);f.write(`const ${E} = ${h(b)};`),f.write(`
75
+ if (${E}.issues.length) {
76
+ payload.issues = payload.issues.concat(${E}.issues.map(iss => ({
77
+ ...iss,
78
+ path: iss.path ? [${I}, ...iss.path] : [${I}]
79
+ })));
80
+ }
81
+
82
+
83
+ if (${E}.value === undefined) {
84
+ if (${I} in input) {
85
+ newResult[${I}] = undefined;
86
+ }
87
+ } else {
88
+ newResult[${I}] = ${E}.value;
89
+ }
90
+
91
+ `)}f.write("payload.value = newResult;"),f.write("return payload;");let _=f.compile();return(b,E)=>_(p,b,E)},o,s=va,a=!Mh.jitless,c=a&&Lb.value,u=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return s(m)?a&&c&&f?.async===!1&&f.jitless!==!0?(o||(o=i(e.shape)),p=o(p,f),u?UT([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function TT(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;let i=t.filter(o=>!ms(o));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>ri(s,n,Er())))}),e)}var Jh=C("$ZodUnion",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),ut(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),ut(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),ut(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>rf(o.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1,a=[];for(let l of e.options){let c=l._zod.run({value:i.value,issues:[]},o);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(l=>TT(l,i,t,o)):TT(a,i,t,o)}}),Iw=C("$ZodDiscriminatedUnion",(t,e)=>{Jh.init(t,e);let r=t._zod.parse;ut(t._zod,"propValues",()=>{let i={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,l]of Object.entries(s)){i[a]||(i[a]=new Set);for(let c of l)i[a].add(c)}}return i});let n=Uc(()=>{let i=e.options,o=new Map;for(let s of i){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});t._zod.parse=(i,o)=>{let s=i.value;if(!va(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:t}),i)}}),Ew=C("$ZodIntersection",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,o=e.left._zod.run({value:i,issues:[]},n),s=e.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,c])=>AT(r,l,c)):AT(r,o,s)}});function Hb(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ps(t)&&ps(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),i={...t,...e};for(let o of n){let s=Hb(t[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=e[n],s=Hb(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function AT(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ms(t))return t;let n=Hb(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Pw=C("$ZodRecord",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!ps(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let o=[],s=e.keyType._zod.values;if(s){r.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=e.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...vo(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...vo(c,u.issues)),r.value[c]=u.value)}let l;for(let c in i)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let l=e.keyType._zod.run({value:a,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(u=>ri(u,n,Er())),input:a,path:[a],inst:t}),r.value[l.value]=l.value;continue}let c=e.valueType._zod.run({value:i[a],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...vo(a,u.issues)),r.value[l.value]=u.value})):(c.issues.length&&r.issues.push(...vo(a,c.issues)),r.value[l.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Tw=C("$ZodEnum",(t,e)=>{st.init(t,e);let r=Dh(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>Ub.has(typeof i)).map(i=>typeof i=="string"?Ai(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{let s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:r,input:s,inst:t}),i}}),Aw=C("$ZodLiteral",(t,e)=>{if(st.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Ai(n):n?Ai(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var zw=C("$ZodTransform",(t,e)=>{st.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Dc(t.constructor.name);let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new Ti;return r.value=i,r}});function zT(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var Nw=C("$ZodOptional",(t,e)=>{st.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rf(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>zT(o,r.value)):zT(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Cw=C("$ZodNullable",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rf(r.source)}|null)$`):void 0}),ut(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Ow=C("$ZodDefault",(t,e)=>{st.init(t,e),t._zod.optin="optional",ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>NT(o,e)):NT(i,e)}});function NT(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Rw=C("$ZodPrefault",(t,e)=>{st.init(t,e),t._zod.optin="optional",ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Mw=C("$ZodNonOptional",(t,e)=>{st.init(t,e),ut(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>CT(o,t)):CT(i,t)}});function CT(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var jw=C("$ZodCatch",(t,e)=>{st.init(t,e),ut(t._zod,"optin",()=>e.innerType._zod.optin),ut(t._zod,"optout",()=>e.innerType._zod.optout),ut(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ri(s,n,Er()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>ri(o,n,Er()))},input:r.value}),r.issues=[]),r)}});var Dw=C("$ZodPipe",(t,e)=>{st.init(t,e),ut(t._zod,"values",()=>e.in._zod.values),ut(t._zod,"optin",()=>e.in._zod.optin),ut(t._zod,"optout",()=>e.out._zod.optout),ut(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=e.out._zod.run(r,n);return o instanceof Promise?o.then(s=>Gh(s,e.in,n)):Gh(o,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>Gh(o,e.out,n)):Gh(i,e.out,n)}});function Gh(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var Lw=C("$ZodReadonly",(t,e)=>{st.init(t,e),ut(t._zod,"propValues",()=>e.innerType._zod.propValues),ut(t._zod,"values",()=>e.innerType._zod.values),ut(t._zod,"optin",()=>e.innerType?._zod?.optin),ut(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(OT):OT(i)}});function OT(t){return t.value=Object.freeze(t.value),t}var Uw=C("$ZodCustom",(t,e)=>{or.init(t,e),st.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(o=>RT(o,r,n,t));RT(i,r,n,t)}});function RT(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(Zc(i))}}var $U=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},kU=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${$U(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${_e(n.values[0])}`:`Invalid option: expected one of ${ve(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ve(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Zw(){return{localeError:kU()}}var VT,qT=Symbol("ZodOutput"),WT=Symbol("ZodInput"),Yh=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Vw(){return new Yh}(VT=globalThis).__zod_globalRegistry??(VT.__zod_globalRegistry=Vw());var _o=globalThis.__zod_globalRegistry;function qw(t,e){return new t({type:"string",...de(e)})}function Ww(t,e){return new t({type:"string",coerce:!0,...de(e)})}function Bw(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...de(e)})}function Qh(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...de(e)})}function Gw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...de(e)})}function Hw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(e)})}function Xw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(e)})}function Kw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(e)})}function eg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...de(e)})}function Jw(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...de(e)})}function Yw(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(e)})}function Qw(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...de(e)})}function e0(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(e)})}function t0(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...de(e)})}function r0(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...de(e)})}function n0(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(e)})}function i0(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(e)})}function o0(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(e)})}function s0(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(e)})}function a0(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(e)})}function l0(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...de(e)})}function c0(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...de(e)})}function u0(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...de(e)})}function d0(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...de(e)})}function f0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(e)})}function p0(t,e){return new t({type:"string",format:"date",check:"string_format",...de(e)})}function m0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...de(e)})}function h0(t,e){return new t({type:"string",format:"duration",check:"string_format",...de(e)})}function g0(t,e){return new t({type:"number",checks:[],...de(e)})}function y0(t,e){return new t({type:"number",coerce:!0,checks:[],...de(e)})}function v0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...de(e)})}function _0(t,e){return new t({type:"boolean",...de(e)})}function b0(t,e){return new t({type:"boolean",coerce:!0,...de(e)})}function w0(t,e){return new t({type:"bigint",coerce:!0,...de(e)})}function x0(t,e){return new t({type:"null",...de(e)})}function $0(t){return new t({type:"any"})}function k0(t){return new t({type:"unknown"})}function S0(t,e){return new t({type:"never",...de(e)})}function I0(t,e){return new t({type:"date",coerce:!0,...de(e)})}function ba(t,e){return new Bb({check:"less_than",...de(e),value:t,inclusive:!1})}function ni(t,e){return new Bb({check:"less_than",...de(e),value:t,inclusive:!0})}function wa(t,e){return new Gb({check:"greater_than",...de(e),value:t,inclusive:!1})}function xn(t,e){return new Gb({check:"greater_than",...de(e),value:t,inclusive:!0})}function qc(t,e){return new mT({check:"multiple_of",...de(e),value:t})}function cf(t,e){return new gT({check:"max_length",...de(e),maximum:t})}function xa(t,e){return new yT({check:"min_length",...de(e),minimum:t})}function uf(t,e){return new vT({check:"length_equals",...de(e),length:t})}function tg(t,e){return new _T({check:"string_format",format:"regex",...de(e),pattern:t})}function rg(t){return new bT({check:"string_format",format:"lowercase",...de(t)})}function ng(t){return new wT({check:"string_format",format:"uppercase",...de(t)})}function ig(t,e){return new xT({check:"string_format",format:"includes",...de(e),includes:t})}function og(t,e){return new $T({check:"string_format",format:"starts_with",...de(e),prefix:t})}function sg(t,e){return new kT({check:"string_format",format:"ends_with",...de(e),suffix:t})}function bo(t){return new ST({check:"overwrite",tx:t})}function ag(t){return bo(e=>e.normalize(t))}function lg(){return bo(t=>t.trim())}function cg(){return bo(t=>t.toLowerCase())}function ug(){return bo(t=>t.toUpperCase())}function E0(){return bo(t=>Db(t))}function GT(t,e,r){return new t({type:"array",element:e,...de(r)})}function P0(t,e,r){let n=de(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function T0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...de(r)})}function A0(t){let e=PU(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Zc(n,r.value,e._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),r.issues.push(Zc(i))}},t(r.value,r)));return e}function PU(t,e){let r=new or({check:"custom",...de(e)});return r._zod.check=t,r}function Wc(t){return!!t._zod}function oi(t,e){return Wc(t)?Fc(t,e):t.safeParse(e)}function dg(t){var e,r;if(!t)return;let n;if(Wc(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function tA(t){var e;if(Wc(t)){let s=(e=t._zod)===null||e===void 0?void 0:e.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}var df={};Qu(df,{ZodISODate:()=>C0,ZodISODateTime:()=>z0,ZodISODuration:()=>j0,ZodISOTime:()=>R0,date:()=>O0,datetime:()=>N0,duration:()=>D0,time:()=>M0});var z0=C("ZodISODateTime",(t,e)=>{sw.init(t,e),It.init(t,e)});function N0(t){return f0(z0,t)}var C0=C("ZodISODate",(t,e)=>{aw.init(t,e),It.init(t,e)});function O0(t){return p0(C0,t)}var R0=C("ZodISOTime",(t,e)=>{lw.init(t,e),It.init(t,e)});function M0(t){return m0(R0,t)}var j0=C("ZodISODuration",(t,e)=>{cw.init(t,e),It.init(t,e)});function D0(t){return h0(j0,t)}var nA=(t,e)=>{Zh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Vh(t,r)},flatten:{value:r=>Fh(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Lc,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Lc,2)}},isEmpty:{get(){return t.issues.length===0}}})},Bme=C("ZodError",nA),$n=C("ZodError",nA,{Parent:Error});var iA=qh($n),oA=Wh($n),sA=of($n),aA=sf($n),lA=AP($n),cA=zP($n),uA=NP($n),dA=CP($n),fA=OP($n),pA=RP($n),mA=MP($n),hA=jP($n);var vt=C("ZodType",(t,e)=>(st.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(X.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),t.clone=(r,n)=>Yr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>iA(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>sA(t,r,n),t.parseAsync=async(r,n)=>oA(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>aA(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>lA(t,r,n),t.decode=(r,n)=>cA(t,r,n),t.encodeAsync=async(r,n)=>uA(t,r,n),t.decodeAsync=async(r,n)=>dA(t,r,n),t.safeEncode=(r,n)=>fA(t,r,n),t.safeDecode=(r,n)=>pA(t,r,n),t.safeEncodeAsync=async(r,n)=>mA(t,r,n),t.safeDecodeAsync=async(r,n)=>hA(t,r,n),t.refine=(r,n)=>t.check(l6(r,n)),t.superRefine=r=>t.check(c6(r)),t.overwrite=r=>t.check(bo(r)),t.optional=()=>ae(t),t.nullable=()=>vA(t),t.nullish=()=>ae(vA(t)),t.nonoptional=r=>r6(t,r),t.array=()=>J(t),t.or=r=>wt([t,r]),t.and=r=>mg(t,r),t.transform=r=>U0(t,EA(r)),t.default=r=>QZ(t,r),t.prefault=r=>t6(t,r),t.catch=r=>i6(t,r),t.pipe=r=>U0(t,r),t.readonly=()=>a6(t),t.describe=r=>{let n=t.clone();return _o.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return _o.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return _o.get(t);let n=t.clone();return _o.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),_A=C("_ZodString",(t,e)=>{Vc.init(t,e),vt.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(tg(...n)),t.includes=(...n)=>t.check(ig(...n)),t.startsWith=(...n)=>t.check(og(...n)),t.endsWith=(...n)=>t.check(sg(...n)),t.min=(...n)=>t.check(xa(...n)),t.max=(...n)=>t.check(cf(...n)),t.length=(...n)=>t.check(uf(...n)),t.nonempty=(...n)=>t.check(xa(1,...n)),t.lowercase=n=>t.check(rg(n)),t.uppercase=n=>t.check(ng(n)),t.trim=()=>t.check(lg()),t.normalize=(...n)=>t.check(ag(...n)),t.toLowerCase=()=>t.check(cg()),t.toUpperCase=()=>t.check(ug()),t.slugify=()=>t.check(E0())}),Z0=C("ZodString",(t,e)=>{Vc.init(t,e),_A.init(t,e),t.email=r=>t.check(Bw($Z,r)),t.url=r=>t.check(eg(bA,r)),t.jwt=r=>t.check(d0(DZ,r)),t.emoji=r=>t.check(Jw(kZ,r)),t.guid=r=>t.check(Qh(gA,r)),t.uuid=r=>t.check(Gw(fg,r)),t.uuidv4=r=>t.check(Hw(fg,r)),t.uuidv6=r=>t.check(Xw(fg,r)),t.uuidv7=r=>t.check(Kw(fg,r)),t.nanoid=r=>t.check(Yw(SZ,r)),t.guid=r=>t.check(Qh(gA,r)),t.cuid=r=>t.check(Qw(IZ,r)),t.cuid2=r=>t.check(e0(EZ,r)),t.ulid=r=>t.check(t0(PZ,r)),t.base64=r=>t.check(l0(RZ,r)),t.base64url=r=>t.check(c0(MZ,r)),t.xid=r=>t.check(r0(TZ,r)),t.ksuid=r=>t.check(n0(AZ,r)),t.ipv4=r=>t.check(i0(zZ,r)),t.ipv6=r=>t.check(o0(NZ,r)),t.cidrv4=r=>t.check(s0(CZ,r)),t.cidrv6=r=>t.check(a0(OZ,r)),t.e164=r=>t.check(u0(jZ,r)),t.datetime=r=>t.check(N0(r)),t.date=r=>t.check(O0(r)),t.time=r=>t.check(M0(r)),t.duration=r=>t.check(D0(r))});function $(t){return qw(Z0,t)}var It=C("ZodStringFormat",(t,e)=>{yt.init(t,e),_A.init(t,e)}),$Z=C("ZodEmail",(t,e)=>{Jb.init(t,e),It.init(t,e)});var gA=C("ZodGUID",(t,e)=>{Xb.init(t,e),It.init(t,e)});var fg=C("ZodUUID",(t,e)=>{Kb.init(t,e),It.init(t,e)});var bA=C("ZodURL",(t,e)=>{Yb.init(t,e),It.init(t,e)});function wA(t){return eg(bA,t)}var kZ=C("ZodEmoji",(t,e)=>{Qb.init(t,e),It.init(t,e)});var SZ=C("ZodNanoID",(t,e)=>{ew.init(t,e),It.init(t,e)});var IZ=C("ZodCUID",(t,e)=>{tw.init(t,e),It.init(t,e)});var EZ=C("ZodCUID2",(t,e)=>{rw.init(t,e),It.init(t,e)});var PZ=C("ZodULID",(t,e)=>{nw.init(t,e),It.init(t,e)});var TZ=C("ZodXID",(t,e)=>{iw.init(t,e),It.init(t,e)});var AZ=C("ZodKSUID",(t,e)=>{ow.init(t,e),It.init(t,e)});var zZ=C("ZodIPv4",(t,e)=>{uw.init(t,e),It.init(t,e)});var NZ=C("ZodIPv6",(t,e)=>{dw.init(t,e),It.init(t,e)});var CZ=C("ZodCIDRv4",(t,e)=>{fw.init(t,e),It.init(t,e)});var OZ=C("ZodCIDRv6",(t,e)=>{pw.init(t,e),It.init(t,e)});var RZ=C("ZodBase64",(t,e)=>{mw.init(t,e),It.init(t,e)});var MZ=C("ZodBase64URL",(t,e)=>{hw.init(t,e),It.init(t,e)});var jZ=C("ZodE164",(t,e)=>{gw.init(t,e),It.init(t,e)});var DZ=C("ZodJWT",(t,e)=>{yw.init(t,e),It.init(t,e)});var pg=C("ZodNumber",(t,e)=>{Xh.init(t,e),vt.init(t,e),t.gt=(n,i)=>t.check(wa(n,i)),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.lt=(n,i)=>t.check(ba(n,i)),t.lte=(n,i)=>t.check(ni(n,i)),t.max=(n,i)=>t.check(ni(n,i)),t.int=n=>t.check(yA(n)),t.safe=n=>t.check(yA(n)),t.positive=n=>t.check(wa(0,n)),t.nonnegative=n=>t.check(xn(0,n)),t.negative=n=>t.check(ba(0,n)),t.nonpositive=n=>t.check(ni(0,n)),t.multipleOf=(n,i)=>t.check(qc(n,i)),t.step=(n,i)=>t.check(qc(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function at(t){return g0(pg,t)}var LZ=C("ZodNumberFormat",(t,e)=>{vw.init(t,e),pg.init(t,e)});function yA(t){return v0(LZ,t)}var F0=C("ZodBoolean",(t,e)=>{Kh.init(t,e),vt.init(t,e)});function _t(t){return _0(F0,t)}var xA=C("ZodBigInt",(t,e)=>{_w.init(t,e),vt.init(t,e),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.gt=(n,i)=>t.check(wa(n,i)),t.gte=(n,i)=>t.check(xn(n,i)),t.min=(n,i)=>t.check(xn(n,i)),t.lt=(n,i)=>t.check(ba(n,i)),t.lte=(n,i)=>t.check(ni(n,i)),t.max=(n,i)=>t.check(ni(n,i)),t.positive=n=>t.check(wa(BigInt(0),n)),t.negative=n=>t.check(ba(BigInt(0),n)),t.nonpositive=n=>t.check(ni(BigInt(0),n)),t.nonnegative=n=>t.check(xn(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(qc(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var UZ=C("ZodNull",(t,e)=>{bw.init(t,e),vt.init(t,e)});function V0(t){return x0(UZ,t)}var ZZ=C("ZodAny",(t,e)=>{ww.init(t,e),vt.init(t,e)});function $A(){return $0(ZZ)}var FZ=C("ZodUnknown",(t,e)=>{xw.init(t,e),vt.init(t,e)});function Xt(){return k0(FZ)}var VZ=C("ZodNever",(t,e)=>{$w.init(t,e),vt.init(t,e)});function qZ(t){return S0(VZ,t)}var kA=C("ZodDate",(t,e)=>{kw.init(t,e),vt.init(t,e),t.min=(n,i)=>t.check(xn(n,i)),t.max=(n,i)=>t.check(ni(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var WZ=C("ZodArray",(t,e)=>{Sw.init(t,e),vt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xa(r,n)),t.nonempty=r=>t.check(xa(1,r)),t.max=(r,n)=>t.check(cf(r,n)),t.length=(r,n)=>t.check(uf(r,n)),t.unwrap=()=>t.element});function J(t,e){return GT(WZ,t,e)}var SA=C("ZodObject",(t,e)=>{FT.init(t,e),vt.init(t,e),X.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>mr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Xt()}),t.loose=()=>t.clone({...t._zod.def,catchall:Xt()}),t.strict=()=>t.clone({...t._zod.def,catchall:qZ()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>X.extend(t,r),t.safeExtend=r=>X.safeExtend(t,r),t.merge=r=>X.merge(t,r),t.pick=r=>X.pick(t,r),t.omit=r=>X.omit(t,r),t.partial=(...r)=>X.partial(PA,t,r[0]),t.required=(...r)=>X.required(TA,t,r[0])});function q(t,e){let r={type:"object",shape:t??{},...X.normalizeParams(e)};return new SA(r)}function Pr(t,e){return new SA({type:"object",shape:t,catchall:Xt(),...X.normalizeParams(e)})}var IA=C("ZodUnion",(t,e)=>{Jh.init(t,e),vt.init(t,e),t.options=e.options});function wt(t,e){return new IA({type:"union",options:t,...X.normalizeParams(e)})}var BZ=C("ZodDiscriminatedUnion",(t,e)=>{IA.init(t,e),Iw.init(t,e)});function q0(t,e,r){return new BZ({type:"union",options:e,discriminator:t,...X.normalizeParams(r)})}var GZ=C("ZodIntersection",(t,e)=>{Ew.init(t,e),vt.init(t,e)});function mg(t,e){return new GZ({type:"intersection",left:t,right:e})}var HZ=C("ZodRecord",(t,e)=>{Pw.init(t,e),vt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Kt(t,e,r){return new HZ({type:"record",keyType:t,valueType:e,...X.normalizeParams(r)})}var L0=C("ZodEnum",(t,e)=>{Tw.init(t,e),vt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new L0({...e,checks:[],...X.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new L0({...e,checks:[],...X.normalizeParams(i),entries:o})}});function mr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new L0({type:"enum",entries:r,...X.normalizeParams(e)})}var XZ=C("ZodLiteral",(t,e)=>{Aw.init(t,e),vt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function se(t,e){return new XZ({type:"literal",values:Array.isArray(t)?t:[t],...X.normalizeParams(e)})}var KZ=C("ZodTransform",(t,e)=>{zw.init(t,e),vt.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Dc(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(X.issue(o,r.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(X.issue(s))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function EA(t){return new KZ({type:"transform",transform:t})}var PA=C("ZodOptional",(t,e)=>{Nw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ae(t){return new PA({type:"optional",innerType:t})}var JZ=C("ZodNullable",(t,e)=>{Cw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function vA(t){return new JZ({type:"nullable",innerType:t})}var YZ=C("ZodDefault",(t,e)=>{Ow.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function QZ(t,e){return new YZ({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():X.shallowClone(e)}})}var e6=C("ZodPrefault",(t,e)=>{Rw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function t6(t,e){return new e6({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():X.shallowClone(e)}})}var TA=C("ZodNonOptional",(t,e)=>{Mw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function r6(t,e){return new TA({type:"nonoptional",innerType:t,...X.normalizeParams(e)})}var n6=C("ZodCatch",(t,e)=>{jw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function i6(t,e){return new n6({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var o6=C("ZodPipe",(t,e)=>{Dw.init(t,e),vt.init(t,e),t.in=e.in,t.out=e.out});function U0(t,e){return new o6({type:"pipe",in:t,out:e})}var s6=C("ZodReadonly",(t,e)=>{Lw.init(t,e),vt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function a6(t){return new s6({type:"readonly",innerType:t})}var AA=C("ZodCustom",(t,e)=>{Uw.init(t,e),vt.init(t,e)});function zA(t,e){return P0(AA,t??(()=>!0),e)}function l6(t,e={}){return T0(AA,t,e)}function c6(t){return A0(t)}function W0(t,e){return U0(EA(t),e)}var CA={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var NA;NA||(NA={});var hg={};Qu(hg,{bigint:()=>p6,boolean:()=>f6,date:()=>m6,number:()=>d6,string:()=>u6});function u6(t){return Ww(Z0,t)}function d6(t){return y0(pg,t)}function f6(t){return b0(F0,t)}function p6(t){return w0(xA,t)}function m6(t){return I0(kA,t)}Er(Zw());var Gc="2025-11-25";var RA=[Gc,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ni="io.modelcontextprotocol/related-task",yg="2.0",zi=zA(t=>t!==null&&(typeof t=="object"||typeof t=="function")),MA=wt([$(),at().int()]),jA=$(),g6=Pr({ttl:wt([at(),V0()]).optional(),pollInterval:at().optional()}),G0=Pr({taskId:$()}),y6=Pr({progressToken:MA.optional(),[Ni]:G0.optional()}),Qr=Pr({task:g6.optional(),_meta:y6.optional()}),hr=q({method:$(),params:Qr.optional()}),$a=Pr({_meta:q({[Ni]:ae(G0)}).passthrough().optional()}),Mn=q({method:$(),params:$a.optional()}),Tr=Pr({_meta:Pr({[Ni]:G0.optional()}).optional()}),vg=wt([$(),at().int()]),DA=q({jsonrpc:se(yg),id:vg,...hr.shape}).strict(),ff=t=>DA.safeParse(t).success,LA=q({jsonrpc:se(yg),...Mn.shape}).strict(),UA=t=>LA.safeParse(t).success,ZA=q({jsonrpc:se(yg),id:vg,result:Tr}).strict(),ka=t=>ZA.safeParse(t).success,we;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(we||(we={}));var FA=q({jsonrpc:se(yg),id:vg,error:q({code:at().int(),message:$(),data:ae(Xt())})}).strict(),VA=t=>FA.safeParse(t).success,Hc=wt([DA,LA,ZA,FA]),Sa=Tr.strict(),v6=$a.extend({requestId:vg,reason:$().optional()}),_g=Mn.extend({method:se("notifications/cancelled"),params:v6}),_6=q({src:$(),mimeType:$().optional(),sizes:J($()).optional()}),pf=q({icons:J(_6).optional()}),Bc=q({name:$(),title:$().optional()}),qA=Bc.extend({...Bc.shape,...pf.shape,version:$(),websiteUrl:$().optional()}),b6=mg(q({applyDefaults:_t().optional()}),Kt($(),Xt())),w6=W0(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,mg(q({form:b6.optional(),url:zi.optional()}),Kt($(),Xt()).optional())),x6=q({list:ae(q({}).passthrough()),cancel:ae(q({}).passthrough()),requests:ae(q({sampling:ae(q({createMessage:ae(q({}).passthrough())}).passthrough()),elicitation:ae(q({create:ae(q({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),$6=q({list:ae(q({}).passthrough()),cancel:ae(q({}).passthrough()),requests:ae(q({tools:ae(q({call:ae(q({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),k6=q({experimental:Kt($(),zi).optional(),sampling:q({context:zi.optional(),tools:zi.optional()}).optional(),elicitation:w6.optional(),roots:q({listChanged:_t().optional()}).optional(),tasks:ae(x6)}),S6=Qr.extend({protocolVersion:$(),capabilities:k6,clientInfo:qA}),I6=hr.extend({method:se("initialize"),params:S6});var E6=q({experimental:Kt($(),zi).optional(),logging:zi.optional(),completions:zi.optional(),prompts:ae(q({listChanged:ae(_t())})),resources:q({subscribe:_t().optional(),listChanged:_t().optional()}).optional(),tools:q({listChanged:_t().optional()}).optional(),tasks:ae($6)}).passthrough(),H0=Tr.extend({protocolVersion:$(),capabilities:E6,serverInfo:qA,instructions:$().optional()}),WA=Mn.extend({method:se("notifications/initialized")}),BA=t=>WA.safeParse(t).success,bg=hr.extend({method:se("ping")}),P6=q({progress:at(),total:ae(at()),message:ae($())}),T6=q({...$a.shape,...P6.shape,progressToken:MA}),wg=Mn.extend({method:se("notifications/progress"),params:T6}),A6=Qr.extend({cursor:jA.optional()}),mf=hr.extend({params:A6.optional()}),hf=Tr.extend({nextCursor:ae(jA)}),gf=q({taskId:$(),status:mr(["working","input_required","completed","failed","cancelled"]),ttl:wt([at(),V0()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:ae(at()),statusMessage:ae($())}),Ia=Tr.extend({task:gf}),z6=$a.merge(gf),yf=Mn.extend({method:se("notifications/tasks/status"),params:z6}),xg=hr.extend({method:se("tasks/get"),params:Qr.extend({taskId:$()})}),$g=Tr.merge(gf),kg=hr.extend({method:se("tasks/result"),params:Qr.extend({taskId:$()})}),Sg=mf.extend({method:se("tasks/list")}),Ig=hf.extend({tasks:J(gf)}),GA=hr.extend({method:se("tasks/cancel"),params:Qr.extend({taskId:$()})}),HA=Tr.merge(gf),XA=q({uri:$(),mimeType:ae($()),_meta:Kt($(),Xt()).optional()}),KA=XA.extend({text:$()}),X0=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),JA=XA.extend({blob:X0}),Xc=q({audience:J(mr(["user","assistant"])).optional(),priority:at().min(0).max(1).optional(),lastModified:df.datetime({offset:!0}).optional()}),YA=q({...Bc.shape,...pf.shape,uri:$(),description:ae($()),mimeType:ae($()),annotations:Xc.optional(),_meta:ae(Pr({}))}),N6=q({...Bc.shape,...pf.shape,uriTemplate:$(),description:ae($()),mimeType:ae($()),annotations:Xc.optional(),_meta:ae(Pr({}))}),C6=mf.extend({method:se("resources/list")}),K0=hf.extend({resources:J(YA)}),O6=mf.extend({method:se("resources/templates/list")}),J0=hf.extend({resourceTemplates:J(N6)}),Y0=Qr.extend({uri:$()}),R6=Y0,M6=hr.extend({method:se("resources/read"),params:R6}),Q0=Tr.extend({contents:J(wt([KA,JA]))}),j6=Mn.extend({method:se("notifications/resources/list_changed")}),D6=Y0,L6=hr.extend({method:se("resources/subscribe"),params:D6}),U6=Y0,Z6=hr.extend({method:se("resources/unsubscribe"),params:U6}),F6=$a.extend({uri:$()}),V6=Mn.extend({method:se("notifications/resources/updated"),params:F6}),q6=q({name:$(),description:ae($()),required:ae(_t())}),W6=q({...Bc.shape,...pf.shape,description:ae($()),arguments:ae(J(q6)),_meta:ae(Pr({}))}),B6=mf.extend({method:se("prompts/list")}),ex=hf.extend({prompts:J(W6)}),G6=Qr.extend({name:$(),arguments:Kt($(),$()).optional()}),H6=hr.extend({method:se("prompts/get"),params:G6}),tx=q({type:se("text"),text:$(),annotations:Xc.optional(),_meta:Kt($(),Xt()).optional()}),rx=q({type:se("image"),data:X0,mimeType:$(),annotations:Xc.optional(),_meta:Kt($(),Xt()).optional()}),nx=q({type:se("audio"),data:X0,mimeType:$(),annotations:Xc.optional(),_meta:Kt($(),Xt()).optional()}),X6=q({type:se("tool_use"),name:$(),id:$(),input:q({}).passthrough(),_meta:ae(q({}).passthrough())}).passthrough(),K6=q({type:se("resource"),resource:wt([KA,JA]),annotations:Xc.optional(),_meta:Kt($(),Xt()).optional()}),J6=YA.extend({type:se("resource_link")}),ix=wt([tx,rx,nx,J6,K6]),Y6=q({role:mr(["user","assistant"]),content:ix}),ox=Tr.extend({description:ae($()),messages:J(Y6)}),Q6=Mn.extend({method:se("notifications/prompts/list_changed")}),eF=q({title:$().optional(),readOnlyHint:_t().optional(),destructiveHint:_t().optional(),idempotentHint:_t().optional(),openWorldHint:_t().optional()}),tF=q({taskSupport:mr(["required","optional","forbidden"]).optional()}),QA=q({...Bc.shape,...pf.shape,description:$().optional(),inputSchema:q({type:se("object"),properties:Kt($(),zi).optional(),required:J($()).optional()}).catchall(Xt()),outputSchema:q({type:se("object"),properties:Kt($(),zi).optional(),required:J($()).optional()}).catchall(Xt()).optional(),annotations:ae(eF),execution:ae(tF),_meta:Kt($(),Xt()).optional()}),rF=mf.extend({method:se("tools/list")}),sx=hf.extend({tools:J(QA)}),Kc=Tr.extend({content:J(ix).default([]),structuredContent:Kt($(),Xt()).optional(),isError:ae(_t())}),fhe=Kc.or(Tr.extend({toolResult:Xt()})),nF=Qr.extend({name:$(),arguments:ae(Kt($(),Xt()))}),iF=hr.extend({method:se("tools/call"),params:nF}),ax=Mn.extend({method:se("notifications/tools/list_changed")}),ez=mr(["debug","info","notice","warning","error","critical","alert","emergency"]),oF=Qr.extend({level:ez}),sF=hr.extend({method:se("logging/setLevel"),params:oF}),aF=$a.extend({level:ez,logger:$().optional(),data:Xt()}),lx=Mn.extend({method:se("notifications/message"),params:aF}),lF=q({name:$().optional()}),cF=q({hints:ae(J(lF)),costPriority:ae(at().min(0).max(1)),speedPriority:ae(at().min(0).max(1)),intelligencePriority:ae(at().min(0).max(1))}),uF=q({mode:ae(mr(["auto","required","none"]))}),dF=q({type:se("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:J(ix).default([]),structuredContent:q({}).passthrough().optional(),isError:ae(_t()),_meta:ae(q({}).passthrough())}).passthrough(),fF=q0("type",[tx,rx,nx]),gg=q0("type",[tx,rx,nx,X6,dF]),pF=q({role:mr(["user","assistant"]),content:wt([gg,J(gg)]),_meta:ae(q({}).passthrough())}).passthrough(),mF=Qr.extend({messages:J(pF),modelPreferences:cF.optional(),systemPrompt:$().optional(),includeContext:mr(["none","thisServer","allServers"]).optional(),temperature:at().optional(),maxTokens:at().int(),stopSequences:J($()).optional(),metadata:zi.optional(),tools:ae(J(QA)),toolChoice:ae(uF)}),cx=hr.extend({method:se("sampling/createMessage"),params:mF}),ux=Tr.extend({model:$(),stopReason:ae(mr(["endTurn","stopSequence","maxTokens"]).or($())),role:mr(["user","assistant"]),content:fF}),hF=Tr.extend({model:$(),stopReason:ae(mr(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:mr(["user","assistant"]),content:wt([gg,J(gg)])}),gF=q({type:se("boolean"),title:$().optional(),description:$().optional(),default:_t().optional()}),yF=q({type:se("string"),title:$().optional(),description:$().optional(),minLength:at().optional(),maxLength:at().optional(),format:mr(["email","uri","date","date-time"]).optional(),default:$().optional()}),vF=q({type:mr(["number","integer"]),title:$().optional(),description:$().optional(),minimum:at().optional(),maximum:at().optional(),default:at().optional()}),_F=q({type:se("string"),title:$().optional(),description:$().optional(),enum:J($()),default:$().optional()}),bF=q({type:se("string"),title:$().optional(),description:$().optional(),oneOf:J(q({const:$(),title:$()})),default:$().optional()}),wF=q({type:se("string"),title:$().optional(),description:$().optional(),enum:J($()),enumNames:J($()).optional(),default:$().optional()}),xF=wt([_F,bF]),$F=q({type:se("array"),title:$().optional(),description:$().optional(),minItems:at().optional(),maxItems:at().optional(),items:q({type:se("string"),enum:J($())}),default:J($()).optional()}),kF=q({type:se("array"),title:$().optional(),description:$().optional(),minItems:at().optional(),maxItems:at().optional(),items:q({anyOf:J(q({const:$(),title:$()}))}),default:J($()).optional()}),SF=wt([$F,kF]),IF=wt([wF,xF,SF]),EF=wt([IF,gF,yF,vF]),PF=Qr.extend({mode:se("form").optional(),message:$(),requestedSchema:q({type:se("object"),properties:Kt($(),EF),required:J($()).optional()})}),TF=Qr.extend({mode:se("url"),message:$(),elicitationId:$(),url:$().url()}),AF=wt([PF,TF]),dx=hr.extend({method:se("elicitation/create"),params:AF}),zF=$a.extend({elicitationId:$()}),NF=Mn.extend({method:se("notifications/elicitation/complete"),params:zF}),fx=Tr.extend({action:mr(["accept","decline","cancel"]),content:W0(t=>t===null?void 0:t,Kt($(),wt([$(),at(),_t(),J($())])).optional())}),CF=q({type:se("ref/resource"),uri:$()});var OF=q({type:se("ref/prompt"),name:$()}),RF=Qr.extend({ref:wt([OF,CF]),argument:q({name:$(),value:$()}),context:q({arguments:Kt($(),$()).optional()}).optional()}),MF=hr.extend({method:se("completion/complete"),params:RF});var px=Tr.extend({completion:Pr({values:J($()).max(100),total:ae(at().int()),hasMore:ae(_t())})}),jF=q({uri:$().startsWith("file://"),name:$().optional(),_meta:Kt($(),Xt()).optional()}),DF=hr.extend({method:se("roots/list")}),LF=Tr.extend({roots:J(jF)}),UF=Mn.extend({method:se("notifications/roots/list_changed")}),phe=wt([bg,I6,MF,sF,H6,B6,C6,O6,M6,L6,Z6,iF,rF,xg,kg,Sg]),mhe=wt([_g,wg,WA,UF,yf]),hhe=wt([Sa,ux,hF,fx,LF,$g,Ig,Ia]),ghe=wt([bg,cx,dx,DF,xg,kg,Sg]),yhe=wt([_g,wg,lx,V6,j6,ax,Q6,yf,NF]),vhe=wt([Sa,H0,px,ox,ex,K0,J0,Q0,Kc,sx,$g,Ig,Ia]),me=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===we.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new B0(i.elicitations,r)}return new t(e,r,n)}},B0=class extends me{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(we.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}};function hs(t){return t==="completed"||t==="failed"||t==="cancelled"}var ZF=Symbol("Let zodToJsonSchema decide on which parser to use");var Yhe=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mx(t){let e=dg(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=tA(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hx(t,e){let r=oi(t,e);if(!r.success)throw r.error;return r.data}var GF=6e4,Eg=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(_g,r=>{this._oncancel(r)}),this.setNotificationHandler(wg,r=>{this._onprogress(r)}),this.setRequestHandler(bg,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xg,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new me(we.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(kg,async(r,n)=>{let i=async()=>{var o;let s=r.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(l.type==="response"||l.type==="error"){let c=l.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),l.type==="response")d(c);else{let p=c,f=new me(p.error.code,p.error.message,p.error.data);d(f)}else{let p=l.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await((o=this._transport)===null||o===void 0?void 0:o.send(l.message,{relatedRequestId:n.requestId}))}}let a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new me(we.InvalidParams,`Task not found: ${s}`);if(!hs(a.status))return await this._waitForTaskUpdate(s,n.signal),await i();if(hs(a.status)){let l=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...l,_meta:{...l._meta,[Ni]:{taskId:s}}}}return await i()};return await i()}),this.setRequestHandler(Sg,async(r,n)=>{var i;try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks((i=r.params)===null||i===void 0?void 0:i.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new me(we.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(GA,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new me(we.InvalidParams,`Task not found: ${r.params.taskId}`);if(hs(i.status))throw new me(we.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new me(we.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof me?i:new me(we.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){let r=this._requestHandlerAbortControllers.get(e.params.requestId);r?.abort(e.params.reason)}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),me.fromError(we.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let o=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{o?.(),this._onclose()};let s=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=l=>{s?.(l),this._onerror(l)};let a=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(l,c)=>{a?.(l,c),ka(l)||VA(l)?this._onresponse(l):ff(l)?this._onrequest(l,c):UA(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let n=me.fromError(we.ConnectionClosed,"Connection closed");this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i,o,s,a,l;let c=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,u=this._transport,d=(s=(o=(i=e.params)===null||i===void 0?void 0:i._meta)===null||o===void 0?void 0:o[Ni])===null||s===void 0?void 0:s.taskId;if(c===void 0){let y={jsonrpc:"2.0",id:e.id,error:{code:we.MethodNotFound,message:"Method not found"}};d&&this._taskMessageQueue?this._enqueueTaskMessage(d,{type:"error",message:y,timestamp:Date.now()},u?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):u?.send(y).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let p=new AbortController;this._requestHandlerAbortControllers.set(e.id,p);let f=(a=e.params)===null||a===void 0?void 0:a.task,m=this._taskStore?this.requestTaskStore(e,u?.sessionId):void 0,h={signal:p.signal,sessionId:u?.sessionId,_meta:(l=e.params)===null||l===void 0?void 0:l._meta,sendNotification:async y=>{let g={relatedRequestId:e.id};d&&(g.relatedTask={taskId:d}),await this.notification(y,g)},sendRequest:async(y,g,_)=>{var b,E;let I={..._,relatedRequestId:e.id};d&&!I.relatedTask&&(I.relatedTask={taskId:d});let P=(E=(b=I.relatedTask)===null||b===void 0?void 0:b.taskId)!==null&&E!==void 0?E:d;return P&&m&&await m.updateTaskStatus(P,"input_required"),await this.request(y,g,I)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:d,taskStore:m,taskRequestedTtl:f?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{f&&this.assertTaskHandlerCapability(e.method)}).then(()=>c(e,h)).then(async y=>{if(p.signal.aborted)return;let g={result:y,jsonrpc:"2.0",id:e.id};d&&this._taskMessageQueue?await this._enqueueTaskMessage(d,{type:"response",message:g,timestamp:Date.now()},u?.sessionId):await u?.send(g)},async y=>{var g;if(p.signal.aborted)return;let _={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(y.code)?y.code:we.InternalError,message:(g=y.message)!==null&&g!==void 0?g:"Internal error",...y.data!==void 0&&{data:y.data}}};d&&this._taskMessageQueue?await this._enqueueTaskMessage(d,{type:"error",message:_,timestamp:Date.now()},u?.sessionId):await u?.send(_)}).catch(y=>this._onerror(new Error(`Failed to send response: ${y}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(l){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(l);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ka(e))n(e);else{let s=new me(e.error.code,e.error.message,e.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(ka(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ka(e))i(e);else{let s=me.fromError(e.error.code,e.error.message,e.error.data);i(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}async*requestStream(e,r,n){var i,o,s,a;let{task:l}=n??{};if(!l){try{yield{type:"result",result:await this.request(e,r,n)}}catch(u){yield{type:"error",error:u instanceof me?u:new me(we.InternalError,String(u))}}return}let c;try{let u=await this.request(e,Ia,n);if(u.task)c=u.task.taskId,yield{type:"taskCreated",task:u.task};else throw new me(we.InternalError,"Task creation did not return a task");for(;;){let d=await this.getTask({taskId:c},n);if(yield{type:"taskStatus",task:d},hs(d.status)){d.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)}:d.status==="failed"?yield{type:"error",error:new me(we.InternalError,`Task ${c} failed`)}:d.status==="cancelled"&&(yield{type:"error",error:new me(we.InternalError,`Task ${c} was cancelled`)});return}if(d.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:c},r,n)};return}let p=(s=(i=d.pollInterval)!==null&&i!==void 0?i:(o=this._options)===null||o===void 0?void 0:o.defaultTaskPollInterval)!==null&&s!==void 0?s:1e3;await new Promise(f=>setTimeout(f,p)),(a=n?.signal)===null||a===void 0||a.throwIfAborted()}}catch(u){yield{type:"error",error:u instanceof me?u:new me(we.InternalError,String(u))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:l}=n??{};return new Promise((c,u)=>{var d,p,f,m,h,y,g;let _=R=>{u(R)};if(!this._transport){_(new Error("Not connected"));return}if(((d=this._options)===null||d===void 0?void 0:d.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){_(R);return}(p=n?.signal)===null||p===void 0||p.throwIfAborted();let b=this._requestMessageId++,E={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),E.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:b}}),a&&(E.params={...E.params,task:a}),l&&(E.params={...E.params,_meta:{...((m=E.params)===null||m===void 0?void 0:m._meta)||{},[Ni]:l}});let I=R=>{var L;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(L=this._transport)===null||L===void 0||L.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(R)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let G=R instanceof me?R:new me(we.RequestTimeout,String(R));u(G)};this._responseHandlers.set(b,R=>{var L;if(!(!((L=n?.signal)===null||L===void 0)&&L.aborted)){if(R instanceof Error)return u(R);try{let G=oi(r,R.result);G.success?c(G.data):u(G.error)}catch(G){u(G)}}}),(h=n?.signal)===null||h===void 0||h.addEventListener("abort",()=>{var R;I((R=n?.signal)===null||R===void 0?void 0:R.reason)});let P=(y=n?.timeout)!==null&&y!==void 0?y:GF,M=()=>I(me.fromError(we.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(b,P,n?.maxTotalTimeout,M,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1);let V=l?.taskId;if(V){let R=L=>{let G=this._responseHandlers.get(b);G?G(L):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,R),this._enqueueTaskMessage(V,{type:"request",message:E,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(b),u(L)})}else this._transport.send(E,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(R=>{this._cleanupTimeout(b),u(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},$g,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ig,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},HA,r)}async notification(e,r){var n,i,o,s,a;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let l=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(l){let p={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((i=e.params)===null||i===void 0?void 0:i._meta)||{},[Ni]:r.relatedTask}}};await this._enqueueTaskMessage(l,{type:"notification",message:p,timestamp:Date.now()});return}if(((s=(o=this._options)===null||o===void 0?void 0:o.debouncedNotificationMethods)!==null&&s!==void 0?s:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var p,f;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let m={...e,jsonrpc:"2.0"};r?.relatedTask&&(m={...m,params:{...m.params,_meta:{...((p=m.params)===null||p===void 0?void 0:p._meta)||{},[Ni]:r.relatedTask}}}),(f=this._transport)===null||f===void 0||f.send(m,r).catch(h=>this._onerror(h))});return}let d={...e,jsonrpc:"2.0"};r?.relatedTask&&(d={...d,params:{...d.params,_meta:{...((a=d.params)===null||a===void 0?void 0:a._meta)||{},[Ni]:r.relatedTask}}}),await this._transport.send(d,r)}setRequestHandler(e,r){let n=mx(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=hx(e,i);return Promise.resolve(r(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=mx(e);this._notificationHandlers.set(n,i=>{let o=hx(e,i);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=(i=this._options)===null||i===void 0?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&ff(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new me(we.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){var n,i,o;let s=(i=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&i!==void 0?i:1e3;try{let a=await((o=this._taskStore)===null||o===void 0?void 0:o.getTask(e));a?.pollInterval&&(s=a.pollInterval)}catch{}return new Promise((a,l)=>{if(r.aborted){l(new me(we.InvalidRequest,"Request cancelled"));return}let c=setTimeout(a,s);r.addEventListener("abort",()=>{clearTimeout(c),l(new me(we.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new me(we.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,r);let a=await n.getTask(i,r);if(a){let l=yf.parse({method:"notifications/tasks/status",params:a});await this.notification(l),hs(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,r);if(!a)throw new me(we.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(hs(a.status))throw new me(we.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,s,r);let l=await n.getTask(i,r);if(l){let c=yf.parse({method:"notifications/tasks/status",params:l});await this.notification(c),hs(l.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function tz(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rz(t,e){let r={...t};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let s=r[i];tz(s)&&tz(o)?r[i]={...s,...o}:r[i]=o}return r}var nM=t_(PC(),1),iM=t_(rM(),1);function AK(){let t=new nM.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,iM.default)(t),t}var Zy=class{constructor(e){this._ajv=e??AK()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Fy=class{constructor(e){this._client=e}async*callToolStream(e,r=Kc,n){var i;let o=this._client,s={...n,task:(i=n?.task)!==null&&i!==void 0?i:o.isToolTask(e.name)?{}:void 0},a=o.requestStream({method:"tools/call",params:e},r,s),l=o.getToolOutputValidator(e.name);for await(let c of a){if(c.type==="result"&&l){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new me(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let d=l(u.structuredContent);if(!d.valid){yield{type:"error",error:new me(we.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof me){yield{type:"error",error:d};return}yield{type:"error",error:new me(we.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function oM(t,e,r){var n;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!(!((n=t.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function sM(t,e,r){var n,i;if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!(!((n=t.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!(!((i=t.elicitation)===null||i===void 0)&&i.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Vy(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let o=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[i]=o.default),r[i]!==void 0&&Vy(o,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)Vy(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)Vy(r,e)}}function zK(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var $p=class extends Eg{constructor(e,r){var n,i;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new Zy}get experimental(){return this._experimental||(this._experimental={tasks:new Fy(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rz(this._capabilities,e)}setRequestHandler(e,r){var n,i,o;let s=dg(e),a=s?.method;if(!a)throw new Error("Schema is missing a method literal");let l;if(Wc(a)){let u=a,d=(n=u._zod)===null||n===void 0?void 0:n.def;l=(i=d?.value)!==null&&i!==void 0?i:u.value}else{let u=a,d=u._def;l=(o=d?.value)!==null&&o!==void 0?o:u.value}if(typeof l!="string")throw new Error("Schema method literal must be a string");let c=l;if(c==="elicitation/create"){let u=async(d,p)=>{var f,m,h;let y=oi(dx,d);if(!y.success){let R=y.error instanceof Error?y.error.message:String(y.error);throw new me(we.InvalidParams,`Invalid elicitation request: ${R}`)}let{params:g}=y.data,_=(f=g.mode)!==null&&f!==void 0?f:"form",{supportsFormMode:b,supportsUrlMode:E}=zK(this._capabilities.elicitation);if(_==="form"&&!b)throw new me(we.InvalidParams,"Client does not support form-mode elicitation requests");if(_==="url"&&!E)throw new me(we.InvalidParams,"Client does not support URL-mode elicitation requests");let I=await Promise.resolve(r(d,p));if(g.task){let R=oi(Ia,I);if(!R.success){let L=R.error instanceof Error?R.error.message:String(R.error);throw new me(we.InvalidParams,`Invalid task creation result: ${L}`)}return R.data}let P=oi(fx,I);if(!P.success){let R=P.error instanceof Error?P.error.message:String(P.error);throw new me(we.InvalidParams,`Invalid elicitation result: ${R}`)}let M=P.data,V=_==="form"?g.requestedSchema:void 0;if(_==="form"&&M.action==="accept"&&M.content&&V&&!((h=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||h===void 0)&&h.applyDefaults)try{Vy(V,M.content)}catch{}return M};return super.setRequestHandler(e,u)}if(c==="sampling/createMessage"){let u=async(d,p)=>{let f=oi(cx,d);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new me(we.InvalidParams,`Invalid sampling request: ${g}`)}let{params:m}=f.data,h=await Promise.resolve(r(d,p));if(m.task){let g=oi(Ia,h);if(!g.success){let _=g.error instanceof Error?g.error.message:String(g.error);throw new me(we.InvalidParams,`Invalid task creation result: ${_}`)}return g.data}let y=oi(ux,h);if(!y.success){let g=y.error instanceof Error?y.error.message:String(y.error);throw new me(we.InvalidParams,`Invalid sampling result: ${g}`)}return y.data};return super.setRequestHandler(e,u)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Gc,capabilities:this._capabilities,clientInfo:this._clientInfo}},H0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!RA.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,o,s;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){var r,n;oM((n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,e,"Server")}assertTaskHandlerCapability(e){var r;this._capabilities&&sM((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Sa,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},px,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Sa,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},ox,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ex,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},K0,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},J0,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Q0,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Sa,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Sa,r)}async callTool(e,r=Kc,n){if(this.isToolTaskRequired(e.name))throw new me(we.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!i.structuredContent&&!i.isError)throw new me(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let s=o(i.structuredContent);if(!s.valid)throw new me(we.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof me?s:new me(we.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}isToolTask(e){var r,n,i,o;return!((o=(i=(n=(r=this._serverCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests)===null||i===void 0?void 0:i.tools)===null||o===void 0)&&o.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){var r;this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let n of e){if(n.outputSchema){let o=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,o)}let i=(r=n.execution)===null||r===void 0?void 0:r.taskSupport;(i==="required"||i==="optional")&&this._cachedKnownTaskTools.add(n.name),i==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},sx,r);return this.cacheToolMetadata(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Su(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function qy(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...Su(e.headers),...Su(n.headers)}:e.headers};return t(r,i)}:t}var DS;DS=globalThis.crypto;async function NK(t){return(await DS).getRandomValues(new Uint8Array(t))}async function CK(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await NK(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function OK(t){return await CK(t)}async function RK(t){let e=await(await DS).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function LS(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await OK(t),r=await RK(e);return{code_verifier:e,code_challenge:r}}var xr=wA().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:CA.custom,message:"URL must be parseable",fatal:!0}),jh}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),lM=Pr({resource:$().url(),authorization_servers:J(xr).optional(),jwks_uri:$().url().optional(),scopes_supported:J($()).optional(),bearer_methods_supported:J($()).optional(),resource_signing_alg_values_supported:J($()).optional(),resource_name:$().optional(),resource_documentation:$().optional(),resource_policy_uri:$().url().optional(),resource_tos_uri:$().url().optional(),tls_client_certificate_bound_access_tokens:_t().optional(),authorization_details_types_supported:J($()).optional(),dpop_signing_alg_values_supported:J($()).optional(),dpop_bound_access_tokens_required:_t().optional()}),US=Pr({issuer:$(),authorization_endpoint:xr,token_endpoint:xr,registration_endpoint:xr.optional(),scopes_supported:J($()).optional(),response_types_supported:J($()),response_modes_supported:J($()).optional(),grant_types_supported:J($()).optional(),token_endpoint_auth_methods_supported:J($()).optional(),token_endpoint_auth_signing_alg_values_supported:J($()).optional(),service_documentation:xr.optional(),revocation_endpoint:xr.optional(),revocation_endpoint_auth_methods_supported:J($()).optional(),revocation_endpoint_auth_signing_alg_values_supported:J($()).optional(),introspection_endpoint:$().optional(),introspection_endpoint_auth_methods_supported:J($()).optional(),introspection_endpoint_auth_signing_alg_values_supported:J($()).optional(),code_challenge_methods_supported:J($()).optional(),client_id_metadata_document_supported:_t().optional()}),MK=Pr({issuer:$(),authorization_endpoint:xr,token_endpoint:xr,userinfo_endpoint:xr.optional(),jwks_uri:xr,registration_endpoint:xr.optional(),scopes_supported:J($()).optional(),response_types_supported:J($()),response_modes_supported:J($()).optional(),grant_types_supported:J($()).optional(),acr_values_supported:J($()).optional(),subject_types_supported:J($()),id_token_signing_alg_values_supported:J($()),id_token_encryption_alg_values_supported:J($()).optional(),id_token_encryption_enc_values_supported:J($()).optional(),userinfo_signing_alg_values_supported:J($()).optional(),userinfo_encryption_alg_values_supported:J($()).optional(),userinfo_encryption_enc_values_supported:J($()).optional(),request_object_signing_alg_values_supported:J($()).optional(),request_object_encryption_alg_values_supported:J($()).optional(),request_object_encryption_enc_values_supported:J($()).optional(),token_endpoint_auth_methods_supported:J($()).optional(),token_endpoint_auth_signing_alg_values_supported:J($()).optional(),display_values_supported:J($()).optional(),claim_types_supported:J($()).optional(),claims_supported:J($()).optional(),service_documentation:$().optional(),claims_locales_supported:J($()).optional(),ui_locales_supported:J($()).optional(),claims_parameter_supported:_t().optional(),request_parameter_supported:_t().optional(),request_uri_parameter_supported:_t().optional(),require_request_uri_registration:_t().optional(),op_policy_uri:xr.optional(),op_tos_uri:xr.optional(),client_id_metadata_document_supported:_t().optional()}),cM=q({...MK.shape,...US.pick({code_challenge_methods_supported:!0}).shape}),uM=q({access_token:$(),id_token:$().optional(),token_type:$(),expires_in:hg.number().optional(),scope:$().optional(),refresh_token:$().optional()}).strip(),dM=q({error:$(),error_description:$().optional(),error_uri:$().optional()}),aM=xr.optional().or(se("").transform(()=>{})),jK=q({redirect_uris:J(xr),token_endpoint_auth_method:$().optional(),grant_types:J($()).optional(),response_types:J($()).optional(),client_name:$().optional(),client_uri:xr.optional(),logo_uri:aM,scope:$().optional(),contacts:J($()).optional(),tos_uri:aM,policy_uri:$().optional(),jwks_uri:xr.optional(),jwks:$A().optional(),software_id:$().optional(),software_version:$().optional(),software_statement:$().optional()}).strip(),DK=q({client_id:$(),client_secret:$().optional(),client_id_issued_at:at().optional(),client_secret_expires_at:at().optional()}).strip(),fM=jK.merge(DK),Owe=q({error:$(),error_description:$().optional()}).strip(),Rwe=q({token:$(),token_type_hint:$().optional()}).strip();function pM(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function mM({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var Ut=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},kp=class extends Ut{};kp.errorCode="invalid_request";var Ga=class extends Ut{};Ga.errorCode="invalid_client";var Ha=class extends Ut{};Ha.errorCode="invalid_grant";var Xa=class extends Ut{};Xa.errorCode="unauthorized_client";var Sp=class extends Ut{};Sp.errorCode="unsupported_grant_type";var Ip=class extends Ut{};Ip.errorCode="invalid_scope";var Ep=class extends Ut{};Ep.errorCode="access_denied";var zo=class extends Ut{};zo.errorCode="server_error";var Pp=class extends Ut{};Pp.errorCode="temporarily_unavailable";var Tp=class extends Ut{};Tp.errorCode="unsupported_response_type";var Ap=class extends Ut{};Ap.errorCode="unsupported_token_type";var zp=class extends Ut{};zp.errorCode="invalid_token";var Np=class extends Ut{};Np.errorCode="method_not_allowed";var Cp=class extends Ut{};Cp.errorCode="too_many_requests";var Ka=class extends Ut{};Ka.errorCode="invalid_client_metadata";var Op=class extends Ut{};Op.errorCode="insufficient_scope";var Rp=class extends Ut{};Rp.errorCode="invalid_target";var hM={[kp.errorCode]:kp,[Ga.errorCode]:Ga,[Ha.errorCode]:Ha,[Xa.errorCode]:Xa,[Sp.errorCode]:Sp,[Ip.errorCode]:Ip,[Ep.errorCode]:Ep,[zo.errorCode]:zo,[Pp.errorCode]:Pp,[Tp.errorCode]:Tp,[Ap.errorCode]:Ap,[zp.errorCode]:zp,[Np.errorCode]:Np,[Cp.errorCode]:Cp,[Ka.errorCode]:Ka,[Op.errorCode]:Op,[Rp.errorCode]:Rp};var Br=class extends Error{constructor(e){super(e??"Unauthorized")}};function LK(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var ZS="code",FS="S256";function UK(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&LK(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function ZK(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":FK(i,o,r);return;case"client_secret_post":VK(i,o,n);return;case"none":qK(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function FK(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function VK(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function qK(t,e){e.set("client_id",t)}async function yM(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=dM.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=hM[i]||zo;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new zo(i)}}async function No(t,e){var r,n;try{return await VS(t,e)}catch(i){if(i instanceof Ga||i instanceof Xa)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await VS(t,e);if(i instanceof Ha)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await VS(t,e);throw i}}async function VS(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){var s,a;let l,c;try{l=await GK(e,{resourceMetadataUrl:i},o),l.authorization_servers&&l.authorization_servers.length>0&&(c=l.authorization_servers[0])}catch{}c||(c=new URL("/",e));let u=await BK(e,t,l),d=await YK(c,{fetchFn:o}),p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let _=d?.client_id_metadata_document_supported===!0,b=t.clientMetadataUrl;if(b&&!WK(b))throw new Ka(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(_&&b)p={client_id:b},await((s=t.saveClientInformation)===null||s===void 0?void 0:s.call(t,p));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let I=await n8(c,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation(I),p=I}}let f=!t.redirectUrl;if(r!==void 0||f){let _=await r8(t,c,{metadata:d,resource:u,authorizationCode:r,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let _=await t8(c,{metadata:d,clientInformation:p,refreshToken:m.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof Ut)||_ instanceof zo))throw _}let h=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:g}=await QK(c,{metadata:d,clientInformation:p,state:h,redirectUrl:t.redirectUrl,scope:n||((a=l?.scopes_supported)===null||a===void 0?void 0:a.join(" "))||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(g),await t.redirectToAuthorization(y),"REDIRECT"}function WK(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function BK(t,e,r){let n=pM(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!mM({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Iu(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let i=qS(t,"resource_metadata")||void 0,o;if(i)try{o=new URL(i)}catch{}let s=qS(t,"scope")||void 0,a=qS(t,"error")||void 0;return{resourceMetadataUrl:o,scope:s,error:a}}function qS(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function GK(t,e,r=fetch){var n,i;let o=await KK(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await((n=o?.body)===null||n===void 0?void 0:n.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await((i=o.body)===null||i===void 0?void 0:i.cancel()),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return lM.parse(await o.json())}async function WS(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?WS(t,void 0,r):void 0;throw n}}function HK(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function gM(t,e,r=fetch){return await WS(t,{"MCP-Protocol-Version":e},r)}function XK(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function KK(t,e,r,n){var i,o;let s=new URL(t),a=(i=n?.protocolVersion)!==null&&i!==void 0?i:Gc,l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{let u=HK(e,s.pathname);l=new URL(u,(o=n?.metadataServerUrl)!==null&&o!==void 0?o:s),l.search=s.search}let c=await gM(l,a,r);if(!n?.metadataUrl&&XK(c,s.pathname)){let u=new URL(`/.well-known/${e}`,s);c=await gM(u,a,r)}return c}function JK(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function YK(t,{fetchFn:e=fetch,protocolVersion:r=Gc}={}){var n;let i={"MCP-Protocol-Version":r,Accept:"application/json"},o=JK(t);for(let{url:s,type:a}of o){let l=await WS(s,i,e);if(l){if(!l.ok){if(await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?US.parse(await l.json()):cM.parse(await l.json())}}}async function QK(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(ZS))throw new Error(`Incompatible auth server: does not support response type ${ZS}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(FS))throw new Error(`Incompatible auth server: does not support code challenge method ${FS}`)}else a=new URL("/authorize",t);let l=await LS(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",ZS),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",FS),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:c}}function e8(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function vM(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:i,resource:o,fetchFn:s}){var a;let l=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),i)await i(c,r,l,e);else if(n){let d=(a=e?.token_endpoint_auth_methods_supported)!==null&&a!==void 0?a:[],p=UK(n,d);ZK(p,n,c,r)}let u=await(s??fetch)(l,{method:"POST",headers:c,body:r});if(!u.ok)throw await yM(u);return uM.parse(await u.json())}async function t8(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await vM(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:o,resource:i,fetchFn:s});return{refresh_token:n,...l}}async function r8(t,e,{metadata:r,resource:n,authorizationCode:i,fetchFn:o}={}){let s=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(s)),!a){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let c=await t.codeVerifier();a=e8(i,c,t.redirectUrl)}let l=await t.clientInformation();return vM(e,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function n8(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await yM(o);return fM.parse(await o.json())}var Wy=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function BS(t){}function By(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=BS,onError:r=BS,onRetry:n=BS,onComment:i}=t,o="",s=!0,a,l="",c="";function u(h){let y=s?h.replace(/^\xEF\xBB\xBF/,""):h,[g,_]=i8(`${o}${y}`);for(let b of g)d(b);o=_,s=!1}function d(h){if(h===""){f();return}if(h.startsWith(":")){i&&i(h.slice(h.startsWith(": ")?2:1));return}let y=h.indexOf(":");if(y!==-1){let g=h.slice(0,y),_=h[y+1]===" "?2:1,b=h.slice(y+_);p(g,b,h);return}p(h,"",h)}function p(h,y,g){switch(h){case"event":c=y;break;case"data":l=`${l}${y}
92
+ `;break;case"id":a=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new Wy(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:g}));break;default:r(new Wy(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:y,line:g}));break}}function f(){l.length>0&&e({id:a,event:c||void 0,data:l.endsWith(`
93
+ `)?l.slice(0,-1):l}),a=void 0,l="",c=""}function m(h={}){o&&h.consume&&d(o),s=!0,a=void 0,l="",c="",o=""}return{feed:u,reset:m}}function i8(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
94
+ `,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
95
+ `&&n++}}return[e,r]}var Gy=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=By({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var o8={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},As=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Hy=class{constructor(e,r){var n;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qy(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=(n=r?.reconnectionOptions)!==null&&n!==void 0?n:o8}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=Su((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}async _startOrAuthSse(e){var r,n,i,o;let{resumptionToken:s}=e;try{let a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);let l=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:a,signal:(n=this._abortController)===null||n===void 0?void 0:n.signal});if(!l.ok){if(await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.status===401&&this._authProvider)return await this._authThenStart();if(l.status===405)return;throw new As(l.status,`Failed to open SSE stream: ${l.statusText}`)}this._handleSseStream(l.body,e,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){var n;let i=this._reconnectionOptions.maxRetries;if(r>=i){(n=this.onerror)===null||n===void 0||n.call(this,new Error(`Maximum reconnection attempts (${i}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,l=!1;(async()=>{var u,d,p,f;try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new Gy({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:_}=await m.read();if(_)break;if(g.id&&(s=g.id,a=!0,i?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let b=Hc.parse(JSON.parse(g.data));ka(b)&&(l=!0,o!==void 0&&(b.id=o)),(u=this.onmessage)===null||u===void 0||u.call(this,b)}catch(b){(d=this.onerror)===null||d===void 0||d.call(this,b)}}(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(m){if((p=this.onerror)===null||p===void 0||p.call(this,new Error(`SSE stream disconnected: ${m}`)),(n||a)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(g){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var n,i,o,s,a,l,c;try{let{resumptionToken:u,onresumptiontoken:d}=r||{};if(u){this._startOrAuthSse({resumptionToken:u,replayMessageId:ff(e)?e.id:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let p=await this._commonHeaders();p.set("content-type","application/json"),p.set("accept","application/json, text/event-stream");let f={...this._requestInit,method:"POST",headers:p,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},m=await((i=this._fetch)!==null&&i!==void 0?i:fetch)(this._url,f),h=m.headers.get("mcp-session-id");if(h&&(this._sessionId=h),!m.ok){let b=await m.text().catch(()=>null);if(m.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new As(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:E,scope:I}=Iu(m);if(this._resourceMetadataUrl=E,this._scope=I,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this._hasCompletedAuthFlow=!0,this.send(e)}if(m.status===403&&this._authProvider){let{resourceMetadataUrl:E,scope:I,error:P}=Iu(m);if(P==="insufficient_scope"){let M=m.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new As(403,"Server returned 403 after trying upscoping");if(I&&(this._scope=I),E&&(this._resourceMetadataUrl=E),this._lastUpscopingHeader=M??void 0,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Br;return this.send(e)}}throw new As(m.status,`Error POSTing to endpoint: ${b}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,m.status===202){await((o=m.body)===null||o===void 0?void 0:o.cancel()),BA(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(b=>{var E;return(E=this.onerror)===null||E===void 0?void 0:E.call(this,b)});return}let g=(Array.isArray(e)?e:[e]).filter(b=>"method"in b&&"id"in b&&b.id!==void 0).length>0,_=m.headers.get("content-type");if(g)if(_?.includes("text/event-stream"))this._handleSseStream(m.body,{onresumptiontoken:d},!1);else if(_?.includes("application/json")){let b=await m.json(),E=Array.isArray(b)?b.map(I=>Hc.parse(I)):[Hc.parse(b)];for(let I of E)(s=this.onmessage)===null||s===void 0||s.call(this,I)}else throw await((a=m.body)===null||a===void 0?void 0:a.cancel()),new As(-1,`Unexpected content type: ${_}`);else await((l=m.body)===null||l===void 0?void 0:l.cancel())}catch(u){throw(c=this.onerror)===null||c===void 0||c.call(this,u),u}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,n,i;if(this._sessionId)try{let o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},a=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(await((n=a.body)===null||n===void 0?void 0:n.cancel()),!a.ok&&a.status!==405)throw new As(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(i=this.onerror)===null||i===void 0||i.call(this,o),o}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Ky=class extends Event{constructor(e,r){var n,i;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(i=r?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(_M(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(_M(this),r)}};function s8(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function GS(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(GS).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${GS(t.cause)}`:t.message:`${t}`}function _M(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var wM=t=>{throw TypeError(t)},tI=(t,e,r)=>e.has(t)||wM("Cannot "+r),Ze=(t,e,r)=>(tI(t,e,"read from private field"),r?r.call(t):e.get(t)),er=(t,e,r)=>e.has(t)?wM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),Et=(t,e,r,n)=>(tI(t,e,"write to private field"),e.set(t,r),r),Co=(t,e,r)=>(tI(t,e,"access private method"),r),ln,Ja,Eu,Xy,Jy,Dp,Au,Lp,zs,Pu,zu,Tu,Mp,hi,HS,XS,KS,bM,JS,YS,jp,QS,eI,Ya=class extends EventTarget{constructor(e,r){var n,i;super(),er(this,hi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,er(this,ln),er(this,Ja),er(this,Eu),er(this,Xy),er(this,Jy),er(this,Dp),er(this,Au),er(this,Lp,null),er(this,zs),er(this,Pu),er(this,zu,null),er(this,Tu,null),er(this,Mp,null),er(this,XS,async o=>{var s;Ze(this,Pu).reset();let{body:a,redirected:l,status:c,headers:u}=o;if(c===204){Co(this,hi,jp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?Et(this,Eu,new URL(o.url)):Et(this,Eu,void 0),c!==200){Co(this,hi,jp).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){Co(this,hi,jp).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.OPEN);let d=new Event("open");if((s=Ze(this,Mp))==null||s.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){Co(this,hi,jp).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let p=new TextDecoder,f=a.getReader(),m=!0;do{let{done:h,value:y}=await f.read();y&&Ze(this,Pu).feed(p.decode(y,{stream:!h})),h&&(m=!1,Ze(this,Pu).reset(),Co(this,hi,QS).call(this))}while(m)}),er(this,KS,o=>{Et(this,zs,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Co(this,hi,QS).call(this,GS(o))}),er(this,JS,o=>{typeof o.id=="string"&&Et(this,Lp,o.id);let s=new MessageEvent(o.event||"message",{data:o.data,origin:Ze(this,Eu)?Ze(this,Eu).origin:Ze(this,Ja).origin,lastEventId:o.id||""});Ze(this,Tu)&&(!o.event||o.event==="message")&&Ze(this,Tu).call(this,s),this.dispatchEvent(s)}),er(this,YS,o=>{Et(this,Dp,o)}),er(this,eI,()=>{Et(this,Au,void 0),Ze(this,ln)===this.CONNECTING&&Co(this,hi,HS).call(this)});try{if(e instanceof URL)Et(this,Ja,e);else if(typeof e=="string")Et(this,Ja,new URL(e,a8()));else throw new Error("Invalid URL")}catch{throw s8("An invalid or illegal string was specified")}Et(this,Pu,By({onEvent:Ze(this,JS),onRetry:Ze(this,YS)})),Et(this,ln,this.CONNECTING),Et(this,Dp,3e3),Et(this,Jy,(n=r?.fetch)!=null?n:globalThis.fetch),Et(this,Xy,(i=r?.withCredentials)!=null?i:!1),Co(this,hi,HS).call(this)}get readyState(){return Ze(this,ln)}get url(){return Ze(this,Ja).href}get withCredentials(){return Ze(this,Xy)}get onerror(){return Ze(this,zu)}set onerror(e){Et(this,zu,e)}get onmessage(){return Ze(this,Tu)}set onmessage(e){Et(this,Tu,e)}get onopen(){return Ze(this,Mp)}set onopen(e){Et(this,Mp,e)}addEventListener(e,r,n){let i=r;super.addEventListener(e,i,n)}removeEventListener(e,r,n){let i=r;super.removeEventListener(e,i,n)}close(){Ze(this,Au)&&clearTimeout(Ze(this,Au)),Ze(this,ln)!==this.CLOSED&&(Ze(this,zs)&&Ze(this,zs).abort(),Et(this,ln,this.CLOSED),Et(this,zs,void 0))}};ln=new WeakMap,Ja=new WeakMap,Eu=new WeakMap,Xy=new WeakMap,Jy=new WeakMap,Dp=new WeakMap,Au=new WeakMap,Lp=new WeakMap,zs=new WeakMap,Pu=new WeakMap,zu=new WeakMap,Tu=new WeakMap,Mp=new WeakMap,hi=new WeakSet,HS=function(){Et(this,ln,this.CONNECTING),Et(this,zs,new AbortController),Ze(this,Jy)(Ze(this,Ja),Co(this,hi,bM).call(this)).then(Ze(this,XS)).catch(Ze(this,KS))},XS=new WeakMap,KS=new WeakMap,bM=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ze(this,Lp)?{"Last-Event-ID":Ze(this,Lp)}:void 0},cache:"no-store",signal:(t=Ze(this,zs))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},JS=new WeakMap,YS=new WeakMap,jp=function(t,e){var r;Ze(this,ln)!==this.CLOSED&&Et(this,ln,this.CLOSED);let n=new Ky("error",{code:e,message:t});(r=Ze(this,zu))==null||r.call(this,n),this.dispatchEvent(n)},QS=function(t,e){var r;if(Ze(this,ln)===this.CLOSED)return;Et(this,ln,this.CONNECTING);let n=new Ky("error",{code:e,message:t});(r=Ze(this,zu))==null||r.call(this,n),this.dispatchEvent(n),Et(this,Au,setTimeout(Ze(this,eI),Ze(this,Dp)))},eI=new WeakMap,Ya.CONNECTING=0,Ya.OPEN=1,Ya.CLOSED=2;function a8(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var rI=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Yy=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=qy(r?.fetch,r?.requestInit)}async _authThenStart(){var e;if(!this._authProvider)throw new Br("No auth provider");let r;try{r=await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw(e=this.onerror)===null||e===void 0||e.call(this,n),n}if(r!=="AUTHORIZED")throw new Br;return await this._startOrAuth()}async _commonHeaders(){var e;let r={};if(this._authProvider){let i=await this._authProvider.tokens();i&&(r.Authorization=`Bearer ${i.access_token}`)}this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);let n=Su((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...n})}_startOrAuth(){var e,r,n;let i=(n=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&n!==void 0?n:fetch;return new Promise((o,s)=>{this._eventSource=new Ya(this._url.href,{...this._eventSourceInit,fetch:async(a,l)=>{let c=await this._commonHeaders();c.set("Accept","text/event-stream");let u=await i(a,{...l,headers:c});if(u.status===401&&u.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:p}=Iu(u);this._resourceMetadataUrl=d,this._scope=p}return u}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{var l;if(a.code===401&&this._authProvider){this._authThenStart().then(o,s);return}let c=new rI(a.code,a.message,a);s(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{var l;let c=a;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){s(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}o()}),this._eventSource.onmessage=a=>{var l,c;let u=a,d;try{d=Hc.parse(JSON.parse(u.data))}catch(p){(l=this.onerror)===null||l===void 0||l.call(this,p);return}(c=this.onmessage)===null||c===void 0||c.call(this,d)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Br("No auth provider");if(await No(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br("Failed to authorize")}async close(){var e,r,n;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var r,n,i,o;if(!this._endpoint)throw new Error("Not connected");try{let s=await this._commonHeaders();s.set("content-type","application/json");let a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},l=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._endpoint,a);if(!l.ok){let c=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){let{resourceMetadataUrl:u,scope:d}=Iu(l);if(this._resourceMetadataUrl=u,this._scope=d,await No(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Br;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${l.status}): ${c}`)}await((i=l.body)===null||i===void 0?void 0:i.cancel())}catch(s){throw(o=this.onerror)===null||o===void 0||o.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}};var Fi={name:"@intelliweave/embedded",version:"2.0.72-beta.7",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6",vitest:"^3.2.4"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15",minisearch:"^6.3.0",openai:"^6.10.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};var tr=new Ve("MCPKnowledgeClient"),Qy=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){tr.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new $p({name:Fi.name,version:Fi.version}),n=new Hy(new URL(this.config.baseURL));return await r.connect(n),tr.debug("Connected with HTTP streaming mode"),r}).catch(async r=>{let n=new $p({name:Fi.name,version:Fi.version}),i=new Yy(new URL(this.config.baseURL));return await n.connect(i),tr.debug("Connected with SSE mode"),n});return await this.disconnect(),this.client=e,e.onerror=r=>{tr.error(`MCP client error: ${r.message}`)},e.onclose=()=>{tr.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(lx,r=>{r.params.level=="critical"?tr.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?tr.error(`[Server] ${r.params.data}`):r.params.level=="error"?tr.error(`[Server] ${r.params.data}`):r.params.level=="warning"?tr.warn(`[Server] ${r.params.data}`):r.params.level=="info"?tr.info(`[Server] ${r.params.data}`):r.params.level=="debug"?tr.debug(`[Server] ${r.params.data}`):tr.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(ax,r=>{tr.debug("Tool list changed",r),this.fetchTools()}),tr.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}tr.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,tr.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return tr.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),tr.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw tr.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var c8=new Ve("Statistics"),Up=[];async function Gr(t,e){let r={...e,event_id:dr(),event_date:new Date().toISOString(),sdk_version:Fi.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Up.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Up.length===0))return;let n=Up.slice();Up.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){c8.warn("Failed to submit analytics event:",i),Up.push(...n);return}}var Qa=new Ve("KnowledgeBase"),nI=1,ev=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>gP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${nI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&bt().knowledgeBaseSources&&(e=e.concat(bt().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Qa.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async c=>{try{let u=Date.now(),d=await c.query(e);return Qa.debug(`Source '${c.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Qa.warn(`Knowledge source '${c.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&bt().knowledgeBase&&(o=o.concat(bt().knowledgeBase)),o=o.filter(c=>c&&!c.disabled);for(let c=0;c<o.length;c++){let u=o[c];u.id=u.id||`temp.${c}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new hP({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let l=s.search(e).map(c=>o.find(u=>u.id==c.id));for(let c of o)c.isContext&&(l.find(u=>u.id===c.id)||l.push(c));return this.lastResults=l,Gr(this.ai,{event_type:"kb_search",value:l.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Qa.debug("Found results:",l),l}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${nI++}`),Qa.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(l,c)=>{Qa.debug(`Calling remote knowledge base action: ${l.id}`);let u={type:"action",userID:this.ai.userID,actionID:l.id,parameters:c},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let p=await d.json();return a(p.updateItems||[]),p.response},a=l=>{for(let c of l){if(!c.id){Qa.warn("KB item skipped since it has no ID.",c);continue}let u=n.find(d=>d.id==c.id);if(u){u.name=c.name||u.name||"",u.content=c.content||u.content||"",u.disabled=c.disabled??u.disabled,u.isContext=c.isContext??u.isContext,u.parameters=c.parameters||u.parameters||[],u.tags=c.tags||u.tags,u.type=c.type||u.type;continue}n.push({...c,action:d=>s(c,d)})}};this.registerSource(r,async l=>{if(o&&i.includes(l))return n;let c={type:"search",userID:this.ai?.userID||"",query:l},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(l)||i.push(l),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e.ensureInternalKnowledge(),e}registerMCPSource(e){e.id||(e.id=`external.${nI++}`);let r=new Qy(e);return this.registerSource(e.id,n=>r.search(n)),r}};var tv=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
96
+
97
+ Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
18
98
 
19
99
  Reply only with one of the following options:
20
- ${t.options.map(i=>`- "${i}"`).join(`
100
+ ${e.options.map(n=>`- "${n}"`).join(`
21
101
  `)}
22
102
 
23
- Do not include any additional text or explanations.`});return t.options.includes(e)?e:t.options.find(i=>e.toLowerCase().includes(i.toLowerCase()))}async extract(t){let e=`
24
- You will receive some data. Extraction instructions: ${t.instruction}
103
+ Do not include any additional text or explanations.`});return e.options.includes(r)?r:e.options.find(n=>r.toLowerCase().includes(n.toLowerCase()))}async extract(e){let r=`
104
+ You will receive some data. Extraction instructions: ${e.instruction}
25
105
 
26
- ${t.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
106
+ ${e.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
27
107
 
28
108
  Objects should have the following keys:
29
- ${t.extractions.map(o=>`- ${o.name} (${o.type}): ${o.description||"No description provided."}`).join(`
109
+ ${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No description provided."}`).join(`
30
110
  `)}
31
- `,i=await this.instruct({...t,instruction:e});if(i=i.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),t.allowMultiple){let o=i.split(`
32
- `).map(n=>n.trim()).filter(n=>!!n.trim()),s=[];for(let n of o)try{s.push(JSON.parse(n))}catch(a){console.error("Failed to parse line as JSON:",n,a.message)}return s}else return[JSON.parse(i.trim())]}async generateMarkdown(t){return this.instruct({...t,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(t){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>t.instruction,t.callback&&e.addEventListener("output",i=>{t.callback(i.detail.message)}),t.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof t.data=="string"?t.data:JSON.stringify(t.data)).then(i=>i.text())}};var E=class{constructor(t){this.messages=t}text(){return this.messages?.flatMap(t=>t.sections)?.filter(t=>t?.type=="text")?.map(t=>t?.text||"")?.filter(t=>!!t)?.join(`
111
+ `,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
112
+ `).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var Nu=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
33
113
 
34
- `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((t,e)=>t+(e.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((t,e)=>t+(e.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(t=>t.sections||[])||[]}toolCalls(){return this.messages?.flatMap(t=>t.sections?.filter(e=>e.type=="tool_call")||[])||[]}toolResult(t){return this.messages?.map(e=>e.sections?.find(i=>i.type=="tool_result"&&i.toolCallInstanceID==t)).filter(e=>!!e)[0]||null}};var se=class{constructor(t){this.subagents=[];this.cachedSubagents={};this.ai=t}register(t){if(this.subagents.find(e=>e.id==t.id))throw new Error(`Sub-agent with ID ${t.id} already exists`);this.subagents.push(t),this.ai.knowledgeBase.registerSource("subagent:"+t.id,e=>[{type:"action",id:"ask:"+t.id,name:`Ask ${t.name||"subagent"}`,content:t.usageInstructions||`Use this tool to ask ${t.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(i,o)=>await this.runQuery(t,i.query)}])}remove(t){this.subagents=this.subagents.filter(e=>e.id!=t),this.ai.knowledgeBase.removeSource("subagent:"+t)}async runQuery(t,e){let i=t.apiKey||this.ai.apiKey,o=this.cachedSubagents[i];return o||(o=new W,await o.load(i,t.config),this.cachedSubagents[i]=o),o=o.clone(),o.knowledgeBase.allowGlobalConfigSources=!1,o.knowledgeBase.allowWindowSources=!1,t.clearExistingKnowledge&&o.knowledgeBase.reset(),t.knowledge&&o.knowledgeBase.registerSource(t.knowledge),t.onAgentLoaded&&await t.onAgentLoaded(o),(await o.sendMessage(e)).text()}};var T=new p("Main"),Re=new Set,G=class G extends EventTarget{constructor(){super(...arguments);this.conversationID=Xe();this.knowledgeBase=new ie(this);this.subAgents=new se(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new oe(this);this.userID=Ae();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:G.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e,i){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{T.debug("Loading configuration...");let o=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!o.ok)throw new Error(`Failed to load configuration: ${o.status} ${o.statusText}`);try{this.config=await o.json(),T.debug("Config loaded successfully:",this.config),i&&(this.config={...this.config,...i}),this.config&&T.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(s){T.error("Failed to parse JSON response:",s);try{let n=await o.clone().text();T.error("Raw response that failed parsing:",n)}catch{T.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${s}`)}})(),(async()=>{try{let o=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!o.ok)throw new Error(`Failed to load VAD model: ${o.status} ${o.statusText}`);this.vadModel=await o.blob()}catch(o){T.warn(`Failed to load VAD model, some features will be unavailable. ${o.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let o of this.config.knowledge||[])o.url&&o.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:o.id,searchToolName:o.mcpSearchToolName,baseURL:o.url}):o.url&&this.knowledgeBase.registerSourceFromURL(o.url);for(let o of this.config.knowledge||[])o.entries?.length&&this.knowledgeBase.registerSource(o.id,()=>o.entries||[]);if(this.config.mcpServers)for(let o of this.config.mcpServers)this.knowledgeBase.registerMCPSource(o);for(let o of this.config.subagents||[])this.subAgents.register(o);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(o){throw T.warn("Failed to load:",o),this.error=o,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:o}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:o}})),o}}setModel(e){let i=this.models.find(s=>s.id==e);if(!i)throw new Error(`Model with ID "${e}" not found.`);let o={...i.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(s,n)=>{let a=this.knowledgeBase.getCachedEntry(s);this.onAIToolStart?.(a?.id||s,n)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(o):i.config.providerID==="anthropic"?this.currentModel=new ee(o):this.currentModel=new q(o),this.currentModel.id=i.id,this.currentModel.metadata=i}async getContextPrefix(){let e=m().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let i=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:i}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:Q(`
114
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var rv=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Cu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Vi=new Ve("Main"),xM=new Set,el=class el extends EventTarget{constructor(){super(...arguments);this.conversationID=dr();this.knowledgeBase=new ev(this);this.subAgents=new rv(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new tv(this);this.userID=b1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:el.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Vi.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Vi.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Vi.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Vi.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Vi.error("Raw response that failed parsing:",s)}catch{Vi.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Vi.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Vi.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Ah(i):this.currentModel=new ih(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=bt().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:rh(`
35
115
  # RAG search
36
116
  Use the \`search\` tool proactively as much as possible to find missing information or tools.
37
117
  Use the \`search\` tool when you are unsure about specific details or actions to take.
38
118
  Use the \`search\` tool if you are unable to complete the user's request.
39
119
  If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
40
- `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${e.length==0?`
120
+ `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${r.length==0?`
121
+
122
+ (no items found)`:""}`});for(let i of r)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=rh(i.content),s=!0;if(i.attachments?.length)for(let a of i.attachments)a.url&&(s&&(o+=`
41
123
 
42
- (no items found)`:""}`});for(let o of e)if(o.type=="info"||o.type=="tour"||o.type=="input-event"){let s=Q(o.content);this.currentModel.contextGroup.add({id:o.id,data:`## ${o.type}: ${o.name}
43
- ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="function"?o.disabled(this):o.disabled})}else if(o.type=="action"){let s={name:o._functionID,description:Q(o.content),params:Le(o.parameters||[{name:"value",type:"string",description:"Input"}]),callback:n=>this.toolRunKBAction(o,n),canRemove:!o.isContext,kbItem:o};this.currentModel.registerTool(s)}else continue}processIncomingMessage(e,i){if(!i){let o=this.currentModel?.stats?.tokensUsed||0,s=e.reduce((n,a)=>n+(a.usage?.totalTokens||0),0);y(this,{event_type:"message_receive",value:s,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:o}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:i,messages:e}})),this.onAIMessage?.(e,!!i)}async sendMessage(e,i){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),Re.has(this.conversationID)||(Re.add(this.conversationID),y(this,{event_type:"session_start"})),y(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e});let o=await this.currentModel.sendMessage(e),s=new E(o),n=this.currentModel.contextGroup.getAllAsString();n+=`
124
+ \`\`\`yaml
125
+ attachments:
126
+ `,s=!1),o+=`- name: "${a.name||""}"
127
+ mimetype: "${a.mimeType||""}"
128
+ url: "${a.url}"
129
+ `);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
130
+ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:rh(i.content),params:w1(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Gr(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:i}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),xM.has(this.conversationID)||(xM.add(this.conversationID),Gr(this,{event_type:"session_start"})),Gr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=await this.currentModel.sendMessage(r),o=new Nu(i),s=this.currentModel.contextGroup.getAllAsString();s+=`
44
131
 
45
132
  === TOOLS ===
46
133
 
47
134
  `+this.currentModel.toolGroup.getAll().map(a=>"- "+a.data?.name).join(`
48
- `),this._lastSystemMsg!=n&&(this._lastSystemMsg=n,this.submitAnalyticsEvent({type:"system-msg",txt:n}));for(let a of o)for(let l of a.sections||[])if(l.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:l.text||""});else if(l.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:l.text||""});else if(l.type=="tool_call"){let c=s.toolResult(l.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:l.toolKbID||"",actionName:l.toolKbName||"",value:l.toolParameters,result:c?.toolErrorResponse||c?.toolSuccessResponse,isError:!!c?.toolErrorResponse})}else l.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(e,i){let o=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:i,ai:this}}));let s=await e.action(i,this),n=Date.now()-o;return y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:n,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,result:s}})),s}catch(s){let n=Date.now()-o;throw y(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:i,execution_time_ms:n,success:!1,error_message:s.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:i,ai:this,error:s}})),s}}submitAnalyticsEvent(e){if(m().analytics===!1||this.config?.analytics===!1)return;let i=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(o=>{T.debug("Failed to submit analytics event:",o)});this.activeAnalyticsPromises.push(i),i.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(o=>o!==i)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=Xe(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let i of e.messages)this.currentModel.messageGroup.add(i)}clone(){let e=new G;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}get messages(){return this.currentModel?.messageGroup.items||[]}};G.version=I.version,G.builtInActionsVersion="1.0.0",T.debug(`Loaded: version=${I.version} builtInActionsVersion=${G.builtInActionsVersion}`);var W=G;var w=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},i=""){this.register();let o=document.createElement(this.tagName);for(let s in e)o.setAttribute(s,e[s]);return o.onBeforeCreate(),o.innerHTML=i,o}static add(e={},i=""){this.register();let o=s=>s.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(s=>`${s}="${o(e[s]+"")}"`).join(" ")}>${i}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,i,o){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,i)=>this.getAttribute(i.toString())||"",set:(e,i,o)=>(this.getAttribute(i.toString())===o||(o?this.setAttribute(i.toString(),o):this.removeAttribute(i.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,i)=>this._state[i],set:(e,i,o)=>(this._state[i]=o,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let i=this.root?.getElementById(e);if(!i)throw new Error(`Child with ID ${e} not found`);return i}};w.observedAttributes=[],w.tagName="",w._isRegistered=!1;var Ve='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Pe='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var je='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var B=class extends w{constructor(){super(...arguments);this.html=()=>`
135
+ `),this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}));for(let a of i)for(let l of a.sections||[])if(l.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:l.text||""});else if(l.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:l.text||""});else if(l.type=="tool_call"){let c=o.toolResult(l.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:l.toolKbID||"",actionName:l.toolKbName||"",value:l.toolParameters,result:c?.toolErrorResponse||c?.toolSuccessResponse,isError:!!c?.toolErrorResponse})}else l.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return o}finally{this.isProcessing=!1}}async toolRunKBAction(r,n){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:r,input:n,ai:this}}));let o=await r.action(n,this),s=Date.now()-i;return Gr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,result:o}})),o}catch(o){let s=Date.now()-i;throw Gr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(r){if(bt().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(i=>{Vi.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=dr(),this._lastSystemMsg="")}insertAssistantMessage(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(r)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(r?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${r.type}`);this.conversationID=r.conversationID;for(let n of r.messages)this.currentModel.messageGroup.add(n)}clone(){let r=new el;return r.apiKey=this.apiKey,r.config=this.config,r.models=this.models,this.config?.id&&r.setModel(this.config.id),r.audio=this.audio,r.vadModel=this.vadModel,r.userID=this.userID,r.knowledgeBase=this.knowledgeBase.clone(),r}get messages(){return this.currentModel?.messageGroup.items||[]}};el.version=Fi.version,el.builtInActionsVersion="1.0.0",Vi.debug(`Loaded: version=${Fi.version} builtInActionsVersion=${el.builtInActionsVersion}`);var Cu=el;var kn=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(r={},n=""){this.register();let i=document.createElement(this.tagName);for(let o in r)i.setAttribute(o,r[o]);return i.onBeforeCreate(),i.innerHTML=n,i}static add(r={},n=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(r).map(o=>`${o}="${i(r[o]+"")}"`).join(" ")}>${n}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(r,n,i){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(r,n)=>this.getAttribute(n.toString())||"",set:(r,n,i)=>(this.getAttribute(n.toString())===i||(i?this.setAttribute(n.toString(),i):this.removeAttribute(n.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(r,n)=>this._state[n],set:(r,n,i)=>(this._state[n]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(r){return!!this.root?.getElementById(r)}child(r){let n=this.root?.getElementById(r);if(!n)throw new Error(`Child with ID ${r} not found`);return n}};kn.observedAttributes=[],kn.tagName="",kn._isRegistered=!1;var $M='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var kM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var SM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Zp=class extends kn{constructor(){super(...arguments);this.html=()=>`
49
136
 
50
137
  <!-- Styling -->
51
138
  <style>
@@ -62,6 +149,11 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
62
149
  color: var(--intelliweave-text-color, white);
63
150
  }
64
151
 
152
+ /** Remove top border in fullscreen UI */
153
+ :host([layout="fullscreen"]) {
154
+ border-top: none;
155
+ }
156
+
65
157
  :host input {
66
158
  flex: 1 1 1px;
67
159
  border: none;
@@ -88,8 +180,39 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
88
180
  border: 1px solid rgba(255, 255, 255, 0.2);
89
181
  }
90
182
 
183
+ :host #send-button {
184
+ flex: 0 0 auto;
185
+ width: 34px;
186
+ height: 34px;
187
+ margin: 0 4px 0 0;
188
+ border-radius: 8px;
189
+ background-color: var(--intelliweave-persona-bg, var(--intelliweave-background, #4a6572));
190
+ border: none;
191
+ cursor: pointer;
192
+ display: flex;
193
+ align-items: center;
194
+ justify-content: center;
195
+ transition: opacity 0.15s ease;
196
+ }
197
+ :host #send-button svg {
198
+ width: 18px;
199
+ height: 18px;
200
+ fill: var(--intelliweave-text-color, white);
201
+ }
202
+
203
+ /** Remove send button background in widget UI */
204
+ :host([layout="widget"]) #send-button {
205
+ background-color: transparent;
206
+ opacity: 0.5;
207
+ }
208
+
209
+ /** Send button hover */
210
+ :host #send-button:hover {
211
+ opacity: 0.85;
212
+ }
213
+
91
214
  :host #loader {
92
- background-image: url('${Ve}');
215
+ background-image: url('${$M}');
93
216
  background-size: 64px 64px;
94
217
  background-position: center;
95
218
  background-repeat: no-repeat;
@@ -112,7 +235,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
112
235
  }
113
236
 
114
237
  :host #microphone-button {
115
- background-image: url('${Pe}');
238
+ background-image: url('${kM}');
116
239
  z-index: 2;
117
240
  margin-right: -10px;
118
241
  }
@@ -136,7 +259,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
136
259
  }
137
260
 
138
261
  :host #cancel-speech-button {
139
- background-image: url('${je}');
262
+ background-image: url('${SM}');
140
263
  z-index: 2;
141
264
  }
142
265
 
@@ -157,10 +280,17 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
157
280
  <!-- LLM button -->
158
281
  <div id='llm-button'>LLM</div>
159
282
 
283
+ <!-- Send button -->
284
+ <button id='send-button' type='button' aria-label='Send message'>
285
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
286
+ <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
287
+ </svg>
288
+ </button>
289
+
160
290
  <!-- Loader bar -->
161
291
  <div id='loader'></div>
162
292
 
163
- `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",i=>this.onSpeechEvent(i)),this.ai.audio?.speechRecognition.addEventListener("start",i=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",i=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",i=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",i=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(i=>i.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let i=this.child("input-field"),o=i.value?.trim();i.value="",o&&this.dispatchEvent(new CustomEvent("input-message",{detail:o}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let i=this.ai?.audio?.speechRecognition.volumeLevel||0,o=30,s=6,n=Math.round(i*(o-s)+s),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${n}px/2); left: 0px; width: 6px; height: ${n}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let i=this.voiceAnimationPieces[e];i.posX+=2,i.style.transform=`translate(${i.posX}px, 0px)`,!(i.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),i.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};B.observedAttributes=["loading","llmName","llmButtonVisible","textColor"];var ze='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var Y=class extends w{constructor(){super(...arguments);this.html=()=>`
293
+ `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",r=>this.onInputKeyPress(r),{capture:!0}),this.child("input-field").addEventListener("keydown",r=>r.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",r=>this.onLLMButtonClick(r)),this.child("send-button").addEventListener("click",r=>this.onSendButtonClick(r)),this.child("microphone-button").addEventListener("click",r=>this.onMicButtonClick(r)),this.child("cancel-speech-button").addEventListener("click",r=>this.onCancelSpeechButtonClick(r))}connectAI(r){this.ai=r,this.ai.audio?.speechRecognition.addEventListener("speech",n=>this.onSpeechEvent(n)),this.ai.audio?.speechRecognition.addEventListener("start",n=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",n=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let r=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;r&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!r&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(n=>n.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(r){if(r.stopPropagation(),r.key!="Enter")return;let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onLLMButtonClick(r){r.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(r){r.preventDefault();let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onMicButtonClick(r){r.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let r="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(r="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(r="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(r="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(r="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(r="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(r="rgba(0, 255, 0, 0.5)");let n=this.ai?.audio?.speechRecognition.volumeLevel||0,i=30,o=6,s=Math.round(n*(i-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${r}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let r=0;r<this.voiceAnimationPieces.length;r++){let n=this.voiceAnimationPieces[r];n.posX+=2,n.style.transform=`translate(${n.posX}px, 0px)`,!(n.posX<400)&&(this.voiceAnimationPieces.splice(r--,1),n.remove())}}}onSpeechEvent(r){this.attr.loading||r.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:r.detail.transcript}))}onCancelSpeechButtonClick(r){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};Zp.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var IM='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var Fp=class extends kn{constructor(){super(...arguments);this.html=()=>`
164
294
 
165
295
  <!-- Styling -->
166
296
  <style>
@@ -213,7 +343,32 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
213
343
  <!-- Logo -->
214
344
  <img id='root' />
215
345
 
216
- `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let i=this.attr.logo||ze;this._lastLogoSrc!=i&&(this._lastLogoSrc=i,e.src=i);let o=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(o){let s=window.visualViewport?.offsetTop||0,n=window.visualViewport?.offsetLeft||0,a=o.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+n)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+s)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};Y.observedAttributes=["logo","focusID"];import Ue from"rehype-external-links";import Ke from"rehype-format";import Fe from"rehype-stringify";import He from"remark-parse";import Je from"remark-rehype";import{unified as Qe}from"unified";var _=class extends w{constructor(){super(...arguments);this.html=()=>`
346
+ `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let r=this.child("root");if(!r)return;let n=this.attr.logo||IM;this._lastLogoSrc!=n&&(this._lastLogoSrc=n,r.src=n);let i=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(i){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=i.getBoundingClientRect();if(!a)return;r.classList.add("focused-mode"),r.style.width="128px",r.style.height="128px",r.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",r.style.top=Math.round(a.y+a.height/2-128/2+o)+"px"}else r.classList.remove("focused-mode"),r.style.width="",r.style.height="",r.style.left="",r.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};Fp.observedAttributes=["logo","focusID"];var EM=typeof self=="object"?self:globalThis,m8=(t,e)=>{let r=(i,o)=>(t.set(o,i),i),n=i=>{if(t.has(i))return t.get(i);let[o,s]=e[i];switch(o){case 0:case-1:return r(s,i);case 1:{let a=r([],i);for(let l of s)a.push(n(l));return a}case 2:{let a=r({},i);for(let[l,c]of s)a[n(l)]=n(c);return a}case 3:return r(new Date(s),i);case 4:{let{source:a,flags:l}=s;return r(new RegExp(a,l),i)}case 5:{let a=r(new Map,i);for(let[l,c]of s)a.set(n(l),n(c));return a}case 6:{let a=r(new Set,i);for(let l of s)a.add(n(l));return a}case 7:{let{name:a,message:l}=s;return r(new EM[a](l),i)}case 8:return r(BigInt(s),i);case"BigInt":return r(Object(BigInt(s)),i)}return r(new EM[o](s),i)};return n},aI=t=>m8(new Map,t)(0);var Ou="",{toString:h8}={},{keys:g8}=Object,Bp=t=>{let e=typeof t;if(e!=="object"||!t)return[0,e];let r=h8.call(t).slice(8,-1);switch(r){case"Array":return[1,Ou];case"Object":return[2,Ou];case"Date":return[3,Ou];case"RegExp":return[4,Ou];case"Map":return[5,Ou];case"Set":return[6,Ou]}return r.includes("Array")?[1,r]:r.includes("Error")?[7,r]:[2,r]},av=([t,e])=>t===0&&(e==="function"||e==="symbol"),y8=(t,e,r,n)=>{let i=(s,a)=>{let l=n.push(s)-1;return r.set(a,l),l},o=s=>{if(r.has(s))return r.get(s);let[a,l]=Bp(s);switch(a){case 0:{let u=s;switch(l){case"bigint":a=8,u=s.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+l);u=null;break;case"undefined":return i([-1],s)}return i([a,u],s)}case 1:{if(l)return i([l,[...s]],s);let u=[],d=i([a,u],s);for(let p of s)u.push(o(p));return d}case 2:{if(l)switch(l){case"BigInt":return i([l,s.toString()],s);case"Boolean":case"Number":case"String":return i([l,s.valueOf()],s)}if(e&&"toJSON"in s)return o(s.toJSON());let u=[],d=i([a,u],s);for(let p of g8(s))(t||!av(Bp(s[p])))&&u.push([o(p),o(s[p])]);return d}case 3:return i([a,s.toISOString()],s);case 4:{let{source:u,flags:d}=s;return i([a,{source:u,flags:d}],s)}case 5:{let u=[],d=i([a,u],s);for(let[p,f]of s)(t||!(av(Bp(p))||av(Bp(f))))&&u.push([o(p),o(f)]);return d}case 6:{let u=[],d=i([a,u],s);for(let p of s)(t||!av(Bp(p)))&&u.push(o(p));return d}}let{message:c}=s;return i([a,{name:l,message:c}],s)};return o},lI=(t,{json:e,lossy:r}={})=>{let n=[];return y8(!(e||r),!!e,new Map,n)(t),n};var qi=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?aI(lI(t,e)):structuredClone(t):(t,e)=>aI(lI(t,e));var Wi=function(t,e,r,n,i){let o=Bi(e);if(r!=null&&(typeof r!="number"||r<0||r===Number.POSITIVE_INFINITY))throw new Error("Expected positive finite `index`");if(n!=null&&(!n.type||!n.children))throw new Error("Expected valid `parent`");if(r==null!=(n==null))throw new Error("Expected both `index` and `parent`");return PM(t)?o.call(i,t,r,n):!1},Bi=function(t){if(t==null)return b8;if(typeof t=="string")return _8(t);if(typeof t=="object")return v8(t);if(typeof t=="function")return cI(t);throw new Error("Expected function, string, or array as `test`")};function v8(t){let e=[],r=-1;for(;++r<t.length;)e[r]=Bi(t[r]);return cI(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function _8(t){return cI(e);function e(r){return r.tagName===t}}function cI(t){return e;function e(r,n,i){return!!(PM(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function b8(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="element"&&"tagName"in t&&typeof t.tagName=="string")}function PM(t){return t!==null&&typeof t=="object"&&"type"in t&&"tagName"in t}var w8=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,x8=/^[a-zA-Z]:\\/;function uI(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return x8.test(t)?!1:w8.test(t)}function TM(t){let e=String(t||"").trim();return e?e.split(/[ \t\n\r\f]+/g):[]}function AM(t){return t.join(" ").trim()}var Ru=function(t){if(t==null)return I8;if(typeof t=="function")return lv(t);if(typeof t=="object")return Array.isArray(t)?$8(t):k8(t);if(typeof t=="string")return S8(t);throw new Error("Expected function, string, or object as test")};function $8(t){let e=[],r=-1;for(;++r<t.length;)e[r]=Ru(t[r]);return lv(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function k8(t){let e=t;return lv(r);function r(n){let i=n,o;for(o in t)if(i[o]!==e[o])return!1;return!0}}function S8(t){return lv(e);function e(r){return r&&r.type===t}}function lv(t){return e;function e(r,n,i){return!!(E8(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function I8(){return!0}function E8(t){return t!==null&&typeof t=="object"&&"type"in t}var zM=[],dI=!0,cv=!1,Gp="skip";function Hp(t,e,r,n){let i;typeof e=="function"&&typeof r!="function"?(n=r,r=e):i=e;let o=Ru(i),s=n?-1:1;a(t,void 0,[])();function a(l,c,u){let d=l&&typeof l=="object"?l:{};if(typeof d.type=="string"){let f=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(p,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return p;function p(){let f=zM,m,h,y;if((!e||o(l,c,u[u.length-1]||void 0))&&(f=P8(r(l,u)),f[0]===cv))return f;if("children"in l&&l.children){let g=l;if(g.children&&f[0]!==Gp)for(h=(n?g.children.length:-1)+s,y=u.concat(g);h>-1&&h<g.children.length;){let _=g.children[h];if(m=a(_,h,y)(),m[0]===cv)return m;h=typeof m[1]=="number"?m[1]:h+s}}return f}}}function P8(t){return Array.isArray(t)?t:typeof t=="number"?[dI,t]:t==null?zM:[t]}function Xp(t,e,r,n){let i,o,s;typeof e=="function"&&typeof r!="function"?(o=void 0,s=e,i=r):(o=e,s=r,i=n),Hp(t,o,a,i);function a(l,c){let u=c[c.length-1],d=u?u.children.indexOf(l):void 0;return s(l,d,u)}}var T8=["http","https"],A8=["nofollow"],z8={};function Jp(t){let e=t||z8,r=e.protocols||T8,n=Bi(e.test);return function(i){Xp(i,"element",function(o,s,a){if(o.tagName==="a"&&typeof o.properties.href=="string"&&n(o,s,a)){let l=o.properties.href;if(uI(l)?r.includes(l.slice(0,l.indexOf(":"))):l.startsWith("//")){let c=Kp(e.content,o),u=c&&!Array.isArray(c)?[c]:c,d=Kp(e.rel,o)||A8,p=typeof d=="string"?TM(d):d,f=Kp(e.target,o),m=Kp(e.properties,o);if(m&&Object.assign(o.properties,qi(m)),p.length>0&&(o.properties.rel=[...p]),f&&(o.properties.target=f),u){let h=Kp(e.contentProperties,o)||{};o.children.push({type:"element",tagName:"span",properties:qi(h),children:qi(u)})}}}})}}function Kp(t,e){return typeof t=="function"?t(e):t}var tl=Bi(function(t){return t.tagName==="audio"||t.tagName==="canvas"||t.tagName==="embed"||t.tagName==="iframe"||t.tagName==="img"||t.tagName==="math"||t.tagName==="object"||t.tagName==="picture"||t.tagName==="svg"||t.tagName==="video"});var N8={}.hasOwnProperty;function fI(t,e){let r=t.type==="element"&&N8.call(t.properties,e)&&t.properties[e];return r!=null&&r!==!1}var C8=new Set(["pingback","prefetch","stylesheet"]);function pI(t){if(t.type!=="element"||t.tagName!=="link")return!1;if(t.properties.itemProp)return!0;let e=t.properties.rel,r=-1;if(!Array.isArray(e)||e.length===0)return!1;for(;++r<e.length;)if(!C8.has(String(e[r])))return!1;return!0}var O8=Bi(["a","abbr","area","b","bdi","bdo","br","button","cite","code","data","datalist","del","dfn","em","i","input","ins","kbd","keygen","label","map","mark","meter","noscript","output","progress","q","ruby","s","samp","script","select","small","span","strong","sub","sup","template","textarea","time","u","var","wbr"]),R8=Bi("meta");function mI(t){return!!(t.type==="text"||O8(t)||tl(t)||pI(t)||R8(t)&&fI(t,"itemProp"))}var M8=/[ \t\n\f\r]/g;function Sn(t){return typeof t=="object"?t.type==="text"?NM(t.value):!1:NM(t)}function NM(t){return t.replace(M8,"")===""}var hI=["pre","script","style","textarea"];var CM=["address","article","aside","blockquote","body","br","caption","center","col","colgroup","dd","dialog","dir","div","dl","dt","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","legend","li","li","listing","main","menu","nav","ol","optgroup","option","p","plaintext","pre","section","summary","table","tbody","td","td","tfoot","th","th","thead","tr","ul","wbr","xmp"];var OM=["button","input","select","textarea"];var RM=["area","base","basefont","dialog","datalist","head","link","meta","noembed","noframes","param","rp","script","source","style","template","track","title"];var j8={},gI=Ru(["doctype","comment"]);function uv(t){let r=q8((t||j8).newlines?F8:V8);return function(n){jM(n,{collapse:r,whitespace:"normal"})}}function jM(t,e){if("children"in t){let r={...e};return(t.type==="root"||UM(t))&&(r.before=!0,r.after=!0),r.whitespace=W8(t,e),L8(t,r)}if(t.type==="text"){if(e.whitespace==="normal")return D8(t,e);e.whitespace==="nowrap"&&(t.value=e.collapse(t.value))}return{ignore:gI(t),stripAtStart:!1,remove:!1}}function D8(t,e){let r=e.collapse(t.value),n={ignore:!1,stripAtStart:!1,remove:!1},i=0,o=r.length;return e.before&&MM(r.charAt(0))&&i++,i!==o&&MM(r.charAt(o-1))&&(e.after?o--:n.stripAtStart=!0),i===o?n.remove=!0:t.value=r.slice(i,o),n}function L8(t,e){let r=e.before,n=e.after,i=t.children,o=i.length,s=-1;for(;++s<o;){let a=jM(i[s],{...e,after:DM(i,s,n),before:r});a.remove?(i.splice(s,1),s--,o--):a.ignore||(r=a.stripAtStart),LM(i[s])&&(r=!1)}return{ignore:!1,stripAtStart:!!(r||n),remove:!1}}function DM(t,e,r){for(;++e<t.length;){let n=t[e],i=U8(n);if(i===void 0&&"children"in n&&!Z8(n)&&(i=DM(n.children,-1)),typeof i=="boolean")return i}return r}function U8(t){if(t.type==="element"){if(LM(t))return!1;if(UM(t))return!0}else if(t.type==="text"){if(!Sn(t))return!1}else if(!gI(t))return!1}function LM(t){return tl(t)||Wi(t,OM)}function UM(t){return Wi(t,CM)}function Z8(t){return!!(t.type==="element"&&t.properties.hidden)||gI(t)||Wi(t,RM)}function MM(t){return t===" "||t===`
347
+ `}function F8(t){let e=/\r?\n|\r/.exec(t);return e?e[0]:" "}function V8(){return" "}function q8(t){return e;function e(r){return String(r).replace(/[\t\n\v\f\r ]+/g,t)}}function W8(t,e){if("tagName"in t&&t.properties)switch(t.tagName){case"listing":case"plaintext":case"script":case"style":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return t.properties.wrap?"pre-wrap":"pre";case"td":case"th":return t.properties.noWrap?"nowrap":e.whitespace;case"textarea":return"pre-wrap";default:}return e.whitespace}var B8={},G8=uv({newlines:!0});function Yp(t){let e=t||B8,r=e.indent||2,n=e.indentInitial;return typeof r=="number"&&(r=" ".repeat(r)),n==null&&(n=!0),function(s){let a;G8(s),Hp(s,function(l,c){let u=-1;if(!("children"in l))return;if(Wi(l,"head")&&(a=!0),a&&Wi(l,"body")&&(a=void 0),Wi(l,hI))return Gp;let d=l.children,p=c.length;if(d.length===0||!yI(l,a))return;n||p--;let f;for(;++u<d.length;){let y=d[u];(y.type==="text"||y.type==="comment")&&(y.value.includes(`
348
+ `)&&(f=!0),y.value=y.value.replace(/ *\n/g,"$&"+String(r).repeat(p)))}let m=[],h;for(u=-1;++u<d.length;){let y=d[u];(yI(y,a)||f&&!u)&&(i(m,p,y),f=!0),h=y,m.push(y)}h&&(f||yI(h,a))&&(Sn(h)&&(m.pop(),h=m[m.length-1]),i(m,p-1)),l.children=m})};function i(s,a,l){let c=s[s.length-1],u=c&&Sn(c)?s[s.length-2]:c,d=(o(u)&&o(l)?`
349
+
350
+ `:`
351
+ `)+String(r).repeat(Math.max(a,0));c&&c.type==="text"?c.value=Sn(c)?d:c.value+d:s.push({type:"text",value:d})}function o(s){return!!(s&&s.type==="element"&&e.blanks&&e.blanks.length>0&&e.blanks.includes(s.tagName))}}function yI(t,e){return t.type==="root"||(t.type==="element"?e||Wi(t,"script")||tl(t)||!mI(t):!1)}var ZM=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];var Oo=class{constructor(e,r,n){this.property=e,this.normal=r,n&&(this.space=n)}};Oo.prototype.property={};Oo.prototype.normal={};Oo.prototype.space=null;function vI(t,e){let r={},n={},i=-1;for(;++i<t.length;)Object.assign(r,t[i].property),Object.assign(n,t[i].normal);return new Oo(r,n,e)}function Qp(t){return t.toLowerCase()}var Rr=class{constructor(e,r){this.property=e,this.attribute=r}};Rr.prototype.space=null;Rr.prototype.boolean=!1;Rr.prototype.booleanish=!1;Rr.prototype.overloadedBoolean=!1;Rr.prototype.number=!1;Rr.prototype.commaSeparated=!1;Rr.prototype.spaceSeparated=!1;Rr.prototype.commaOrSpaceSeparated=!1;Rr.prototype.mustUseProperty=!1;Rr.prototype.defined=!1;var em={};Qu(em,{boolean:()=>ke,booleanish:()=>Ct,commaOrSpaceSeparated:()=>cn,commaSeparated:()=>Ns,number:()=>F,overloadedBoolean:()=>_I,spaceSeparated:()=>lt});var H8=0,ke=rl(),Ct=rl(),_I=rl(),F=rl(),lt=rl(),Ns=rl(),cn=rl();function rl(){return 2**++H8}var bI=Object.keys(em),nl=class extends Rr{constructor(e,r,n,i){let o=-1;if(super(e,r),FM(this,"space",i),typeof n=="number")for(;++o<bI.length;){let s=bI[o];FM(this,bI[o],(n&em[s])===em[s])}}};nl.prototype.defined=!0;function FM(t,e,r){r&&(t[e]=r)}var X8={}.hasOwnProperty;function Wn(t){let e={},r={},n;for(n in t.properties)if(X8.call(t.properties,n)){let i=t.properties[n],o=new nl(n,t.transform(t.attributes||{},n),i,t.space);t.mustUseProperty&&t.mustUseProperty.includes(n)&&(o.mustUseProperty=!0),e[n]=o,r[Qp(n)]=n,r[Qp(o.attribute)]=n}return new Oo(e,r,t.space)}var wI=Wn({space:"xlink",transform(t,e){return"xlink:"+e.slice(5).toLowerCase()},properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}});var xI=Wn({space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()},properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function dv(t,e){return e in t?t[e]:e}function fv(t,e){return dv(t,e.toLowerCase())}var $I=Wn({space:"xmlns",attributes:{xmlnsxlink:"xmlns:xlink"},transform:fv,properties:{xmlns:null,xmlnsXLink:null}});var kI=Wn({transform(t,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()},properties:{ariaActiveDescendant:null,ariaAtomic:Ct,ariaAutoComplete:null,ariaBusy:Ct,ariaChecked:Ct,ariaColCount:F,ariaColIndex:F,ariaColSpan:F,ariaControls:lt,ariaCurrent:null,ariaDescribedBy:lt,ariaDetails:null,ariaDisabled:Ct,ariaDropEffect:lt,ariaErrorMessage:null,ariaExpanded:Ct,ariaFlowTo:lt,ariaGrabbed:Ct,ariaHasPopup:null,ariaHidden:Ct,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:lt,ariaLevel:F,ariaLive:null,ariaModal:Ct,ariaMultiLine:Ct,ariaMultiSelectable:Ct,ariaOrientation:null,ariaOwns:lt,ariaPlaceholder:null,ariaPosInSet:F,ariaPressed:Ct,ariaReadOnly:Ct,ariaRelevant:null,ariaRequired:Ct,ariaRoleDescription:lt,ariaRowCount:F,ariaRowIndex:F,ariaRowSpan:F,ariaSelected:Ct,ariaSetSize:F,ariaSort:null,ariaValueMax:F,ariaValueMin:F,ariaValueNow:F,ariaValueText:null,role:null}});var VM=Wn({space:"html",attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},transform:fv,mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ns,acceptCharset:lt,accessKey:lt,action:null,allow:null,allowFullScreen:ke,allowPaymentRequest:ke,allowUserMedia:ke,alt:null,as:null,async:ke,autoCapitalize:null,autoComplete:lt,autoFocus:ke,autoPlay:ke,blocking:lt,capture:null,charSet:null,checked:ke,cite:null,className:lt,cols:F,colSpan:null,content:null,contentEditable:Ct,controls:ke,controlsList:lt,coords:F|Ns,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ke,defer:ke,dir:null,dirName:null,disabled:ke,download:_I,draggable:Ct,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ke,formTarget:null,headers:lt,height:F,hidden:ke,high:F,href:null,hrefLang:null,htmlFor:lt,httpEquiv:lt,id:null,imageSizes:null,imageSrcSet:null,inert:ke,inputMode:null,integrity:null,is:null,isMap:ke,itemId:null,itemProp:lt,itemRef:lt,itemScope:ke,itemType:lt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ke,low:F,manifest:null,max:null,maxLength:F,media:null,method:null,min:null,minLength:F,multiple:ke,muted:ke,name:null,nonce:null,noModule:ke,noValidate:ke,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:ke,optimum:F,pattern:null,ping:lt,placeholder:null,playsInline:ke,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ke,referrerPolicy:null,rel:lt,required:ke,reversed:ke,rows:F,rowSpan:F,sandbox:lt,scope:null,scoped:ke,seamless:ke,selected:ke,shadowRootClonable:ke,shadowRootDelegatesFocus:ke,shadowRootMode:null,shape:null,size:F,sizes:null,slot:null,span:F,spellCheck:Ct,src:null,srcDoc:null,srcLang:null,srcSet:null,start:F,step:null,style:null,tabIndex:F,target:null,title:null,translate:null,type:null,typeMustMatch:ke,useMap:null,value:Ct,width:F,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:lt,axis:null,background:null,bgColor:null,border:F,borderColor:null,bottomMargin:F,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ke,declare:ke,event:null,face:null,frame:null,frameBorder:null,hSpace:F,leftMargin:F,link:null,longDesc:null,lowSrc:null,marginHeight:F,marginWidth:F,noResize:ke,noHref:ke,noShade:ke,noWrap:ke,object:null,profile:null,prompt:null,rev:null,rightMargin:F,rules:null,scheme:null,scrolling:Ct,standby:null,summary:null,text:null,topMargin:F,valueType:null,version:null,vAlign:null,vLink:null,vSpace:F,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ke,disableRemotePlayback:ke,prefix:null,property:null,results:F,security:null,unselectable:null}});var qM=Wn({space:"svg",attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},transform:dv,properties:{about:cn,accentHeight:F,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:F,amplitude:F,arabicForm:null,ascent:F,attributeName:null,attributeType:null,azimuth:F,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:F,by:null,calcMode:null,capHeight:F,className:lt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:F,diffuseConstant:F,direction:null,display:null,dur:null,divisor:F,dominantBaseline:null,download:ke,dx:null,dy:null,edgeMode:null,editable:null,elevation:F,enableBackground:null,end:null,event:null,exponent:F,externalResourcesRequired:null,fill:null,fillOpacity:F,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ns,g2:Ns,glyphName:Ns,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:F,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:F,horizOriginX:F,horizOriginY:F,id:null,ideographic:F,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:F,k:F,k1:F,k2:F,k3:F,k4:F,kernelMatrix:cn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:F,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:F,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:F,overlineThickness:F,paintOrder:null,panose1:null,path:null,pathLength:F,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:lt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:F,pointsAtY:F,pointsAtZ:F,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:cn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:cn,rev:cn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:cn,requiredFeatures:cn,requiredFonts:cn,requiredFormats:cn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:F,specularExponent:F,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:F,strikethroughThickness:F,string:null,stroke:null,strokeDashArray:cn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:F,strokeOpacity:F,strokeWidth:null,style:null,surfaceScale:F,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:cn,tabIndex:F,tableValues:null,target:null,targetX:F,targetY:F,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:cn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:F,underlineThickness:F,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:F,values:null,vAlphabetic:F,vMathematical:F,vectorEffect:null,vHanging:F,vIdeographic:F,version:null,vertAdvY:F,vertOriginX:F,vertOriginY:F,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:F,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null}});var K8=/^data[-\w.:]+$/i,WM=/-[a-z]/g,J8=/[A-Z]/g;function SI(t,e){let r=Qp(e),n=e,i=Rr;if(r in t.normal)return t.property[t.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&K8.test(e)){if(e.charAt(4)==="-"){let o=e.slice(5).replace(WM,Q8);n="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=e.slice(4);if(!WM.test(o)){let s=o.replace(J8,Y8);s.charAt(0)!=="-"&&(s="-"+s),e="data"+s}}i=nl}return new i(n,e)}function Y8(t){return"-"+t.toLowerCase()}function Q8(t){return t.charAt(1).toUpperCase()}var BM=vI([xI,wI,$I,kI,VM],"html"),pv=vI([xI,wI,$I,kI,qM],"svg");var GM={}.hasOwnProperty;function HM(t,e){let r=e||{};function n(i,...o){let s=n.invalid,a=n.handlers;if(i&&GM.call(i,t)){let l=String(i[t]);s=GM.call(a,l)?a[l]:n.unknown}if(s)return s.call(this,i,...o)}return n.handlers=r.handlers||{},n.invalid=r.invalid,n.unknown=r.unknown,n}var eJ=/["&'<>`]/g,tJ=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,rJ=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,nJ=/[|\\{}()[\]^$+*?.]/g,XM=new WeakMap;function KM(t,e){if(t=t.replace(e.subset?iJ(e.subset):eJ,n),e.subset||e.escapeOnly)return t;return t.replace(tJ,r).replace(rJ,n);function r(i,o,s){return e.format((i.charCodeAt(0)-55296)*1024+i.charCodeAt(1)-56320+65536,s.charCodeAt(o+2),e)}function n(i,o,s){return e.format(i.charCodeAt(0),s.charCodeAt(o+1),e)}}function iJ(t){let e=XM.get(t);return e||(e=oJ(t),XM.set(t,e)),e}function oJ(t){let e=[],r=-1;for(;++r<t.length;)e.push(t[r].replace(nJ,"\\$&"));return new RegExp("(?:"+e.join("|")+")","g")}var sJ=/[\dA-Fa-f]/;function JM(t,e,r){let n="&#x"+t.toString(16).toUpperCase();return r&&e&&!sJ.test(String.fromCharCode(e))?n:n+";"}var aJ=/\d/;function YM(t,e,r){let n="&#"+String(t);return r&&e&&!aJ.test(String.fromCharCode(e))?n:n+";"}var QM=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var mv={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var ej=["cent","copy","divide","gt","lt","not","para","times"];var tj={}.hasOwnProperty,II={},hv;for(hv in mv)tj.call(mv,hv)&&(II[mv[hv]]=hv);var lJ=/[^\dA-Za-z]/;function rj(t,e,r,n){let i=String.fromCharCode(t);if(tj.call(II,i)){let o=II[i],s="&"+o;return r&&QM.includes(o)&&!ej.includes(o)&&(!n||e&&e!==61&&lJ.test(String.fromCharCode(e)))?s:s+";"}return""}function nj(t,e,r){let n=JM(t,e,r.omitOptionalSemicolons),i;if((r.useNamedReferences||r.useShortestReferences)&&(i=rj(t,e,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!i)&&r.useShortestReferences){let o=YM(t,e,r.omitOptionalSemicolons);o.length<n.length&&(n=o)}return i&&(!r.useShortestReferences||i.length<n.length)?i:n}function Ro(t,e){return KM(t,Object.assign({format:nj},e))}var cJ=/^>|^->|<!--|-->|--!>|<!-$/g,uJ=[">"],dJ=["<",">"];function ij(t,e,r,n){return n.settings.bogusComments?"<?"+Ro(t.value,Object.assign({},n.settings.characterReferences,{subset:uJ}))+">":"<!--"+t.value.replace(cJ,i)+"-->";function i(o){return Ro(o,Object.assign({},n.settings.characterReferences,{subset:dJ}))}}function oj(t,e,r,n){return"<!"+(n.settings.upperDoctype?"DOCTYPE":"doctype")+(n.settings.tightDoctype?"":" ")+"html>"}function EI(t,e){let r=String(t);if(typeof e!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(e);for(;i!==-1;)n++,i=r.indexOf(e,i+e.length);return n}function sj(t,e){let r=e||{};return(t[t.length-1]===""?[...t,""]:t).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}var Zt=aj(1),PI=aj(-1),fJ=[];function aj(t){return e;function e(r,n,i){let o=r?r.children:fJ,s=(n||0)+t,a=o[s];if(!i)for(;a&&Sn(a);)s+=t,a=o[s];return a}}var pJ={}.hasOwnProperty;function gv(t){return e;function e(r,n,i){return pJ.call(t,r.tagName)&&t[r.tagName](r,n,i)}}var tm=gv({body:hJ,caption:TI,colgroup:TI,dd:_J,dt:vJ,head:TI,html:mJ,li:yJ,optgroup:bJ,option:wJ,p:gJ,rp:lj,rt:lj,tbody:$J,td:cj,tfoot:kJ,th:cj,thead:xJ,tr:SJ});function TI(t,e,r){let n=Zt(r,e,!0);return!n||n.type!=="comment"&&!(n.type==="text"&&Sn(n.value.charAt(0)))}function mJ(t,e,r){let n=Zt(r,e);return!n||n.type!=="comment"}function hJ(t,e,r){let n=Zt(r,e);return!n||n.type!=="comment"}function gJ(t,e,r){let n=Zt(r,e);return n?n.type==="element"&&(n.tagName==="address"||n.tagName==="article"||n.tagName==="aside"||n.tagName==="blockquote"||n.tagName==="details"||n.tagName==="div"||n.tagName==="dl"||n.tagName==="fieldset"||n.tagName==="figcaption"||n.tagName==="figure"||n.tagName==="footer"||n.tagName==="form"||n.tagName==="h1"||n.tagName==="h2"||n.tagName==="h3"||n.tagName==="h4"||n.tagName==="h5"||n.tagName==="h6"||n.tagName==="header"||n.tagName==="hgroup"||n.tagName==="hr"||n.tagName==="main"||n.tagName==="menu"||n.tagName==="nav"||n.tagName==="ol"||n.tagName==="p"||n.tagName==="pre"||n.tagName==="section"||n.tagName==="table"||n.tagName==="ul"):!r||!(r.type==="element"&&(r.tagName==="a"||r.tagName==="audio"||r.tagName==="del"||r.tagName==="ins"||r.tagName==="map"||r.tagName==="noscript"||r.tagName==="video"))}function yJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="li"}function vJ(t,e,r){let n=Zt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd"))}function _J(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd")}function lj(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="rp"||n.tagName==="rt")}function bJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="optgroup"}function wJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="option"||n.tagName==="optgroup")}function xJ(t,e,r){let n=Zt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot"))}function $J(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot")}function kJ(t,e,r){return!Zt(r,e)}function SJ(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&n.tagName==="tr"}function cj(t,e,r){let n=Zt(r,e);return!n||n.type==="element"&&(n.tagName==="td"||n.tagName==="th")}var uj=gv({body:PJ,colgroup:TJ,head:EJ,html:IJ,tbody:AJ});function IJ(t){let e=Zt(t,-1);return!e||e.type!=="comment"}function EJ(t){let e=t.children,r=[],n=-1;for(;++n<e.length;){let i=e[n];if(i.type==="element"&&(i.tagName==="title"||i.tagName==="base")){if(r.includes(i.tagName))return!1;r.push(i.tagName)}}return e.length>0}function PJ(t){let e=Zt(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&Sn(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function TJ(t,e,r){let n=PI(r,e),i=Zt(t,-1,!0);return r&&n&&n.type==="element"&&n.tagName==="colgroup"&&tm(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="col")}function AJ(t,e,r){let n=PI(r,e),i=Zt(t,-1);return r&&n&&n.type==="element"&&(n.tagName==="thead"||n.tagName==="tbody")&&tm(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="tr")}var yv={name:[[`
352
+ \f\r &/=>`.split(""),`
353
+ \f\r "&'/=>\``.split("")],[`\0
354
+ \f\r "&'/<=>`.split(""),`\0
355
+ \f\r "&'/<=>\``.split("")]],unquoted:[[`
356
+ \f\r &>`.split(""),`\0
357
+ \f\r "&'<=>\``.split("")],[`\0
358
+ \f\r "&'<=>\``.split(""),`\0
359
+ \f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function dj(t,e,r,n){let i=n.schema,o=i.space==="svg"?!1:n.settings.omitOptionalTags,s=i.space==="svg"?n.settings.closeEmptyElements:n.settings.voids.includes(t.tagName.toLowerCase()),a=[],l;i.space==="html"&&t.tagName==="svg"&&(n.schema=pv);let c=zJ(n,t.properties),u=n.all(i.space==="html"&&t.tagName==="template"?t.content:t);return n.schema=i,u&&(s=!1),(c||!o||!uj(t,e,r))&&(a.push("<",t.tagName,c?" "+c:""),s&&(i.space==="svg"||n.settings.closeSelfClosing)&&(l=c.charAt(c.length-1),(!n.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&a.push(" "),a.push("/")),a.push(">")),a.push(u),!s&&(!o||!tm(t,e,r))&&a.push("</"+t.tagName+">"),a.join("")}function zJ(t,e){let r=[],n=-1,i;if(e){for(i in e)if(e[i]!==null&&e[i]!==void 0){let o=NJ(t,i,e[i]);o&&r.push(o)}}for(;++n<r.length;){let o=t.settings.tightAttributes?r[n].charAt(r[n].length-1):void 0;n!==r.length-1&&o!=='"'&&o!=="'"&&(r[n]+=" ")}return r.join("")}function NJ(t,e,r){let n=SI(t.schema,e),i=t.settings.allowParseErrors&&t.schema.space==="html"?0:1,o=t.settings.allowDangerousCharacters?0:1,s=t.quote,a;if(n.overloadedBoolean&&(r===n.attribute||r==="")?r=!0:(n.boolean||n.overloadedBoolean&&typeof r!="string")&&(r=!!r),r==null||r===!1||typeof r=="number"&&Number.isNaN(r))return"";let l=Ro(n.attribute,Object.assign({},t.settings.characterReferences,{subset:yv.name[i][o]}));return r===!0||(r=Array.isArray(r)?(n.commaSeparated?sj:AM)(r,{padLeft:!t.settings.tightCommaSeparatedLists}):String(r),t.settings.collapseEmptyAttributes&&!r)?l:(t.settings.preferUnquoted&&(a=Ro(r,Object.assign({},t.settings.characterReferences,{attribute:!0,subset:yv.unquoted[i][o]}))),a!==r&&(t.settings.quoteSmart&&EI(r,s)>EI(r,t.alternative)&&(s=t.alternative),a=s+Ro(r,Object.assign({},t.settings.characterReferences,{subset:(s==="'"?yv.single:yv.double)[i][o],attribute:!0}))+s),l+(a&&"="+a))}var CJ=["<","&"];function vv(t,e,r,n){return r&&r.type==="element"&&(r.tagName==="script"||r.tagName==="style")?t.value:Ro(t.value,Object.assign({},n.settings.characterReferences,{subset:CJ}))}function fj(t,e,r,n){return n.settings.allowDangerousHtml?t.value:vv(t,e,r,n)}function pj(t,e,r,n){return n.all(t)}var mj=HM("type",{invalid:OJ,unknown:RJ,handlers:{comment:ij,doctype:oj,element:dj,raw:fj,root:pj,text:vv}});function OJ(t){throw new Error("Expected node, not `"+t+"`")}function RJ(t){let e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}var MJ={},jJ={},DJ=[];function AI(t,e){let r=e||MJ,n=r.quote||'"',i=n==='"'?"'":'"';if(n!=='"'&&n!=="'")throw new Error("Invalid quote `"+n+"`, expected `'` or `\"`");return{one:LJ,all:UJ,settings:{omitOptionalTags:r.omitOptionalTags||!1,allowParseErrors:r.allowParseErrors||!1,allowDangerousCharacters:r.allowDangerousCharacters||!1,quoteSmart:r.quoteSmart||!1,preferUnquoted:r.preferUnquoted||!1,tightAttributes:r.tightAttributes||!1,upperDoctype:r.upperDoctype||!1,tightDoctype:r.tightDoctype||!1,bogusComments:r.bogusComments||!1,tightCommaSeparatedLists:r.tightCommaSeparatedLists||!1,tightSelfClosing:r.tightSelfClosing||!1,collapseEmptyAttributes:r.collapseEmptyAttributes||!1,allowDangerousHtml:r.allowDangerousHtml||!1,voids:r.voids||ZM,characterReferences:r.characterReferences||jJ,closeSelfClosing:r.closeSelfClosing||!1,closeEmptyElements:r.closeEmptyElements||!1},schema:r.space==="svg"?pv:BM,quote:n,alternative:i}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function LJ(t,e,r){return mj(t,e,r,this)}function UJ(t){let e=[],r=t&&t.children||DJ,n=-1;for(;++n<r.length;)e[n]=this.one(r[n],n,t);return e.join("")}function rm(t){let e=this,r={...e.data("settings"),...t};e.compiler=n;function n(i){return AI(i,r)}}var ZJ={};function zI(t,e){let r=e||ZJ,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return gj(t,n,i)}function gj(t,e,r){if(FJ(t)){if("value"in t)return t.type==="html"&&!r?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return hj(t.children,e,r)}return Array.isArray(t)?hj(t,e,r):""}function hj(t,e,r){let n=[],i=-1;for(;++i<t.length;)n[i]=gj(t[i],e,r);return n.join("")}function FJ(t){return!!(t&&typeof t=="object")}var yj=document.createElement("i");function Mu(t){let e="&"+t+";";yj.innerHTML=e;let r=yj.textContent;return r.charCodeAt(r.length-1)===59&&t!=="semi"||r===e?!1:r}function Mr(t,e,r,n){let i=t.length,o=0,s;if(e<0?e=-e>i?0:i+e:e=e>i?i:e,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(e,r),t.splice(...s);else for(r&&t.splice(e,r);o<n.length;)s=n.slice(o,o+1e4),s.unshift(e,0),t.splice(...s),o+=1e4,e+=1e4}function Hr(t,e){return t.length>0?(Mr(t,t.length,0,e),t):e}var vj={}.hasOwnProperty;function _j(t){let e={},r=-1;for(;++r<t.length;)VJ(e,t[r]);return e}function VJ(t,e){let r;for(r in e){let i=(vj.call(t,r)?t[r]:void 0)||(t[r]={}),o=e[r],s;if(o)for(s in o){vj.call(i,s)||(i[s]=[]);let a=o[s];qJ(i[s],Array.isArray(a)?a:a?[a]:[])}}}function qJ(t,e){let r=-1,n=[];for(;++r<e.length;)(e[r].add==="after"?t:n).push(e[r]);Mr(t,0,0,n)}function _v(t,e){let r=Number.parseInt(t,e);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"\uFFFD":String.fromCodePoint(r)}function Mo(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var In=Cs(/[A-Za-z]/),sr=Cs(/[\dA-Za-z]/),bj=Cs(/[#-'*+\--9=?A-Z^-~]/);function nm(t){return t!==null&&(t<32||t===127)}var im=Cs(/\d/),wj=Cs(/[\dA-Fa-f]/),xj=Cs(/[!-/:-@[-`{-~]/);function ne(t){return t!==null&&t<-2}function Ft(t){return t!==null&&(t<0||t===32)}function Se(t){return t===-2||t===-1||t===32}var $j=Cs(/\p{P}|\p{S}/u),kj=Cs(/\s/);function Cs(t){return e;function e(r){return r!==null&&r>-1&&t.test(String.fromCharCode(r))}}function Bn(t){let e=[],r=-1,n=0,i=0;for(;++r<t.length;){let o=t.charCodeAt(r),s="";if(o===37&&sr(t.charCodeAt(r+1))&&sr(t.charCodeAt(r+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(s=String.fromCharCode(o));else if(o>55295&&o<57344){let a=t.charCodeAt(r+1);o<56320&&a>56319&&a<57344?(s=String.fromCharCode(o,a),i=1):s="\uFFFD"}else s=String.fromCharCode(o);s&&(e.push(t.slice(n,r),encodeURIComponent(s)),n=r+i+1,s=""),i&&(r+=i,i=0)}return e.join("")+t.slice(n)}function Ie(t,e,r,n){let i=n?n-1:Number.POSITIVE_INFINITY,o=0;return s;function s(l){return Se(l)?(t.enter(r),a(l)):e(l)}function a(l){return Se(l)&&o++<i?(t.consume(l),a):(t.exit(r),e(l))}}var Sj={tokenize:WJ};function WJ(t){let e=t.attempt(this.parser.constructs.contentInitial,n,i),r;return e;function n(a){if(a===null){t.consume(a);return}return t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),Ie(t,e,"linePrefix")}function i(a){return t.enter("paragraph"),o(a)}function o(a){let l=t.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(a)}function s(a){if(a===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(a);return}return ne(a)?(t.consume(a),t.exit("chunkText"),o):(t.consume(a),s)}}var Ej={tokenize:BJ},Ij={tokenize:GJ};function BJ(t){let e=this,r=[],n=0,i,o,s;return a;function a(b){if(n<r.length){let E=r[n];return e.containerState=E[1],t.attempt(E[0].continuation,l,c)(b)}return c(b)}function l(b){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,i&&_();let E=e.events.length,I=E,P;for(;I--;)if(e.events[I][0]==="exit"&&e.events[I][1].type==="chunkFlow"){P=e.events[I][1].end;break}g(n);let M=E;for(;M<e.events.length;)e.events[M][1].end=Object.assign({},P),M++;return Mr(e.events,I+1,0,e.events.slice(E)),e.events.length=M,c(b)}return a(b)}function c(b){if(n===r.length){if(!i)return p(b);if(i.currentConstruct&&i.currentConstruct.concrete)return m(b);e.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return e.containerState={},t.check(Ij,u,d)(b)}function u(b){return i&&_(),g(n),p(b)}function d(b){return e.parser.lazy[e.now().line]=n!==r.length,s=e.now().offset,m(b)}function p(b){return e.containerState={},t.attempt(Ij,f,m)(b)}function f(b){return n++,r.push([e.currentConstruct,e.containerState]),p(b)}function m(b){if(b===null){i&&_(),g(0),t.consume(b);return}return i=i||e.parser.flow(e.now()),t.enter("chunkFlow",{contentType:"flow",previous:o,_tokenizer:i}),h(b)}function h(b){if(b===null){y(t.exit("chunkFlow"),!0),g(0),t.consume(b);return}return ne(b)?(t.consume(b),y(t.exit("chunkFlow")),n=0,e.interrupt=void 0,a):(t.consume(b),h)}function y(b,E){let I=e.sliceStream(b);if(E&&I.push(null),b.previous=o,o&&(o.next=b),o=b,i.defineSkip(b.start),i.write(I),e.parser.lazy[b.start.line]){let P=i.events.length;for(;P--;)if(i.events[P][1].start.offset<s&&(!i.events[P][1].end||i.events[P][1].end.offset>s))return;let M=e.events.length,V=M,R,L;for(;V--;)if(e.events[V][0]==="exit"&&e.events[V][1].type==="chunkFlow"){if(R){L=e.events[V][1].end;break}R=!0}for(g(n),P=M;P<e.events.length;)e.events[P][1].end=Object.assign({},L),P++;Mr(e.events,V+1,0,e.events.slice(M)),e.events.length=P}}function g(b){let E=r.length;for(;E-- >b;){let I=r[E];e.containerState=I[1],I[0].exit.call(e,t)}r.length=b}function _(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function GJ(t,e,r){return Ie(t,t.attempt(this.parser.constructs.document,e,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function NI(t){if(t===null||Ft(t)||kj(t))return 1;if($j(t))return 2}function ju(t,e,r){let n=[],i=-1;for(;++i<t.length;){let o=t[i].resolveAll;o&&!n.includes(o)&&(e=o(e,r),n.push(o))}return e}var om={name:"attention",tokenize:XJ,resolveAll:HJ};function HJ(t,e){let r=-1,n,i,o,s,a,l,c,u;for(;++r<t.length;)if(t[r][0]==="enter"&&t[r][1].type==="attentionSequence"&&t[r][1]._close){for(n=r;n--;)if(t[n][0]==="exit"&&t[n][1].type==="attentionSequence"&&t[n][1]._open&&e.sliceSerialize(t[n][1]).charCodeAt(0)===e.sliceSerialize(t[r][1]).charCodeAt(0)){if((t[n][1]._close||t[r][1]._open)&&(t[r][1].end.offset-t[r][1].start.offset)%3&&!((t[n][1].end.offset-t[n][1].start.offset+t[r][1].end.offset-t[r][1].start.offset)%3))continue;l=t[n][1].end.offset-t[n][1].start.offset>1&&t[r][1].end.offset-t[r][1].start.offset>1?2:1;let d=Object.assign({},t[n][1].end),p=Object.assign({},t[r][1].start);Pj(d,-l),Pj(p,l),s={type:l>1?"strongSequence":"emphasisSequence",start:d,end:Object.assign({},t[n][1].end)},a={type:l>1?"strongSequence":"emphasisSequence",start:Object.assign({},t[r][1].start),end:p},o={type:l>1?"strongText":"emphasisText",start:Object.assign({},t[n][1].end),end:Object.assign({},t[r][1].start)},i={type:l>1?"strong":"emphasis",start:Object.assign({},s.start),end:Object.assign({},a.end)},t[n][1].end=Object.assign({},s.start),t[r][1].start=Object.assign({},a.end),c=[],t[n][1].end.offset-t[n][1].start.offset&&(c=Hr(c,[["enter",t[n][1],e],["exit",t[n][1],e]])),c=Hr(c,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),c=Hr(c,ju(e.parser.constructs.insideSpan.null,t.slice(n+1,r),e)),c=Hr(c,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[r][1].end.offset-t[r][1].start.offset?(u=2,c=Hr(c,[["enter",t[r][1],e],["exit",t[r][1],e]])):u=0,Mr(t,n-1,r-n+3,c),r=n+c.length-u-2;break}}for(r=-1;++r<t.length;)t[r][1].type==="attentionSequence"&&(t[r][1].type="data");return t}function XJ(t,e){let r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=NI(n),o;return s;function s(l){return o=l,t.enter("attentionSequence"),a(l)}function a(l){if(l===o)return t.consume(l),a;let c=t.exit("attentionSequence"),u=NI(l),d=!u||u===2&&i||r.includes(l),p=!i||i===2&&u||r.includes(n);return c._open=!!(o===42?d:d&&(i||!p)),c._close=!!(o===42?p:p&&(u||!d)),e(l)}}function Pj(t,e){t.column+=e,t.offset+=e,t._bufferIndex+=e}var CI={name:"autolink",tokenize:KJ};function KJ(t,e,r){let n=0;return i;function i(f){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(f){return In(f)?(t.consume(f),s):f===64?r(f):c(f)}function s(f){return f===43||f===45||f===46||sr(f)?(n=1,a(f)):c(f)}function a(f){return f===58?(t.consume(f),n=0,l):(f===43||f===45||f===46||sr(f))&&n++<32?(t.consume(f),a):(n=0,c(f))}function l(f){return f===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):f===null||f===32||f===60||nm(f)?r(f):(t.consume(f),l)}function c(f){return f===64?(t.consume(f),u):bj(f)?(t.consume(f),c):r(f)}function u(f){return sr(f)?d(f):r(f)}function d(f){return f===46?(t.consume(f),n=0,u):f===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),e):p(f)}function p(f){if((f===45||sr(f))&&n++<63){let m=f===45?p:d;return t.consume(f),m}return r(f)}}var Os={tokenize:JJ,partial:!0};function JJ(t,e,r){return n;function n(o){return Se(o)?Ie(t,i,"linePrefix")(o):i(o)}function i(o){return o===null||ne(o)?e(o):r(o)}}var bv={name:"blockQuote",tokenize:YJ,continuation:{tokenize:QJ},exit:e7};function YJ(t,e,r){let n=this;return i;function i(s){if(s===62){let a=n.containerState;return a.open||(t.enter("blockQuote",{_container:!0}),a.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(s),t.exit("blockQuoteMarker"),o}return r(s)}function o(s){return Se(s)?(t.enter("blockQuotePrefixWhitespace"),t.consume(s),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),e):(t.exit("blockQuotePrefix"),e(s))}}function QJ(t,e,r){let n=this;return i;function i(s){return Se(s)?Ie(t,o,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):o(s)}function o(s){return t.attempt(bv,e,r)(s)}}function e7(t){t.exit("blockQuote")}var wv={name:"characterEscape",tokenize:t7};function t7(t,e,r){return n;function n(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),i}function i(o){return xj(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),e):r(o)}}var xv={name:"characterReference",tokenize:r7};function r7(t,e,r){let n=this,i=0,o,s;return a;function a(d){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),l}function l(d){return d===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(d),t.exit("characterReferenceMarkerNumeric"),c):(t.enter("characterReferenceValue"),o=31,s=sr,u(d))}function c(d){return d===88||d===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(d),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,s=wj,u):(t.enter("characterReferenceValue"),o=7,s=im,u(d))}function u(d){if(d===59&&i){let p=t.exit("characterReferenceValue");return s===sr&&!Mu(n.sliceSerialize(p))?r(d):(t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),t.exit("characterReference"),e)}return s(d)&&i++<o?(t.consume(d),u):r(d)}}var Tj={tokenize:i7,partial:!0},$v={name:"codeFenced",tokenize:n7,concrete:!0};function n7(t,e,r){let n=this,i={tokenize:I,partial:!0},o=0,s=0,a;return l;function l(P){return c(P)}function c(P){let M=n.events[n.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,a=P,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(P)}function u(P){return P===a?(s++,t.consume(P),u):s<3?r(P):(t.exit("codeFencedFenceSequence"),Se(P)?Ie(t,d,"whitespace")(P):d(P))}function d(P){return P===null||ne(P)?(t.exit("codeFencedFence"),n.interrupt?e(P):t.check(Tj,h,E)(P)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),p(P))}function p(P){return P===null||ne(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),d(P)):Se(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ie(t,f,"whitespace")(P)):P===96&&P===a?r(P):(t.consume(P),p)}function f(P){return P===null||ne(P)?d(P):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),m(P))}function m(P){return P===null||ne(P)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),d(P)):P===96&&P===a?r(P):(t.consume(P),m)}function h(P){return t.attempt(i,E,y)(P)}function y(P){return t.enter("lineEnding"),t.consume(P),t.exit("lineEnding"),g}function g(P){return o>0&&Se(P)?Ie(t,_,"linePrefix",o+1)(P):_(P)}function _(P){return P===null||ne(P)?t.check(Tj,h,E)(P):(t.enter("codeFlowValue"),b(P))}function b(P){return P===null||ne(P)?(t.exit("codeFlowValue"),_(P)):(t.consume(P),b)}function E(P){return t.exit("codeFenced"),e(P)}function I(P,M,V){let R=0;return L;function L(ie){return P.enter("lineEnding"),P.consume(ie),P.exit("lineEnding"),G}function G(ie){return P.enter("codeFencedFence"),Se(ie)?Ie(P,H,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ie):H(ie)}function H(ie){return ie===a?(P.enter("codeFencedFenceSequence"),W(ie)):V(ie)}function W(ie){return ie===a?(R++,P.consume(ie),W):R>=s?(P.exit("codeFencedFenceSequence"),Se(ie)?Ie(P,Y,"whitespace")(ie):Y(ie)):V(ie)}function Y(ie){return ie===null||ne(ie)?(P.exit("codeFencedFence"),M(ie)):V(ie)}}}function i7(t,e,r){let n=this;return i;function i(s){return s===null?r(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}var sm={name:"codeIndented",tokenize:s7},o7={tokenize:a7,partial:!0};function s7(t,e,r){let n=this;return i;function i(c){return t.enter("codeIndented"),Ie(t,o,"linePrefix",5)(c)}function o(c){let u=n.events[n.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(c):r(c)}function s(c){return c===null?l(c):ne(c)?t.attempt(o7,s,l)(c):(t.enter("codeFlowValue"),a(c))}function a(c){return c===null||ne(c)?(t.exit("codeFlowValue"),s(c)):(t.consume(c),a)}function l(c){return t.exit("codeIndented"),e(c)}}function a7(t,e,r){let n=this;return i;function i(s){return n.parser.lazy[n.now().line]?r(s):ne(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):Ie(t,o,"linePrefix",5)(s)}function o(s){let a=n.events[n.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):ne(s)?i(s):r(s)}}var OI={name:"codeText",tokenize:u7,resolve:l7,previous:c7};function l7(t){let e=t.length-4,r=3,n,i;if((t[r][1].type==="lineEnding"||t[r][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(n=r;++n<e;)if(t[n][1].type==="codeTextData"){t[r][1].type="codeTextPadding",t[e][1].type="codeTextPadding",r+=2,e-=2;break}}for(n=r-1,e++;++n<=e;)i===void 0?n!==e&&t[n][1].type!=="lineEnding"&&(i=n):(n===e||t[n][1].type==="lineEnding")&&(t[i][1].type="codeTextData",n!==i+2&&(t[i][1].end=t[n-1][1].end,t.splice(i+2,n-i-2),e-=n-i-2,n=i+2),i=void 0);return t}function c7(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function u7(t,e,r){let n=this,i=0,o,s;return a;function a(p){return t.enter("codeText"),t.enter("codeTextSequence"),l(p)}function l(p){return p===96?(t.consume(p),i++,l):(t.exit("codeTextSequence"),c(p))}function c(p){return p===null?r(p):p===32?(t.enter("space"),t.consume(p),t.exit("space"),c):p===96?(s=t.enter("codeTextSequence"),o=0,d(p)):ne(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),c):(t.enter("codeTextData"),u(p))}function u(p){return p===null||p===32||p===96||ne(p)?(t.exit("codeTextData"),c(p)):(t.consume(p),u)}function d(p){return p===96?(t.consume(p),o++,d):o===i?(t.exit("codeTextSequence"),t.exit("codeText"),e(p)):(s.type="codeTextData",u(p))}}var kv=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,r){let n=r??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,r,n){let i=r||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&am(this.left,n),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),am(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),am(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let r=this.left.splice(e,Number.POSITIVE_INFINITY);am(this.right,r.reverse())}else{let r=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);am(this.left,r.reverse())}}};function am(t,e){let r=0;if(e.length<1e4)t.push(...e);else for(;r<e.length;)t.push(...e.slice(r,r+1e4)),r+=1e4}function Sv(t){let e={},r=-1,n,i,o,s,a,l,c,u=new kv(t);for(;++r<u.length;){for(;r in e;)r=e[r];if(n=u.get(r),r&&n[1].type==="chunkFlow"&&u.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,o=0,o<l.length&&l[o][1].type==="lineEndingBlank"&&(o+=2),o<l.length&&l[o][1].type==="content"))for(;++o<l.length&&l[o][1].type!=="content";)l[o][1].type==="chunkText"&&(l[o][1]._isInFirstContentOfListItem=!0,o++);if(n[0]==="enter")n[1].contentType&&(Object.assign(e,d7(u,r)),r=e[r],c=!0);else if(n[1]._container){for(o=r,i=void 0;o--&&(s=u.get(o),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank");)s[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),s[1].type="lineEnding",i=o);i&&(n[1].end=Object.assign({},u.get(i)[1].start),a=u.slice(i,r),a.unshift(n),u.splice(i,r-i+1,a))}}return Mr(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!c}function d7(t,e){let r=t.get(e)[1],n=t.get(e)[2],i=e-1,o=[],s=r._tokenizer||n.parser[r.contentType](r.start),a=s.events,l=[],c={},u,d,p=-1,f=r,m=0,h=0,y=[h];for(;f;){for(;t.get(++i)[1]!==f;);o.push(i),f._tokenizer||(u=n.sliceStream(f),f.next||u.push(null),d&&s.defineSkip(f.start),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(u),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=f,f=f.next}for(f=r;++p<a.length;)a[p][0]==="exit"&&a[p-1][0]==="enter"&&a[p][1].type===a[p-1][1].type&&a[p][1].start.line!==a[p][1].end.line&&(h=p+1,y.push(h),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(s.events=[],f?(f._tokenizer=void 0,f.previous=void 0):y.pop(),p=y.length;p--;){let g=a.slice(y[p],y[p+1]),_=o.pop();l.push([_,_+g.length-1]),t.splice(_,2,g)}for(l.reverse(),p=-1;++p<l.length;)c[m+l[p][0]]=m+l[p][1],m+=l[p][1]-l[p][0]-1;return c}var RI={tokenize:m7,resolve:p7},f7={tokenize:h7,partial:!0};function p7(t){return Sv(t),t}function m7(t,e){let r;return n;function n(a){return t.enter("content"),r=t.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?o(a):ne(a)?t.check(f7,s,o)(a):(t.consume(a),i)}function o(a){return t.exit("chunkContent"),t.exit("content"),e(a)}function s(a){return t.consume(a),t.exit("chunkContent"),r.next=t.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function h7(t,e,r){let n=this;return i;function i(s){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),Ie(t,o,"linePrefix")}function o(s){if(s===null||ne(s))return r(s);let a=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):t.interrupt(n.parser.constructs.flow,r,e)(s)}}function Iv(t,e,r,n,i,o,s,a,l){let c=l||Number.POSITIVE_INFINITY,u=0;return d;function d(g){return g===60?(t.enter(n),t.enter(i),t.enter(o),t.consume(g),t.exit(o),p):g===null||g===32||g===41||nm(g)?r(g):(t.enter(n),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),h(g))}function p(g){return g===62?(t.enter(o),t.consume(g),t.exit(o),t.exit(i),t.exit(n),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===62?(t.exit("chunkString"),t.exit(a),p(g)):g===null||g===60||ne(g)?r(g):(t.consume(g),g===92?m:f)}function m(g){return g===60||g===62||g===92?(t.consume(g),f):f(g)}function h(g){return!u&&(g===null||g===41||Ft(g))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(n),e(g)):u<c&&g===40?(t.consume(g),u++,h):g===41?(t.consume(g),u--,h):g===null||g===32||g===40||nm(g)?r(g):(t.consume(g),g===92?y:h)}function y(g){return g===40||g===41||g===92?(t.consume(g),h):h(g)}}function Ev(t,e,r,n,i,o){let s=this,a=0,l;return c;function c(f){return t.enter(n),t.enter(i),t.consume(f),t.exit(i),t.enter(o),u}function u(f){return a>999||f===null||f===91||f===93&&!l||f===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):f===93?(t.exit(o),t.enter(i),t.consume(f),t.exit(i),t.exit(n),e):ne(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===null||f===91||f===93||ne(f)||a++>999?(t.exit("chunkString"),u(f)):(t.consume(f),l||(l=!Se(f)),f===92?p:d)}function p(f){return f===91||f===92||f===93?(t.consume(f),a++,d):d(f)}}function Pv(t,e,r,n,i,o){let s;return a;function a(p){return p===34||p===39||p===40?(t.enter(n),t.enter(i),t.consume(p),t.exit(i),s=p===40?41:p,l):r(p)}function l(p){return p===s?(t.enter(i),t.consume(p),t.exit(i),t.exit(n),e):(t.enter(o),c(p))}function c(p){return p===s?(t.exit(o),l(s)):p===null?r(p):ne(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),Ie(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(p))}function u(p){return p===s||p===null||ne(p)?(t.exit("chunkString"),c(p)):(t.consume(p),p===92?d:u)}function d(p){return p===s||p===92?(t.consume(p),u):u(p)}}function il(t,e){let r;return n;function n(i){return ne(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),r=!0,n):Se(i)?Ie(t,n,r?"linePrefix":"lineSuffix")(i):e(i)}}var MI={name:"definition",tokenize:y7},g7={tokenize:v7,partial:!0};function y7(t,e,r){let n=this,i;return o;function o(f){return t.enter("definition"),s(f)}function s(f){return Ev.call(n,t,a,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function a(f){return i=Mo(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),l):r(f)}function l(f){return Ft(f)?il(t,c)(f):c(f)}function c(f){return Iv(t,u,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return t.attempt(g7,d,d)(f)}function d(f){return Se(f)?Ie(t,p,"whitespace")(f):p(f)}function p(f){return f===null||ne(f)?(t.exit("definition"),n.parser.defined.push(i),e(f)):r(f)}}function v7(t,e,r){return n;function n(a){return Ft(a)?il(t,i)(a):r(a)}function i(a){return Pv(t,o,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return Se(a)?Ie(t,s,"whitespace")(a):s(a)}function s(a){return a===null||ne(a)?e(a):r(a)}}var jI={name:"hardBreakEscape",tokenize:_7};function _7(t,e,r){return n;function n(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return ne(o)?(t.exit("hardBreakEscape"),e(o)):r(o)}}var DI={name:"headingAtx",tokenize:w7,resolve:b7};function b7(t,e){let r=t.length-2,n=3,i,o;return t[n][1].type==="whitespace"&&(n+=2),r-2>n&&t[r][1].type==="whitespace"&&(r-=2),t[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&t[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:t[n][1].start,end:t[r][1].end},o={type:"chunkText",start:t[n][1].start,end:t[r][1].end,contentType:"text"},Mr(t,n,r-n+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function w7(t,e,r){let n=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&n++<6?(t.consume(u),s):u===null||Ft(u)?(t.exit("atxHeadingSequence"),a(u)):r(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),l(u)):u===null||ne(u)?(t.exit("atxHeading"),e(u)):Se(u)?Ie(t,a,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function l(u){return u===35?(t.consume(u),l):(t.exit("atxHeadingSequence"),a(u))}function c(u){return u===null||u===35||Ft(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),c)}}var Aj=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],LI=["pre","script","style","textarea"];var UI={name:"htmlFlow",tokenize:S7,resolveTo:k7,concrete:!0},x7={tokenize:E7,partial:!0},$7={tokenize:I7,partial:!0};function k7(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function S7(t,e,r){let n=this,i,o,s,a,l;return c;function c(k){return u(k)}function u(k){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(k),d}function d(k){return k===33?(t.consume(k),p):k===47?(t.consume(k),o=!0,h):k===63?(t.consume(k),i=3,n.interrupt?e:x):In(k)?(t.consume(k),s=String.fromCharCode(k),y):r(k)}function p(k){return k===45?(t.consume(k),i=2,f):k===91?(t.consume(k),i=5,a=0,m):In(k)?(t.consume(k),i=4,n.interrupt?e:x):r(k)}function f(k){return k===45?(t.consume(k),n.interrupt?e:x):r(k)}function m(k){let Vt="CDATA[";return k===Vt.charCodeAt(a++)?(t.consume(k),a===Vt.length?n.interrupt?e:H:m):r(k)}function h(k){return In(k)?(t.consume(k),s=String.fromCharCode(k),y):r(k)}function y(k){if(k===null||k===47||k===62||Ft(k)){let Vt=k===47,qt=s.toLowerCase();return!Vt&&!o&&LI.includes(qt)?(i=1,n.interrupt?e(k):H(k)):Aj.includes(s.toLowerCase())?(i=6,Vt?(t.consume(k),g):n.interrupt?e(k):H(k)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):o?_(k):b(k))}return k===45||sr(k)?(t.consume(k),s+=String.fromCharCode(k),y):r(k)}function g(k){return k===62?(t.consume(k),n.interrupt?e:H):r(k)}function _(k){return Se(k)?(t.consume(k),_):L(k)}function b(k){return k===47?(t.consume(k),L):k===58||k===95||In(k)?(t.consume(k),E):Se(k)?(t.consume(k),b):L(k)}function E(k){return k===45||k===46||k===58||k===95||sr(k)?(t.consume(k),E):I(k)}function I(k){return k===61?(t.consume(k),P):Se(k)?(t.consume(k),I):b(k)}function P(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(t.consume(k),l=k,M):Se(k)?(t.consume(k),P):V(k)}function M(k){return k===l?(t.consume(k),l=null,R):k===null||ne(k)?r(k):(t.consume(k),M)}function V(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Ft(k)?I(k):(t.consume(k),V)}function R(k){return k===47||k===62||Se(k)?b(k):r(k)}function L(k){return k===62?(t.consume(k),G):r(k)}function G(k){return k===null||ne(k)?H(k):Se(k)?(t.consume(k),G):r(k)}function H(k){return k===45&&i===2?(t.consume(k),Fe):k===60&&i===1?(t.consume(k),it):k===62&&i===4?(t.consume(k),Dr):k===63&&i===3?(t.consume(k),x):k===93&&i===5?(t.consume(k),Pt):ne(k)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(x7,Gn,W)(k)):k===null||ne(k)?(t.exit("htmlFlowData"),W(k)):(t.consume(k),H)}function W(k){return t.check($7,Y,Gn)(k)}function Y(k){return t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),ie}function ie(k){return k===null||ne(k)?W(k):(t.enter("htmlFlowData"),H(k))}function Fe(k){return k===45?(t.consume(k),x):H(k)}function it(k){return k===47?(t.consume(k),s="",Ot):H(k)}function Ot(k){if(k===62){let Vt=s.toLowerCase();return LI.includes(Vt)?(t.consume(k),Dr):H(k)}return In(k)&&s.length<8?(t.consume(k),s+=String.fromCharCode(k),Ot):H(k)}function Pt(k){return k===93?(t.consume(k),x):H(k)}function x(k){return k===62?(t.consume(k),Dr):k===45&&i===2?(t.consume(k),x):H(k)}function Dr(k){return k===null||ne(k)?(t.exit("htmlFlowData"),Gn(k)):(t.consume(k),Dr)}function Gn(k){return t.exit("htmlFlow"),e(k)}}function I7(t,e,r){let n=this;return i;function i(s){return ne(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):r(s)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}function E7(t,e,r){return n;function n(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(Os,e,r)}}var ZI={name:"htmlText",tokenize:P7};function P7(t,e,r){let n=this,i,o,s;return a;function a(x){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(x),l}function l(x){return x===33?(t.consume(x),c):x===47?(t.consume(x),I):x===63?(t.consume(x),b):In(x)?(t.consume(x),V):r(x)}function c(x){return x===45?(t.consume(x),u):x===91?(t.consume(x),o=0,m):In(x)?(t.consume(x),_):r(x)}function u(x){return x===45?(t.consume(x),f):r(x)}function d(x){return x===null?r(x):x===45?(t.consume(x),p):ne(x)?(s=d,it(x)):(t.consume(x),d)}function p(x){return x===45?(t.consume(x),f):d(x)}function f(x){return x===62?Fe(x):x===45?p(x):d(x)}function m(x){let Dr="CDATA[";return x===Dr.charCodeAt(o++)?(t.consume(x),o===Dr.length?h:m):r(x)}function h(x){return x===null?r(x):x===93?(t.consume(x),y):ne(x)?(s=h,it(x)):(t.consume(x),h)}function y(x){return x===93?(t.consume(x),g):h(x)}function g(x){return x===62?Fe(x):x===93?(t.consume(x),g):h(x)}function _(x){return x===null||x===62?Fe(x):ne(x)?(s=_,it(x)):(t.consume(x),_)}function b(x){return x===null?r(x):x===63?(t.consume(x),E):ne(x)?(s=b,it(x)):(t.consume(x),b)}function E(x){return x===62?Fe(x):b(x)}function I(x){return In(x)?(t.consume(x),P):r(x)}function P(x){return x===45||sr(x)?(t.consume(x),P):M(x)}function M(x){return ne(x)?(s=M,it(x)):Se(x)?(t.consume(x),M):Fe(x)}function V(x){return x===45||sr(x)?(t.consume(x),V):x===47||x===62||Ft(x)?R(x):r(x)}function R(x){return x===47?(t.consume(x),Fe):x===58||x===95||In(x)?(t.consume(x),L):ne(x)?(s=R,it(x)):Se(x)?(t.consume(x),R):Fe(x)}function L(x){return x===45||x===46||x===58||x===95||sr(x)?(t.consume(x),L):G(x)}function G(x){return x===61?(t.consume(x),H):ne(x)?(s=G,it(x)):Se(x)?(t.consume(x),G):R(x)}function H(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(t.consume(x),i=x,W):ne(x)?(s=H,it(x)):Se(x)?(t.consume(x),H):(t.consume(x),Y)}function W(x){return x===i?(t.consume(x),i=void 0,ie):x===null?r(x):ne(x)?(s=W,it(x)):(t.consume(x),W)}function Y(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||Ft(x)?R(x):(t.consume(x),Y)}function ie(x){return x===47||x===62||Ft(x)?R(x):r(x)}function Fe(x){return x===62?(t.consume(x),t.exit("htmlTextData"),t.exit("htmlText"),e):r(x)}function it(x){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(x),t.exit("lineEnding"),Ot}function Ot(x){return Se(x)?Ie(t,Pt,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):Pt(x)}function Pt(x){return t.enter("htmlTextData"),s(x)}}var ol={name:"labelEnd",tokenize:O7,resolveTo:C7,resolveAll:N7},T7={tokenize:R7},A7={tokenize:M7},z7={tokenize:j7};function N7(t){let e=-1;for(;++e<t.length;){let r=t[e][1];(r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd")&&(t.splice(e+1,r.type==="labelImage"?4:2),r.type="data",e++)}return t}function C7(t,e){let r=t.length,n=0,i,o,s,a;for(;r--;)if(i=t[r][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;t[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(s){if(t[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(s=r);let l={type:t[o][1].type==="labelLink"?"link":"image",start:Object.assign({},t[o][1].start),end:Object.assign({},t[t.length-1][1].end)},c={type:"label",start:Object.assign({},t[o][1].start),end:Object.assign({},t[s][1].end)},u={type:"labelText",start:Object.assign({},t[o+n+2][1].end),end:Object.assign({},t[s-2][1].start)};return a=[["enter",l,e],["enter",c,e]],a=Hr(a,t.slice(o+1,o+n+3)),a=Hr(a,[["enter",u,e]]),a=Hr(a,ju(e.parser.constructs.insideSpan.null,t.slice(o+n+4,s-3),e)),a=Hr(a,[["exit",u,e],t[s-2],t[s-1],["exit",c,e]]),a=Hr(a,t.slice(s+1)),a=Hr(a,[["exit",l,e]]),Mr(t,o,t.length,a),t}function O7(t,e,r){let n=this,i=n.events.length,o,s;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){o=n.events[i][1];break}return a;function a(p){return o?o._inactive?d(p):(s=n.parser.defined.includes(Mo(n.sliceSerialize({start:o.end,end:n.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(p),t.exit("labelMarker"),t.exit("labelEnd"),l):r(p)}function l(p){return p===40?t.attempt(T7,u,s?u:d)(p):p===91?t.attempt(A7,u,s?c:d)(p):s?u(p):d(p)}function c(p){return t.attempt(z7,u,d)(p)}function u(p){return e(p)}function d(p){return o._balanced=!0,r(p)}}function R7(t,e,r){return n;function n(d){return t.enter("resource"),t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),i}function i(d){return Ft(d)?il(t,o)(d):o(d)}function o(d){return d===41?u(d):Iv(t,s,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function s(d){return Ft(d)?il(t,l)(d):u(d)}function a(d){return r(d)}function l(d){return d===34||d===39||d===40?Pv(t,c,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):u(d)}function c(d){return Ft(d)?il(t,u)(d):u(d)}function u(d){return d===41?(t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),t.exit("resource"),e):r(d)}}function M7(t,e,r){let n=this;return i;function i(a){return Ev.call(n,t,o,s,"reference","referenceMarker","referenceString")(a)}function o(a){return n.parser.defined.includes(Mo(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(a):r(a)}function s(a){return r(a)}}function j7(t,e,r){return n;function n(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),i}function i(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),e):r(o)}}var FI={name:"labelStartImage",tokenize:D7,resolveAll:ol.resolveAll};function D7(t,e,r){let n=this;return i;function i(a){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(a),t.exit("labelImageMarker"),o}function o(a){return a===91?(t.enter("labelMarker"),t.consume(a),t.exit("labelMarker"),t.exit("labelImage"),s):r(a)}function s(a){return a===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(a):e(a)}}var VI={name:"labelStartLink",tokenize:L7,resolveAll:ol.resolveAll};function L7(t,e,r){let n=this;return i;function i(s){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(s),t.exit("labelMarker"),t.exit("labelLink"),o}function o(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):e(s)}}var lm={name:"lineEnding",tokenize:U7};function U7(t,e){return r;function r(n){return t.enter("lineEnding"),t.consume(n),t.exit("lineEnding"),Ie(t,e,"linePrefix")}}var sl={name:"thematicBreak",tokenize:Z7};function Z7(t,e,r){let n=0,i;return o;function o(c){return t.enter("thematicBreak"),s(c)}function s(c){return i=c,a(c)}function a(c){return c===i?(t.enter("thematicBreakSequence"),l(c)):n>=3&&(c===null||ne(c))?(t.exit("thematicBreak"),e(c)):r(c)}function l(c){return c===i?(t.consume(c),n++,l):(t.exit("thematicBreakSequence"),Se(c)?Ie(t,a,"whitespace")(c):a(c))}}var jr={name:"list",tokenize:q7,continuation:{tokenize:W7},exit:G7},F7={tokenize:H7,partial:!0},V7={tokenize:B7,partial:!0};function q7(t,e,r){let n=this,i=n.events[n.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(f){let m=n.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(m==="listUnordered"?!n.containerState.marker||f===n.containerState.marker:im(f)){if(n.containerState.type||(n.containerState.type=m,t.enter(m,{_container:!0})),m==="listUnordered")return t.enter("listItemPrefix"),f===42||f===45?t.check(sl,r,c)(f):c(f);if(!n.interrupt||f===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(f)}return r(f)}function l(f){return im(f)&&++s<10?(t.consume(f),l):(!n.interrupt||s<2)&&(n.containerState.marker?f===n.containerState.marker:f===41||f===46)?(t.exit("listItemValue"),c(f)):r(f)}function c(f){return t.enter("listItemMarker"),t.consume(f),t.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||f,t.check(Os,n.interrupt?r:u,t.attempt(F7,p,d))}function u(f){return n.containerState.initialBlankLine=!0,o++,p(f)}function d(f){return Se(f)?(t.enter("listItemPrefixWhitespace"),t.consume(f),t.exit("listItemPrefixWhitespace"),p):r(f)}function p(f){return n.containerState.size=o+n.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(f)}}function W7(t,e,r){let n=this;return n.containerState._closeFlow=void 0,t.check(Os,i,o);function i(a){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,Ie(t,e,"listItemIndent",n.containerState.size+1)(a)}function o(a){return n.containerState.furtherBlankLines||!Se(a)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(a)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,t.attempt(V7,e,s)(a))}function s(a){return n.containerState._closeFlow=!0,n.interrupt=void 0,Ie(t,t.attempt(jr,e,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function B7(t,e,r){let n=this;return Ie(t,i,"listItemIndent",n.containerState.size+1);function i(o){let s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?e(o):r(o)}}function G7(t){t.exit(this.containerState.type)}function H7(t,e,r){let n=this;return Ie(t,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=n.events[n.events.length-1];return!Se(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):r(o)}}var Tv={name:"setextUnderline",tokenize:K7,resolveTo:X7};function X7(t,e){let r=t.length,n,i,o;for(;r--;)if(t[r][0]==="enter"){if(t[r][1].type==="content"){n=r;break}t[r][1].type==="paragraph"&&(i=r)}else t[r][1].type==="content"&&t.splice(r,1),!o&&t[r][1].type==="definition"&&(o=r);let s={type:"setextHeading",start:Object.assign({},t[i][1].start),end:Object.assign({},t[t.length-1][1].end)};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[n][1],e]),t[n][1].end=Object.assign({},t[o][1].end)):t[n][1]=s,t.push(["exit",s,e]),t}function K7(t,e,r){let n=this,i;return o;function o(c){let u=n.events.length,d;for(;u--;)if(n.events[u][1].type!=="lineEnding"&&n.events[u][1].type!=="linePrefix"&&n.events[u][1].type!=="content"){d=n.events[u][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||d)?(t.enter("setextHeadingLine"),i=c,s(c)):r(c)}function s(c){return t.enter("setextHeadingLineSequence"),a(c)}function a(c){return c===i?(t.consume(c),a):(t.exit("setextHeadingLineSequence"),Se(c)?Ie(t,l,"lineSuffix")(c):l(c))}function l(c){return c===null||ne(c)?(t.exit("setextHeadingLine"),e(c)):r(c)}}var zj={tokenize:J7};function J7(t){let e=this,r=t.attempt(Os,n,t.attempt(this.parser.constructs.flowInitial,i,Ie(t,t.attempt(this.parser.constructs.flow,i,t.attempt(RI,i)),"linePrefix")));return r;function n(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,r}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,r}}var Nj={resolveAll:Mj()},Cj=Rj("string"),Oj=Rj("text");function Rj(t){return{tokenize:e,resolveAll:Mj(t==="text"?Y7:void 0)};function e(r){let n=this,i=this.parser.constructs[t],o=r.attempt(i,s,a);return s;function s(u){return c(u)?o(u):a(u)}function a(u){if(u===null){r.consume(u);return}return r.enter("data"),r.consume(u),l}function l(u){return c(u)?(r.exit("data"),o(u)):(r.consume(u),l)}function c(u){if(u===null)return!0;let d=i[u],p=-1;if(d)for(;++p<d.length;){let f=d[p];if(!f.previous||f.previous.call(n,n.previous))return!0}return!1}}}function Mj(t){return e;function e(r,n){let i=-1,o;for(;++i<=r.length;)o===void 0?r[i]&&r[i][1].type==="data"&&(o=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==o+2&&(r[o][1].end=r[i-1][1].end,r.splice(o+2,i-o-2),i=o+2),o=void 0);return t?t(r,n):r}}function Y7(t,e){let r=0;for(;++r<=t.length;)if((r===t.length||t[r][1].type==="lineEnding")&&t[r-1][1].type==="data"){let n=t[r-1][1],i=e.sliceStream(n),o=i.length,s=-1,a=0,l;for(;o--;){let c=i[o];if(typeof c=="string"){for(s=c.length;c.charCodeAt(s-1)===32;)a++,s--;if(s)break;s=-1}else if(c===-2)l=!0,a++;else if(c!==-1){o++;break}}if(a){let c={type:r===t.length||l||a<2?"lineSuffix":"hardBreakTrailing",start:{line:n.end.line,column:n.end.column-a,offset:n.end.offset-a,_index:n.start._index+o,_bufferIndex:o?s:n.start._bufferIndex+s},end:Object.assign({},n.end)};n.end=Object.assign({},c.start),n.start.offset===n.end.offset?Object.assign(n,c):(t.splice(r,0,["enter",c,e],["exit",c,e]),r+=2)}r++}return t}function jj(t,e,r){let n=Object.assign(r?Object.assign({},r):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1}),i={},o=[],s=[],a=[],l=!0,c={consume:E,enter:I,exit:P,attempt:R(M),check:R(V),interrupt:R(V,{interrupt:!0})},u={previous:null,code:null,containerState:{},events:[],parser:t,sliceStream:h,sliceSerialize:m,now:y,defineSkip:g,write:f},d=e.tokenize.call(u,c),p;return e.resolveAll&&o.push(e),u;function f(W){return s=Hr(s,W),_(),s[s.length-1]!==null?[]:(L(e,0),u.events=ju(o,u.events,u),u.events)}function m(W,Y){return eY(h(W),Y)}function h(W){return Q7(s,W)}function y(){let{line:W,column:Y,offset:ie,_index:Fe,_bufferIndex:it}=n;return{line:W,column:Y,offset:ie,_index:Fe,_bufferIndex:it}}function g(W){i[W.line]=W.column,H()}function _(){let W;for(;n._index<s.length;){let Y=s[n._index];if(typeof Y=="string")for(W=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===W&&n._bufferIndex<Y.length;)b(Y.charCodeAt(n._bufferIndex));else b(Y)}}function b(W){l=void 0,p=W,d=d(W)}function E(W){ne(W)?(n.line++,n.column=1,n.offset+=W===-3?2:1,H()):W!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=W,l=!0}function I(W,Y){let ie=Y||{};return ie.type=W,ie.start=y(),u.events.push(["enter",ie,u]),a.push(ie),ie}function P(W){let Y=a.pop();return Y.end=y(),u.events.push(["exit",Y,u]),Y}function M(W,Y){L(W,Y.from)}function V(W,Y){Y.restore()}function R(W,Y){return ie;function ie(Fe,it,Ot){let Pt,x,Dr,Gn;return Array.isArray(Fe)?Vt(Fe):"tokenize"in Fe?Vt([Fe]):k(Fe);function k(Rt){return Hi;function Hi(Kr){let Xi=Kr!==null&&Rt[Kr],jo=Kr!==null&&Rt.null,Wu=[...Array.isArray(Xi)?Xi:Xi?[Xi]:[],...Array.isArray(jo)?jo:jo?[jo]:[]];return Vt(Wu)(Kr)}}function Vt(Rt){return Pt=Rt,x=0,Rt.length===0?Ot:qt(Rt[x])}function qt(Rt){return Hi;function Hi(Kr){return Gn=G(),Dr=Rt,Rt.partial||(u.currentConstruct=Rt),Rt.name&&u.parser.constructs.disable.null.includes(Rt.name)?Hn(Kr):Rt.tokenize.call(Y?Object.assign(Object.create(u),Y):u,c,Xr,Hn)(Kr)}}function Xr(Rt){return l=!0,W(Dr,Gn),it}function Hn(Rt){return l=!0,Gn.restore(),++x<Pt.length?qt(Pt[x]):Ot}}}function L(W,Y){W.resolveAll&&!o.includes(W)&&o.push(W),W.resolve&&Mr(u.events,Y,u.events.length-Y,W.resolve(u.events.slice(Y),u)),W.resolveTo&&(u.events=W.resolveTo(u.events,u))}function G(){let W=y(),Y=u.previous,ie=u.currentConstruct,Fe=u.events.length,it=Array.from(a);return{restore:Ot,from:Fe};function Ot(){n=W,u.previous=Y,u.currentConstruct=ie,u.events.length=Fe,a=it,H()}}function H(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function Q7(t,e){let r=e.start._index,n=e.start._bufferIndex,i=e.end._index,o=e.end._bufferIndex,s;if(r===i)s=[t[r].slice(n,o)];else{if(s=t.slice(r,i),n>-1){let a=s[0];typeof a=="string"?s[0]=a.slice(n):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function eY(t,e){let r=-1,n=[],i;for(;++r<t.length;){let o=t[r],s;if(typeof o=="string")s=o;else switch(o){case-5:{s="\r";break}case-4:{s=`
360
+ `;break}case-3:{s=`\r
361
+ `;break}case-2:{s=e?" ":" ";break}case-1:{if(!e&&i)continue;s=" ";break}default:s=String.fromCharCode(o)}i=o===-2,n.push(s)}return n.join("")}var qI={};Qu(qI,{attentionMarkers:()=>lY,contentInitial:()=>rY,disable:()=>cY,document:()=>tY,flow:()=>iY,flowInitial:()=>nY,insideSpan:()=>aY,string:()=>oY,text:()=>sY});var tY={42:jr,43:jr,45:jr,48:jr,49:jr,50:jr,51:jr,52:jr,53:jr,54:jr,55:jr,56:jr,57:jr,62:bv},rY={91:MI},nY={[-2]:sm,[-1]:sm,32:sm},iY={35:DI,42:sl,45:[Tv,sl],60:UI,61:Tv,95:sl,96:$v,126:$v},oY={38:xv,92:wv},sY={[-5]:lm,[-4]:lm,[-3]:lm,33:FI,38:xv,42:om,60:[CI,ZI],91:VI,92:[jI,wv],93:ol,95:om,96:OI},aY={null:[om,Nj]},lY={null:[42,95]},cY={null:[]};function WI(t){let r=_j([qI,...(t||{}).extensions||[]]),n={defined:[],lazy:{},constructs:r,content:i(Sj),document:i(Ej),flow:i(zj),string:i(Cj),text:i(Oj)};return n;function i(o){return s;function s(a){return jj(n,o,a)}}}function BI(t){for(;!Sv(t););return t}var Dj=/[\0\t\n\r]/g;function GI(){let t=1,e="",r=!0,n;return i;function i(o,s,a){let l=[],c,u,d,p,f;for(o=e+(typeof o=="string"?o.toString():new TextDecoder(s||void 0).decode(o)),d=0,e="",r&&(o.charCodeAt(0)===65279&&d++,r=void 0);d<o.length;){if(Dj.lastIndex=d,c=Dj.exec(o),p=c&&c.index!==void 0?c.index:o.length,f=o.charCodeAt(p),!c){e=o.slice(d);break}if(f===10&&d===p&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),d<p&&(l.push(o.slice(d,p)),t+=p-d),f){case 0:{l.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,l.push(-2);t++<u;)l.push(-1);break}case 10:{l.push(-4),t=1;break}default:n=!0,t=1}d=p+1}return a&&(n&&l.push(-5),e&&l.push(e),l.push(null)),l}}var uY=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Lj(t){return t.replace(uY,dY)}function dY(t,e,r){if(e)return e;if(r.charCodeAt(0)===35){let i=r.charCodeAt(1),o=i===120||i===88;return _v(r.slice(o?2:1),o?16:10)}return Mu(r)||t}function Rs(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Uj(t.position):"start"in t||"end"in t?Uj(t):"line"in t||"column"in t?HI(t):""}function HI(t){return Zj(t&&t.line)+":"+Zj(t&&t.column)}function Uj(t){return HI(t&&t.start)+"-"+HI(t&&t.end)}function Zj(t){return t&&typeof t=="number"?t:1}var Vj={}.hasOwnProperty;function XI(t,e,r){return typeof e!="string"&&(r=e,e=void 0),fY(r)(BI(WI(r).document().write(GI()(t,e,!0))))}function fY(t){let e={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Gu),autolinkProtocol:R,autolinkEmail:R,atxHeading:o(En),blockQuote:o(Hi),characterEscape:R,characterReference:R,codeFenced:o(Kr),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:o(Kr,s),codeText:o(Xi,s),codeTextData:R,data:R,codeFlowValue:R,definition:o(jo),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:o(Wu),hardBreakEscape:o(vm),hardBreakTrailing:o(vm),htmlFlow:o(Bu,s),htmlFlowData:R,htmlText:o(Bu,s),htmlTextData:R,image:o(_m),label:s,link:o(Gu),listItem:o(Do),listItemValue:p,listOrdered:o(bm,d),listUnordered:o(bm),paragraph:o(Pn),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:o(En),strong:o(wm),thematicBreak:o(Jv)},exit:{atxHeading:l(),atxHeadingSequence:I,autolink:l(),autolinkEmail:Rt,autolinkProtocol:Hn,blockQuote:l(),characterEscapeValue:L,characterReferenceMarkerHexadecimal:qt,characterReferenceMarkerNumeric:qt,characterReferenceValue:Xr,codeFenced:l(y),codeFencedFence:h,codeFencedFenceInfo:f,codeFencedFenceMeta:m,codeFlowValue:L,codeIndented:l(g),codeText:l(ie),codeTextData:L,data:L,definition:l(),definitionDestinationString:E,definitionLabelString:_,definitionTitleString:b,emphasis:l(),hardBreakEscape:l(H),hardBreakTrailing:l(H),htmlFlow:l(W),htmlFlowData:L,htmlText:l(Y),htmlTextData:L,image:l(it),label:Pt,labelText:Ot,lineEnding:G,link:l(Fe),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:Vt,resourceDestinationString:x,resourceTitleString:Dr,resource:Gn,setextHeading:l(V),setextHeadingLineSequence:M,setextHeadingText:P,strong:l(),thematicBreak:l()}};qj(e,(t||{}).mdastExtensions||[]);let r={};return n;function n(j){let K={type:"root",children:[]},fe={stack:[K],tokenStack:[],config:e,enter:a,exit:c,buffer:s,resume:u,data:r},Pe=[],nt=-1;for(;++nt<j.length;)if(j[nt][1].type==="listOrdered"||j[nt][1].type==="listUnordered")if(j[nt][0]==="enter")Pe.push(nt);else{let Jr=Pe.pop();nt=i(j,Jr,nt)}for(nt=-1;++nt<j.length;){let Jr=e[j[nt][0]];Vj.call(Jr,j[nt][1].type)&&Jr[j[nt][1].type].call(Object.assign({sliceSerialize:j[nt][2].sliceSerialize},fe),j[nt][1])}if(fe.tokenStack.length>0){let Jr=fe.tokenStack[fe.tokenStack.length-1];(Jr[1]||Fj).call(fe,void 0,Jr[0])}for(K.position={start:Ms(j.length>0?j[0][1].start:{line:1,column:1,offset:0}),end:Ms(j.length>0?j[j.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt<e.transforms.length;)K=e.transforms[nt](K)||K;return K}function i(j,K,fe){let Pe=K-1,nt=-1,Jr=!1,dn,Tn,js,Ds;for(;++Pe<=fe;){let $r=j[Pe];switch($r[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{$r[0]==="enter"?nt++:nt--,Ds=void 0;break}case"lineEndingBlank":{$r[0]==="enter"&&(dn&&!Ds&&!nt&&!js&&(js=Pe),Ds=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ds=void 0}if(!nt&&$r[0]==="enter"&&$r[1].type==="listItemPrefix"||nt===-1&&$r[0]==="exit"&&($r[1].type==="listUnordered"||$r[1].type==="listOrdered")){if(dn){let lr=Pe;for(Tn=void 0;lr--;){let Xn=j[lr];if(Xn[1].type==="lineEnding"||Xn[1].type==="lineEndingBlank"){if(Xn[0]==="exit")continue;Tn&&(j[Tn][1].type="lineEndingBlank",Jr=!0),Xn[1].type="lineEnding",Tn=lr}else if(!(Xn[1].type==="linePrefix"||Xn[1].type==="blockQuotePrefix"||Xn[1].type==="blockQuotePrefixWhitespace"||Xn[1].type==="blockQuoteMarker"||Xn[1].type==="listItemIndent"))break}js&&(!Tn||js<Tn)&&(dn._spread=!0),dn.end=Object.assign({},Tn?j[Tn][1].start:$r[1].end),j.splice(Tn||Pe,0,["exit",dn,$r[2]]),Pe++,fe++}if($r[1].type==="listItemPrefix"){let lr={type:"listItem",_spread:!1,start:Object.assign({},$r[1].start),end:void 0};dn=lr,j.splice(Pe,0,["enter",lr,$r[2]]),Pe++,fe++,js=void 0,Ds=!0}}}return j[K][1]._spread=Jr,fe}function o(j,K){return fe;function fe(Pe){a.call(this,j(Pe),Pe),K&&K.call(this,Pe)}}function s(){this.stack.push({type:"fragment",children:[]})}function a(j,K,fe){this.stack[this.stack.length-1].children.push(j),this.stack.push(j),this.tokenStack.push([K,fe]),j.position={start:Ms(K.start),end:void 0}}function l(j){return K;function K(fe){j&&j.call(this,fe),c.call(this,fe)}}function c(j,K){let fe=this.stack.pop(),Pe=this.tokenStack.pop();if(Pe)Pe[0].type!==j.type&&(K?K.call(this,j,Pe[0]):(Pe[1]||Fj).call(this,j,Pe[0]));else throw new Error("Cannot close `"+j.type+"` ("+Rs({start:j.start,end:j.end})+"): it\u2019s not open");fe.position.end=Ms(j.end)}function u(){return zI(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function p(j){if(this.data.expectingFirstListItemValue){let K=this.stack[this.stack.length-2];K.start=Number.parseInt(this.sliceSerialize(j),10),this.data.expectingFirstListItemValue=void 0}}function f(){let j=this.resume(),K=this.stack[this.stack.length-1];K.lang=j}function m(){let j=this.resume(),K=this.stack[this.stack.length-1];K.meta=j}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function g(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j.replace(/(\r?\n|\r)$/g,"")}function _(j){let K=this.resume(),fe=this.stack[this.stack.length-1];fe.label=K,fe.identifier=Mo(this.sliceSerialize(j)).toLowerCase()}function b(){let j=this.resume(),K=this.stack[this.stack.length-1];K.title=j}function E(){let j=this.resume(),K=this.stack[this.stack.length-1];K.url=j}function I(j){let K=this.stack[this.stack.length-1];if(!K.depth){let fe=this.sliceSerialize(j).length;K.depth=fe}}function P(){this.data.setextHeadingSlurpLineEnding=!0}function M(j){let K=this.stack[this.stack.length-1];K.depth=this.sliceSerialize(j).codePointAt(0)===61?1:2}function V(){this.data.setextHeadingSlurpLineEnding=void 0}function R(j){let fe=this.stack[this.stack.length-1].children,Pe=fe[fe.length-1];(!Pe||Pe.type!=="text")&&(Pe=Kv(),Pe.position={start:Ms(j.start),end:void 0},fe.push(Pe)),this.stack.push(Pe)}function L(j){let K=this.stack.pop();K.value+=this.sliceSerialize(j),K.position.end=Ms(j.end)}function G(j){let K=this.stack[this.stack.length-1];if(this.data.atHardBreak){let fe=K.children[K.children.length-1];fe.position.end=Ms(j.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&e.canContainEols.includes(K.type)&&(R.call(this,j),L.call(this,j))}function H(){this.data.atHardBreak=!0}function W(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function Y(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function ie(){let j=this.resume(),K=this.stack[this.stack.length-1];K.value=j}function Fe(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let K=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=K,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function it(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let K=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=K,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function Ot(j){let K=this.sliceSerialize(j),fe=this.stack[this.stack.length-2];fe.label=Lj(K),fe.identifier=Mo(K).toLowerCase()}function Pt(){let j=this.stack[this.stack.length-1],K=this.resume(),fe=this.stack[this.stack.length-1];if(this.data.inReference=!0,fe.type==="link"){let Pe=j.children;fe.children=Pe}else fe.alt=K}function x(){let j=this.resume(),K=this.stack[this.stack.length-1];K.url=j}function Dr(){let j=this.resume(),K=this.stack[this.stack.length-1];K.title=j}function Gn(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function Vt(j){let K=this.resume(),fe=this.stack[this.stack.length-1];fe.label=K,fe.identifier=Mo(this.sliceSerialize(j)).toLowerCase(),this.data.referenceType="full"}function qt(j){this.data.characterReferenceType=j.type}function Xr(j){let K=this.sliceSerialize(j),fe=this.data.characterReferenceType,Pe;fe?(Pe=_v(K,fe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Pe=Mu(K);let nt=this.stack.pop();nt.value+=Pe,nt.position.end=Ms(j.end)}function Hn(j){L.call(this,j);let K=this.stack[this.stack.length-1];K.url=this.sliceSerialize(j)}function Rt(j){L.call(this,j);let K=this.stack[this.stack.length-1];K.url="mailto:"+this.sliceSerialize(j)}function Hi(){return{type:"blockquote",children:[]}}function Kr(){return{type:"code",lang:null,meta:null,value:""}}function Xi(){return{type:"inlineCode",value:""}}function jo(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Wu(){return{type:"emphasis",children:[]}}function En(){return{type:"heading",depth:0,children:[]}}function vm(){return{type:"break"}}function Bu(){return{type:"html",value:""}}function _m(){return{type:"image",title:null,url:"",alt:null}}function Gu(){return{type:"link",title:null,url:"",children:[]}}function bm(j){return{type:"list",ordered:j.type==="listOrdered",start:null,spread:j._spread,children:[]}}function Do(j){return{type:"listItem",spread:j._spread,checked:null,children:[]}}function Pn(){return{type:"paragraph",children:[]}}function wm(){return{type:"strong",children:[]}}function Kv(){return{type:"text",value:""}}function Jv(){return{type:"thematicBreak"}}}function Ms(t){return{line:t.line,column:t.column,offset:t.offset}}function qj(t,e){let r=-1;for(;++r<e.length;){let n=e[r];Array.isArray(n)?qj(t,n):pY(t,n)}}function pY(t,e){let r;for(r in e)if(Vj.call(e,r))switch(r){case"canContainEols":{let n=e[r];n&&t[r].push(...n);break}case"transforms":{let n=e[r];n&&t[r].push(...n);break}case"enter":case"exit":{let n=e[r];n&&Object.assign(t[r],n);break}}}function Fj(t,e){throw t?new Error("Cannot close `"+t.type+"` ("+Rs({start:t.start,end:t.end})+"): a different token (`"+e.type+"`, "+Rs({start:e.start,end:e.end})+") is open"):new Error("Cannot close document, a token (`"+e.type+"`, "+Rs({start:e.start,end:e.end})+") is still open")}function cm(t){let e=this;e.parser=r;function r(n){return XI(n,{...e.data("settings"),...t,extensions:e.data("micromarkExtensions")||[],mdastExtensions:e.data("fromMarkdownExtensions")||[]})}}function Wj(t,e){let r={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(e),!0)};return t.patch(e,r),t.applyData(e,r)}function Bj(t,e){let r={type:"element",tagName:"br",properties:{},children:[]};return t.patch(e,r),[t.applyData(e,r),{type:"text",value:`
362
+ `}]}function Gj(t,e){let r=e.value?e.value+`
363
+ `:"",n={};e.lang&&(n.className=["language-"+e.lang]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return e.meta&&(i.data={meta:e.meta}),t.patch(e,i),i=t.applyData(e,i),i={type:"element",tagName:"pre",properties:{},children:[i]},t.patch(e,i),i}function Hj(t,e){let r={type:"element",tagName:"del",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Xj(t,e){let r={type:"element",tagName:"em",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Kj(t,e){let r=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=String(e.identifier).toUpperCase(),i=Bn(n.toLowerCase()),o=t.footnoteOrder.indexOf(n),s,a=t.footnoteCounts.get(n);a===void 0?(a=0,t.footnoteOrder.push(n),s=t.footnoteOrder.length):s=o+1,a+=1,t.footnoteCounts.set(n,a);let l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+i,id:r+"fnref-"+i+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};t.patch(e,l);let c={type:"element",tagName:"sup",properties:{},children:[l]};return t.patch(e,c),t.applyData(e,c)}function Jj(t,e){let r={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Yj(t,e){if(t.options.allowDangerousHtml){let r={type:"raw",value:e.value};return t.patch(e,r),t.applyData(e,r)}}function Av(t,e){let r=e.referenceType,n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+n}];let i=t.all(e),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});let s=i[i.length-1];return s&&s.type==="text"?s.value+=n:i.push({type:"text",value:n}),i}function Qj(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return Av(t,e);let i={src:Bn(n.url||""),alt:e.alt};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"img",properties:i,children:[]};return t.patch(e,o),t.applyData(e,o)}function eD(t,e){let r={src:Bn(e.url)};e.alt!==null&&e.alt!==void 0&&(r.alt=e.alt),e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"img",properties:r,children:[]};return t.patch(e,n),t.applyData(e,n)}function tD(t,e){let r={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,r);let n={type:"element",tagName:"code",properties:{},children:[r]};return t.patch(e,n),t.applyData(e,n)}function rD(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return Av(t,e);let i={href:Bn(n.url||"")};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"a",properties:i,children:t.all(e)};return t.patch(e,o),t.applyData(e,o)}function nD(t,e){let r={href:Bn(e.url)};e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"a",properties:r,children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function iD(t,e,r){let n=t.all(e),i=r?mY(r):oD(e),o={},s=[];if(typeof e.checked=="boolean"){let u=n[0],d;u&&u.type==="element"&&u.tagName==="p"?d=u:(d={type:"element",tagName:"p",properties:{},children:[]},n.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let a=-1;for(;++a<n.length;){let u=n[a];(i||a!==0||u.type!=="element"||u.tagName!=="p")&&s.push({type:"text",value:`
364
+ `}),u.type==="element"&&u.tagName==="p"&&!i?s.push(...u.children):s.push(u)}let l=n[n.length-1];l&&(i||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
365
+ `});let c={type:"element",tagName:"li",properties:o,children:s};return t.patch(e,c),t.applyData(e,c)}function mY(t){let e=!1;if(t.type==="list"){e=t.spread||!1;let r=t.children,n=-1;for(;!e&&++n<r.length;)e=oD(r[n])}return e}function oD(t){let e=t.spread;return e??t.children.length>1}function sD(t,e){let r={},n=t.all(e),i=-1;for(typeof e.start=="number"&&e.start!==1&&(r.start=e.start);++i<n.length;){let s=n[i];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}let o={type:"element",tagName:e.ordered?"ol":"ul",properties:r,children:t.wrap(n,!0)};return t.patch(e,o),t.applyData(e,o)}function aD(t,e){let r={type:"element",tagName:"p",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function lD(t,e){let r={type:"root",children:t.wrap(t.all(e))};return t.patch(e,r),t.applyData(e,r)}function cD(t,e){let r={type:"element",tagName:"strong",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}var zv=uD("end"),Nv=uD("start");function uD(t){return e;function e(r){let n=r&&r.position&&r.position[t]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function KI(t){let e=Nv(t),r=zv(t);if(e&&r)return{start:e,end:r}}function dD(t,e){let r=t.all(e),n=r.shift(),i=[];if(n){let s={type:"element",tagName:"thead",properties:{},children:t.wrap([n],!0)};t.patch(e.children[0],s),i.push(s)}if(r.length>0){let s={type:"element",tagName:"tbody",properties:{},children:t.wrap(r,!0)},a=Nv(e.children[1]),l=zv(e.children[e.children.length-1]);a&&l&&(s.position={start:a,end:l}),i.push(s)}let o={type:"element",tagName:"table",properties:{},children:t.wrap(i,!0)};return t.patch(e,o),t.applyData(e,o)}function fD(t,e,r){let n=r?r.children:void 0,o=(n?n.indexOf(e):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,a=s?s.length:e.children.length,l=-1,c=[];for(;++l<a;){let d=e.children[l],p={},f=s?s[l]:void 0;f&&(p.align=f);let m={type:"element",tagName:o,properties:p,children:[]};d&&(m.children=t.all(d),t.patch(d,m),m=t.applyData(d,m)),c.push(m)}let u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(e,u),t.applyData(e,u)}function pD(t,e){let r={type:"element",tagName:"td",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function hD(t){let e=String(t),r=/\r?\n|\r/g,n=r.exec(e),i=0,o=[];for(;n;)o.push(mD(e.slice(i,n.index),i>0,!0),n[0]),i=n.index+n[0].length,n=r.exec(e);return o.push(mD(e.slice(i),i>0,!1)),o.join("")}function mD(t,e,r){let n=0,i=t.length;if(e){let o=t.codePointAt(n);for(;o===9||o===32;)n++,o=t.codePointAt(n)}if(r){let o=t.codePointAt(i-1);for(;o===9||o===32;)i--,o=t.codePointAt(i-1)}return i>n?t.slice(n,i):""}function gD(t,e){let r={type:"text",value:hD(String(e.value))};return t.patch(e,r),t.applyData(e,r)}function yD(t,e){let r={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,r),t.applyData(e,r)}var vD={blockquote:Wj,break:Bj,code:Gj,delete:Hj,emphasis:Xj,footnoteReference:Kj,heading:Jj,html:Yj,imageReference:Qj,image:eD,inlineCode:tD,linkReference:rD,link:nD,listItem:iD,list:sD,paragraph:aD,root:lD,strong:cD,table:dD,tableCell:pD,tableRow:fD,text:gD,thematicBreak:yD,toml:Cv,yaml:Cv,definition:Cv,footnoteDefinition:Cv};function Cv(){}function hY(t,e){let r=[{type:"text",value:"\u21A9"}];return e>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),r}function gY(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function _D(t){let e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",r=t.options.footnoteBackContent||hY,n=t.options.footnoteBackLabel||gY,i=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",s=t.options.footnoteLabelProperties||{className:["sr-only"]},a=[],l=-1;for(;++l<t.footnoteOrder.length;){let c=t.footnoteById.get(t.footnoteOrder[l]);if(!c)continue;let u=t.all(c),d=String(c.identifier).toUpperCase(),p=Bn(d.toLowerCase()),f=0,m=[],h=t.footnoteCounts.get(d);for(;h!==void 0&&++f<=h;){m.length>0&&m.push({type:"text",value:" "});let _=typeof r=="string"?r:r(l,f);typeof _=="string"&&(_={type:"text",value:_}),m.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+p+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,f),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}let y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){let _=y.children[y.children.length-1];_&&_.type==="text"?_.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...m)}else u.push(...m);let g={type:"element",tagName:"li",properties:{id:e+"fn-"+p},children:t.wrap(u,!0)};t.patch(c,g),a.push(g)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...qi(s),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
366
+ `},{type:"element",tagName:"ol",properties:{},children:t.wrap(a,!0)},{type:"text",value:`
367
+ `}]}}var JI={}.hasOwnProperty,yY={};function wD(t,e){let r=e||yY,n=new Map,i=new Map,o=new Map,s={...vD,...r.handlers},a={all:c,applyData:_Y,definitionById:n,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:s,one:l,options:r,patch:vY,wrap:wY};return Xp(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){let d=u.type==="definition"?n:i,p=String(u.identifier).toUpperCase();d.has(p)||d.set(p,u)}}),a;function l(u,d){let p=u.type,f=a.handlers[p];if(JI.call(a.handlers,p)&&f)return f(a,u,d);if(a.options.passThrough&&a.options.passThrough.includes(p)){if("children"in u){let{children:h,...y}=u,g=qi(y);return g.children=a.all(u),g}return qi(u)}return(a.options.unknownHandler||bY)(a,u,d)}function c(u){let d=[];if("children"in u){let p=u.children,f=-1;for(;++f<p.length;){let m=a.one(p[f],u);if(m){if(f&&p[f-1].type==="break"&&(!Array.isArray(m)&&m.type==="text"&&(m.value=bD(m.value)),!Array.isArray(m)&&m.type==="element")){let h=m.children[0];h&&h.type==="text"&&(h.value=bD(h.value))}Array.isArray(m)?d.push(...m):d.push(m)}}}return d}}function vY(t,e){t.position&&(e.position=KI(t))}function _Y(t,e){let r=e;if(t&&t.data){let n=t.data.hName,i=t.data.hChildren,o=t.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{let s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&o&&Object.assign(r.properties,qi(o)),"children"in r&&r.children&&i!==null&&i!==void 0&&(r.children=i)}return r}function bY(t,e){let r=e.data||{},n="value"in e&&!(JI.call(r,"hProperties")||JI.call(r,"hChildren"))?{type:"text",value:e.value}:{type:"element",tagName:"div",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function wY(t,e){let r=[],n=-1;for(e&&r.push({type:"text",value:`
368
+ `});++n<t.length;)n&&r.push({type:"text",value:`
369
+ `}),r.push(t[n]);return e&&t.length>0&&r.push({type:"text",value:`
370
+ `}),r}function bD(t){let e=0,r=t.charCodeAt(e);for(;r===9||r===32;)e++,r=t.charCodeAt(e);return t.slice(e)}function Ov(t,e){let r=wD(t,e),n=r.one(t,void 0),i=_D(r),o=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return i&&("children"in o,o.children.push({type:"text",value:`
371
+ `},i)),o}function um(t,e){return t&&"run"in t?async function(r,n){let i=Ov(r,{file:n,...e});await t.run(i,n)}:function(r,n){return Ov(r,{file:n,...e||t})}}function YI(t){if(t)throw t}var jv=t_(AD(),1);function dm(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function QI(){let t=[],e={run:r,use:n};return e;function r(...i){let o=-1,s=i.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);a(null,...i);function a(l,...c){let u=t[++o],d=-1;if(l){s(l);return}for(;++d<i.length;)(c[d]===null||c[d]===void 0)&&(c[d]=i[d]);i=c,u?zD(u,a)(...c):s(null,...c)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return t.push(i),e}}function zD(t,e){let r;return n;function n(...s){let a=t.length>s.length,l;a&&s.push(i);try{l=t.apply(this,s)}catch(c){let u=c;if(a&&r)throw u;return i(u)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(s,...a){r||(r=!0,e(s,...a))}function o(s){i(null,s)}}var ar=class extends Error{constructor(e,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let i="",o={},s=!1;if(r&&("line"in r&&"column"in r?o={place:r}:"start"in r&&"end"in r?o={place:r}:"type"in r?o={ancestors:[r],place:r.position}:o={...r}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof n=="string"){let l=n.indexOf(":");l===-1?o.ruleId=n:(o.source=n.slice(0,l),o.ruleId=n.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){let l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}let a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file,this.message=i,this.line=a?a.line:void 0,this.name=Rs(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual,this.expected,this.note,this.url}};ar.prototype.file="";ar.prototype.name="";ar.prototype.reason="";ar.prototype.message="";ar.prototype.stack="";ar.prototype.column=void 0;ar.prototype.line=void 0;ar.prototype.ancestors=void 0;ar.prototype.cause=void 0;ar.prototype.fatal=void 0;ar.prototype.place=void 0;ar.prototype.ruleId=void 0;ar.prototype.source=void 0;var gi={basename:xY,dirname:$Y,extname:kY,join:SY,sep:"/"};function xY(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');fm(t);let r=0,n=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else n<0&&(o=!0,n=i+1);return n<0?"":t.slice(r,n)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(n=i):(a=-1,n=s));return r===n?n=s:n<0&&(n=t.length),t.slice(r,n)}function $Y(t){if(fm(t),t.length===0)return".";let e=-1,r=t.length,n;for(;--r;)if(t.codePointAt(r)===47){if(n){e=r;break}}else n||(n=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function kY(t){fm(t);let e=t.length,r=-1,n=0,i=-1,o=0,s;for(;e--;){let a=t.codePointAt(e);if(a===47){if(s){n=e+1;break}continue}r<0&&(s=!0,r=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||r<0||o===0||o===1&&i===r-1&&i===n+1?"":t.slice(i,r)}function SY(...t){let e=-1,r;for(;++e<t.length;)fm(t[e]),t[e]&&(r=r===void 0?t[e]:r+"/"+t[e]);return r===void 0?".":IY(r)}function IY(t){fm(t);let e=t.codePointAt(0)===47,r=EY(t,!e);return r.length===0&&!e&&(r="."),r.length>0&&t.codePointAt(t.length-1)===47&&(r+="/"),e?"/"+r:r}function EY(t,e){let r="",n=0,i=-1,o=0,s=-1,a,l;for(;++s<=t.length;){if(s<t.length)a=t.codePointAt(s);else{if(a===47)break;a=47}if(a===47){if(!(i===s-1||o===1))if(i!==s-1&&o===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),i=s,o=0;continue}}else if(r.length>0){r="",n=0,i=s,o=0;continue}}e&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+t.slice(i+1,s):r=t.slice(i+1,s),n=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return r}function fm(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}var ND={cwd:PY};function PY(){return"/"}function Du(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function CD(t){if(typeof t=="string")t=new URL(t);else if(!Du(t)){let e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){let e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return TY(t)}function TY(t){if(t.hostname!==""){let n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}let e=t.pathname,r=-1;for(;++r<e.length;)if(e.codePointAt(r)===37&&e.codePointAt(r+1)===50){let n=e.codePointAt(r+2);if(n===70||n===102){let i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(e)}var eE=["history","path","basename","stem","extname","dirname"],pm=class{constructor(e){let r;e?Du(e)?r={path:e}:typeof e=="string"||AY(e)?r={value:e}:r=e:r={},this.cwd=ND.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<eE.length;){let o=eE[n];o in r&&r[o]!==void 0&&r[o]!==null&&(this[o]=o==="history"?[...r[o]]:r[o])}let i;for(i in r)eE.includes(i)||(this[i]=r[i])}get basename(){return typeof this.path=="string"?gi.basename(this.path):void 0}set basename(e){rE(e,"basename"),tE(e,"basename"),this.path=gi.join(this.dirname||"",e)}get dirname(){return typeof this.path=="string"?gi.dirname(this.path):void 0}set dirname(e){OD(this.basename,"dirname"),this.path=gi.join(e||"",this.basename)}get extname(){return typeof this.path=="string"?gi.extname(this.path):void 0}set extname(e){if(tE(e,"extname"),OD(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=gi.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){Du(e)&&(e=CD(e)),rE(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path=="string"?gi.basename(this.path,this.extname):void 0}set stem(e){rE(e,"stem"),tE(e,"stem"),this.path=gi.join(this.dirname||"",e+(this.extname||""))}fail(e,r,n){let i=this.message(e,r,n);throw i.fatal=!0,i}info(e,r,n){let i=this.message(e,r,n);return i.fatal=void 0,i}message(e,r,n){let i=new ar(e,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(e){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(e||void 0).decode(this.value)}};function tE(t,e){if(t&&t.includes(gi.sep))throw new Error("`"+e+"` cannot be a path: did not expect `"+gi.sep+"`")}function rE(t,e){if(!t)throw new Error("`"+e+"` cannot be empty")}function OD(t,e){if(!t)throw new Error("Setting `"+e+"` requires `path` to be set too")}function AY(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var RD=function(t){let n=this.constructor.prototype,i=n[t],o=function(){return i.apply(o,arguments)};Object.setPrototypeOf(o,n);let s=Object.getOwnPropertyNames(i);for(let a of s){let l=Object.getOwnPropertyDescriptor(i,a);l&&Object.defineProperty(o,a,l)}return o};var zY={}.hasOwnProperty,sE=class t extends RD{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=QI()}copy(){let e=new t,r=-1;for(;++r<this.attachers.length;){let n=this.attachers[r];e.use(...n)}return e.data((0,jv.default)(!0,{},this.namespace)),e}data(e,r){return typeof e=="string"?arguments.length===2?(oE("data",this.frozen),this.namespace[e]=r,this):zY.call(this.namespace,e)&&this.namespace[e]||void 0:e?(oE("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;let e=this;for(;++this.freezeIndex<this.attachers.length;){let[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);let i=r.call(e,...n);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();let r=Mv(e),n=this.parser||this.Parser;return nE("parse",n),n(String(r),r)}process(e,r){let n=this;return this.freeze(),nE("process",this.parser||this.Parser),iE("process",this.compiler||this.Compiler),r?i(void 0,r):new Promise(i);function i(o,s){let a=Mv(e),l=n.parse(a);n.run(l,a,function(u,d,p){if(u||!d||!p)return c(u);let f=d,m=n.stringify(f,p);CY(m)?p.value=m:p.result=m,c(u,p)});function c(u,d){u||!d?s(u):o?o(d):r(void 0,d)}}}processSync(e){let r=!1,n;return this.freeze(),nE("processSync",this.parser||this.Parser),iE("processSync",this.compiler||this.Compiler),this.process(e,i),jD("processSync","process",r),n;function i(o,s){r=!0,YI(o),n=s}}run(e,r,n){MD(e),this.freeze();let i=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?o(void 0,n):new Promise(o);function o(s,a){let l=Mv(r);i.run(e,l,c);function c(u,d,p){let f=d||e;u?a(u):s?s(f):n(void 0,f,p)}}}runSync(e,r){let n=!1,i;return this.run(e,r,o),jD("runSync","run",n),i;function o(s,a){YI(s),i=a,n=!0}}stringify(e,r){this.freeze();let n=Mv(r),i=this.compiler||this.Compiler;return iE("stringify",i),MD(e),i(e,n)}use(e,...r){let n=this.attachers,i=this.namespace;if(oE("use",this.frozen),e!=null)if(typeof e=="function")l(e,r);else if(typeof e=="object")Array.isArray(e)?a(e):s(e);else throw new TypeError("Expected usable value, not `"+e+"`");return this;function o(c){if(typeof c=="function")l(c,[]);else if(typeof c=="object")if(Array.isArray(c)){let[u,...d]=c;l(u,d)}else s(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function s(c){if(!("plugins"in c)&&!("settings"in c))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(c.plugins),c.settings&&(i.settings=(0,jv.default)(!0,i.settings,c.settings))}function a(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){let d=c[u];o(d)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function l(c,u){let d=-1,p=-1;for(;++d<n.length;)if(n[d][0]===c){p=d;break}if(p===-1)n.push([c,...u]);else if(u.length>0){let[f,...m]=u,h=n[p][1];dm(h)&&dm(f)&&(f=(0,jv.default)(!0,h,f)),n[p]=[c,f,...m]}}}},Dv=new sE().freeze();function nE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function iE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function oE(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function MD(t){if(!dm(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function jD(t,e,r){if(!r)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Mv(t){return NY(t)?t:new pm(t)}function NY(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function CY(t){return typeof t=="string"||OY(t)}function OY(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var mm=class extends kn{constructor(){super(...arguments);this.html=()=>`
217
372
 
218
373
  <!-- Styling -->
219
374
  <style>
@@ -296,11 +451,11 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
296
451
  <div id='llm-selector-list'></div>
297
452
  </div>
298
453
 
299
- `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let i of this.state.items||[]){let o=document.createElement("div");o.className="llm-selector-item"+(i.id==this.state.selectedID?" selected":""),o.innerHTML=`
300
- <div class='llm-selector-item-icon' style="background-image: url('${i.icon}'); "></div>
301
- <div class='llm-selector-item-name'>${i.name}</div>
302
- <div class='llm-selector-item-provider'>${i.provider}</div>
303
- `,o.addEventListener("click",s=>{this.dispatchEvent(new CustomEvent("select",{detail:i.id}))}),e.appendChild(o)}}};_.observedAttributes=["open"];var D=new p("ONNXModel"),M=class u{constructor(t){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=t,D.debug(`Model input parameters: ${t.inputNames.join(", ")}`),D.debug(`Model output parameters: ${t.outputNames.join(", ")}`)}static isSupported(){return!!u.lib}static async load(t){if(!u.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(D.debug("Loading ONNX runtime"),this.onnx=await u.lib()),D.debug(`Loading model: ${t}`);let e=await this.onnx.InferenceSession.create(t);return new u(e)}makeTensor(t,e,i=0){let o=1;for(let n of e)o*=n;let s;if(t=="float32")s=new u.onnx.Tensor(new Float32Array(o),e);else if(t=="int8")s=new u.onnx.Tensor(new Int8Array(o),e);else if(t=="int16")s=new u.onnx.Tensor(new Int16Array(o),e);else if(t=="int32")s=new u.onnx.Tensor(new Int32Array(o),e);else if(t=="int64")s=new u.onnx.Tensor(new BigInt64Array(o),e);else if(t=="uint8")s=new u.onnx.Tensor(new Uint8Array(o),e);else if(t=="uint16")s=new u.onnx.Tensor(new Uint16Array(o),e);else if(t=="uint32")s=new u.onnx.Tensor(new Uint32Array(o),e);else if(t=="uint64")s=new u.onnx.Tensor(new BigUint64Array(o),e);else throw new Error(`Invalid type: ${t}`);return i!==0&&(t=="int64"||t=="uint64")?s.data.fill(BigInt(i)):i!==0&&s.data.fill(i),s}registerConstant(t,e){if(!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);return this.constantTensors[t]=e,e}makeConstant(t,e,i,o=0){return this.registerConstant(t,this.makeTensor(e,i,o))}registerState(t,e,i){if(e||(e=t),!this.session.inputNames.includes(t))throw new Error(`Model does not have an input named: ${t}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[t]={outputName:e,tensor:i},i}makeState(t,e,i,o,s=0){return this.registerState(t,e,this.makeTensor(i,o,s))}async run(t={}){if(this._runActive&&this.ignoreIfBusy)return D.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)t[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)t[e]=this.constantTensors[e];try{let e=await this.session.run(t);for(let i in this.stateTensors){let o=e[this.stateTensors[i].outputName];this.stateTensors[i].tensor=o}return e}finally{this._runActive=!1}}resetState(){D.debug("Resetting state tensors");for(let t in this.stateTensors)this.stateTensors[t].tensor.data.fill(0)}};var Oe="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var bt=new p("PCMPlayerNode"),X=class extends AudioWorkletNode{constructor(e,i,o){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!o||o!="int16"&&o!="float32")throw new Error(`Invalid format: ${o}`);this.sampleRate=i,this.format=o,this.port.onmessage=s=>this.onWorkletMessage(s),this.port.postMessage({action:"start",inputSampleRate:i,outputSampleRate:e.sampleRate,format:o})}static async registerModule(e){await e.audioWorklet.addModule(Oe)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(i=>this._playPromiseResolve=i),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let i=e.getReader();for(;!this.isCancelled;){let{done:o,value:s}=await i.read();if(o||!s)break;this.feed(s)}}catch(i){bt.warn("Stream error:",i),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:i}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var ne=new p("SpeechOutput"),Be=.5,wt=.8,ae=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",i=>this.onTextOutputFromAI(i)),this.ai.audio?.speechRecognition.addEventListener("speechstart",i=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return ne.warn("No voice provider configured");let i=`speech-${vt++}`;await this.ai.audio.beginAccess(i);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(i)}}async _speakWithLock(e){let i=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(i),e=i.detail.message,i.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=wt);let o=this.ai?._voiceTracker||ne.timer(`${this.ai.config.voice.providerID} voice`);o(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let s=new X(this.ai.audio.context,24e3,"int16");this.currentPlayer=s,s.connect(this.analyserNode),s.addEventListener("end",a=>{let l=a;o(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==s&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let n;if(this.ai.config.voice.providerID=="openai")n=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")n=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{ne.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(o(`Received response ${n.status} ${n.statusText}`),!n.ok){ne.warn(`Failed to generate voice sample: ${n.status} ${n.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),o("Playing PCM stream"),await s.play(n.body),o("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,i=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Be);let o=400;e.gain.linearRampToValueAtTime(0,o/1e3),await new Promise(s=>setTimeout(s,o+250)),e.disconnect(),i?.stop(),i?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Be)}},vt=1;function re(u,t){let e=t.reduce((l,c)=>l+c.byteLength,0),i=new DataView(new ArrayBuffer(44));i.setUint8(0,82),i.setUint8(1,73),i.setUint8(2,70),i.setUint8(3,70),i.setUint32(4,44+e,!0),i.setUint8(8,87),i.setUint8(9,65),i.setUint8(10,86),i.setUint8(11,69);let o=1,s=32,n=o*s/8,a=u*n;return i.setUint8(12,102),i.setUint8(13,109),i.setUint8(14,116),i.setUint8(15,32),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,o,!0),i.setUint32(24,u,!0),i.setUint32(28,a,!0),i.setUint16(32,n,!0),i.setUint16(34,s,!0),i.setUint8(36,100),i.setUint8(37,97),i.setUint8(38,116),i.setUint8(39,97),i.setUint32(40,e,!0),new File([i,...t],"audio.wav",{type:"audio/wav"})}var Ye="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var R=class extends AudioWorkletNode{constructor(e,i,o,s){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=o;let n=["int16","int64","float32"];if(!i||i<=0)throw new Error(`Invalid sample rate: ${i}`);if(!n.includes(o))throw new Error(`Invalid format ${o}, must be one of: ${n.join(", ")}`);if(!s||s<=0)throw new Error(`Invalid buffer size: ${s}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:i,format:o,bufferSize:s})}static async registerModule(e){await e.audioWorklet.addModule(Ye)}onWorkletMessage(e){if(e.data.action=="data"){let i=null;if(this.format=="int16"&&(i=new Int16Array(e.data.buffer)),this.format=="int64"&&(i=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(i=new Float32Array(e.data.buffer)),!i)throw new Error(`Invalid format: ${this.format}`);this.onData(i),this.dispatchEvent(new CustomEvent("data",{detail:{data:i}}))}}onData(e){}};var Se=16e3,le=256,V=8,U=new p("VoiceDetectionNode"),K=class K extends R{constructor(e){super(e,Se,"float32",le*V);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!K.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return Se}get numberOfSamples(){return le}get numberOfSampleChunks(){return V}get outputBufferSize(){return le*V}get isModelLoaded(){return!!this.vad}async loadModel(){U.debug("Loading VAD model"),this.vad=await M.load(K.vadModelURL),this.vad.ignoreIfBusy=!0,U.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],Se),this.vad.makeState("h","hn","float32",[2,V,64]),this.vad.makeState("c","cn","float32",[2,V,64])}async onData(e){if(this.vad)try{let i=await this.vad.run({input:new M.onnx.Tensor(e,[V,le])});if(!i)return;this.currentProbability=0;for(let n=0;n<i.output.data.length;n++)i.output.data[n]>this.currentProbability&&(this.currentProbability=i.output.data[n]);let o=this.isVoiceActive?this.sentivityEnd:this.sensitivity,s=this.currentProbability>o;if(!s&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=s,s&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),U.debug("Started speaking")):s?this.lastVoiceActiveDate=Date.now():!s&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!s&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),U.debug("Stopped speaking after timeout")),!s){let n=Date.now();n>this.nextVadReset&&(this.nextVadReset=n+5e3,this.vad.resetState())}}catch(i){U.error("VAD failed:",i)}}onSpeechStart(){}onSpeechEnd(){}};K.vadModelURL="";var P=K;var _e=new p("VoiceChunkOutputNode"),j=class extends P{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,i)=>e+i.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){_e.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let i of this.buffers)this.recordedBuffers.push(i),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:i,isFinal:!1}})),this.onVoiceChunk(i);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let i=this.recordedBuffers.reduce((o,s)=>o+s.length,0);_e.debug(`Voice complete, recorded ${(i/8e3).toFixed(2)} seconds of audio, ${i*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var ce=new p("OpenAITranscriptionNode"),de=class extends j{constructor(e,i){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=i}async onVoiceEnd(e){let i=ce.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let o=re(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let s="";try{let n=new FormData;n.append("file",o),n.append("model","whisper-1"),n.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:n,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);i("Response received"),s=await a.text(),i("Content received: "+s),this.lastRequestAbortController=void 0}catch(n){ce.error(`Failed to transcribe speech: ${n.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!s)return ce.debug("Transcription complete, but no text was found");ce.debug(`Transcription: ${s}`),this.onVoiceTranscription(s),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:s}}))}onVoiceTranscription(e){}};var ue=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var S=new p("IntelliWeaveTranscriptionNode"),Mt="wss://speech.intelliweave.ai/api/v1/transcribe",he=class he extends j{constructor(e,i){super(e);this.apiAddress=Mt;this.apiKey="";this.isTranscribing=!1;this.apiKey=i}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(S.debug("Opening WebSocket connection"),this.ws=new ue(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{S.debug("WebSocket connection opened")},this.ws.addEventListener("message",o=>{let s=JSON.parse(o.data);if(s.error)return S.warn("Error: "+s.error);if(s.type!="transcription")return S.warn("Invalid response type",s);if(s.streaming&&!s.final)return S.debug("Partial transcription: "+s.partialText);if(this.isTranscribing=!1,!s.text.trim())return S.warn(`Empty transcription (${s.processingTime}ms)`);S.debug(`Transcription: ${s.text} (${s.processingTime}ms)`),this.onVoiceTranscription(s.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:s.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",o=>S.warn("WebSocket error")));let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{S.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},i)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),he.debugExportWav){let i=re(this.sampleRate,e),o=document.createElement("a");o.href=URL.createObjectURL(i),o.download="recording.wav",o.click()}}onVoiceTranscription(e){}onSocketClose(){S.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};he.debugExportWav=!1;var pe=he;var ke=new p("SpeechRecognition"),me=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e}get isSupported(){if(!M.lib||!this.ai?.vadModel||!C().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),P.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new de(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new pe(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",i=>{this.ai._voiceTracker=ke.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),y(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("speechend",i=>{this.ai._voiceTracker?.("Speech ended");let o=this.recordingStartTime?Date.now()-this.recordingStartTime:0;y(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:o}}),this.dispatchEvent(new CustomEvent(i.type,{detail:i.detail}))}),this.voiceDetection.addEventListener("transcription",i=>{this.ai._voiceTracker?.(`Transcription: ${i.detail.text}`),y(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:i.detail.confidence||void 0}}),this.onTranscription(i)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){ke.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let o of this.analyserBuffer)e+=o*o;let i=Math.sqrt(e/this.analyserBuffer.length);return i>this.maxVolumeHeard&&(this.maxVolumeHeard=i),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,i/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let i=e.detail.text;ke.debug("Heard:",i),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:i,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var ge=new p("AudioSystem"),F=class u{constructor(t){this.locks=[];if(!t)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=t,this.ai.audio=this,this.speechRecognition=new me(this.ai),this.speechOutput=new ae(this.ai)}static get isSupported(){return!(!M.lib||!C().AudioWorkletNode)}static async registerModules(t){await Promise.all([X.registerModule(t),R.registerModule(t)])}async beginAccess(t){ge.debug(`Began access for: ${t}`),this.locks.includes(t)||this.locks.push(t),!this.context&&(ge.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await u.registerModules(this.context))}endAccess(t){ge.debug(`Ended access for: ${t}`),this.locks=this.locks.filter(e=>e!=t),!this.locks.length&&(ge.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var b=new p("Embed"),A=class extends w{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
454
+ `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let r=this.child("llm-selector-list");for(;r.lastChild;)r.lastChild.remove();for(let n of this.state.items||[]){let i=document.createElement("div");i.className="llm-selector-item"+(n.id==this.state.selectedID?" selected":""),i.innerHTML=`
455
+ <div class='llm-selector-item-icon' style="background-image: url('${n.icon}'); "></div>
456
+ <div class='llm-selector-item-name'>${n.name}</div>
457
+ <div class='llm-selector-item-provider'>${n.provider}</div>
458
+ `,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:n.id}))}),r.appendChild(i)}}};mm.observedAttributes=["open"];var Lu=new Ve("ONNXModel"),yi=class t{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,Lu.debug(`Model input parameters: ${e.inputNames.join(", ")}`),Lu.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!t.lib}static async load(e){if(!t.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(Lu.debug("Loading ONNX runtime"),this.onnx=await t.lib()),Lu.debug(`Loading model: ${e}`);let r=await this.onnx.InferenceSession.create(e);return new t(r)}makeTensor(e,r,n=0){let i=1;for(let s of r)i*=s;let o;if(e=="float32")o=new t.onnx.Tensor(new Float32Array(i),r);else if(e=="int8")o=new t.onnx.Tensor(new Int8Array(i),r);else if(e=="int16")o=new t.onnx.Tensor(new Int16Array(i),r);else if(e=="int32")o=new t.onnx.Tensor(new Int32Array(i),r);else if(e=="int64")o=new t.onnx.Tensor(new BigInt64Array(i),r);else if(e=="uint8")o=new t.onnx.Tensor(new Uint8Array(i),r);else if(e=="uint16")o=new t.onnx.Tensor(new Uint16Array(i),r);else if(e=="uint32")o=new t.onnx.Tensor(new Uint32Array(i),r);else if(e=="uint64")o=new t.onnx.Tensor(new BigUint64Array(i),r);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,r){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=r,r}makeConstant(e,r,n,i=0){return this.registerConstant(e,this.makeTensor(r,n,i))}registerState(e,r,n){if(r||(r=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(r))throw new Error(`Model does not have an output named: ${r}`);return this.stateTensors[e]={outputName:r,tensor:n},n}makeState(e,r,n,i,o=0){return this.registerState(e,r,this.makeTensor(n,i,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return Lu.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let r in this.stateTensors)e[r]=this.stateTensors[r].tensor;for(let r in this.constantTensors)e[r]=this.constantTensors[r];try{let r=await this.session.run(e);for(let n in this.stateTensors){let i=r[this.stateTensors[n].outputName];this.stateTensors[n].tensor=i}return r}finally{this._runActive=!1}}resetState(){Lu.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};var DD="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var MY=new Ve("PCMPlayerNode"),Uu=class extends AudioWorkletNode{constructor(r,n,i){super(r,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=n,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:n,outputSampleRate:r.sampleRate,format:i})}static async registerModule(r){await r.audioWorklet.addModule(DD)}feed(r){this.port.postMessage({action:"data",buffer:r.buffer},[r.buffer])}async play(r){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(n=>this._playPromiseResolve=n),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:r}}));try{let n=r.getReader();for(;!this.isCancelled;){let{done:i,value:o}=await n.read();if(i||!o)break;this.feed(o)}}catch(n){MY.warn("Stream error:",n),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:r,error:n}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(r){r.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var Lv=new Ve("SpeechOutput"),LD=.5,jY=.8,Uv=class extends EventTarget{constructor(r){super();this.maxVolumeHeard=0;this.ai=r,this.ai.addEventListener("output",n=>this.onTextOutputFromAI(n)),this.ai.audio?.speechRecognition.addEventListener("speechstart",n=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(r){r.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(r.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}async speak(r){if(!this.ai?.config?.voice?.providerID)return Lv.warn("No voice provider configured");let n=`speech-${DY++}`;await this.ai.audio.beginAccess(n);try{await this._speakWithLock(r)}finally{this.ai.audio.endAccess(n)}}async _speakWithLock(r){let n=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:r}});if(this.dispatchEvent(n),r=n.detail.message,n.defaultPrevented||!r)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=jY);let i=this.ai?._voiceTracker||Lv.timer(`${this.ai.config.voice.providerID} voice`);i(`Speak: ${r}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new Uu(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",a=>{let l=a;i(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!l.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let s;if(this.ai.config.voice.providerID=="openai")s=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:r,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")s=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:r})});else{Lv.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(i(`Received response ${s.status} ${s.statusText}`),!s.ok){Lv.warn(`Failed to generate voice sample: ${s.status} ${s.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:r}})),i("Playing PCM stream"),await o.play(s.body),i("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let r=this.currentPlayerVolume,n=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=LD);let i=400;r.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+250)),r.disconnect(),n?.stop(),n?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=LD)}},DY=1;function Zv(t,e){let r=e.reduce((l,c)=>l+c.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+r,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let i=1,o=32,s=i*o/8,a=t*s;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,a,!0),n.setUint16(32,s,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,r,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var UD="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Zu=class extends AudioWorkletNode{constructor(r,n,i,o){super(r,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:r.sampleRate,outputSampleRate:n,format:i,bufferSize:o})}static async registerModule(r){await r.audioWorklet.addModule(UD)}onWorkletMessage(r){if(r.data.action=="data"){let n=null;if(this.format=="int16"&&(n=new Int16Array(r.data.buffer)),this.format=="int64"&&(n=new BigInt64Array(r.data.buffer)),this.format=="float32"&&(n=new Float32Array(r.data.buffer)),!n)throw new Error(`Invalid format: ${this.format}`);this.onData(n),this.dispatchEvent(new CustomEvent("data",{detail:{data:n}}))}}onData(r){}};var aE=16e3,Fv=256,Fu=8,hm=new Ve("VoiceDetectionNode"),gm=class gm extends Zu{constructor(r){super(r,aE,"float32",Fv*Fu);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!gm.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return aE}get numberOfSamples(){return Fv}get numberOfSampleChunks(){return Fu}get outputBufferSize(){return Fv*Fu}get isModelLoaded(){return!!this.vad}async loadModel(){hm.debug("Loading VAD model"),this.vad=await yi.load(gm.vadModelURL),this.vad.ignoreIfBusy=!0,hm.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],aE),this.vad.makeState("h","hn","float32",[2,Fu,64]),this.vad.makeState("c","cn","float32",[2,Fu,64])}async onData(r){if(this.vad)try{let n=await this.vad.run({input:new yi.onnx.Tensor(r,[Fu,Fv])});if(!n)return;this.currentProbability=0;for(let s=0;s<n.output.data.length;s++)n.output.data[s]>this.currentProbability&&(this.currentProbability=n.output.data[s]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),hm.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),hm.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(n){hm.error("VAD failed:",n)}}onSpeechStart(){}onSpeechEnd(){}};gm.vadModelURL="";var Vu=gm;var ZD=new Ve("VoiceChunkOutputNode"),qu=class extends Vu{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((r,n)=>r+n.length,0)/8e3}async onData(r){if(await super.onData(r),this.isVoiceActive&&!this._voiceRecording){ZD.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let n of this.buffers)this.recordedBuffers.push(n),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:n,isFinal:!1}})),this.onVoiceChunk(n);this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!0}})),this.onVoiceChunk(r),this._voiceRecording=!1;let n=this.recordedBuffers.reduce((i,o)=>i+o.length,0);ZD.debug(`Voice complete, recorded ${(n/8e3).toFixed(2)} seconds of audio, ${n*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(r);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(r){}onVoiceEnd(r){}};var Vv=new Ve("OpenAITranscriptionNode"),qv=class extends qu{constructor(r,n){super(r);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=n}async onVoiceEnd(r){let n=Vv.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...r);let i=Zv(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);n("Response received"),o=await a.text(),n("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){Vv.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return Vv.debug("Transcription complete, but no text was found");Vv.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(r){}};var Wv=class extends WebSocket{constructor(r){super(r);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(r){this.readyState==WebSocket.OPEN?super.send(r):this.pendingData.push(r)}_onOpen(){for(let r of this.pendingData)super.send(r);this.pendingData=[]}};var Gi=new Ve("IntelliWeaveTranscriptionNode"),UY="wss://speech.intelliweave.ai/api/v1/transcribe",Gv=class Gv extends qu{constructor(r,n){super(r);this.apiAddress=UY;this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0,this.ws?this.ws.send(r):(Gi.debug("Opening WebSocket connection"),this.ws=new Wv(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(r.buffer),this.ws.onopen=()=>{Gi.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return Gi.warn("Error: "+o.error);if(o.type!="transcription")return Gi.warn("Invalid response type",o);if(o.streaming&&!o.final)return Gi.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return Gi.warn(`Empty transcription (${o.processingTime}ms)`);Gi.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",i=>Gi.warn("WebSocket error")));let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Gi.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},n)}async onVoiceEnd(r){if(this.ws?.send(JSON.stringify({type:"end"})),Gv.debugExportWav){let n=Zv(this.sampleRate,r),i=document.createElement("a");i.href=URL.createObjectURL(n),i.download="recording.wav",i.click()}}onVoiceTranscription(r){}onSocketClose(){Gi.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Gv.debugExportWav=!1;var Bv=Gv;var lE=new Ve("SpeechRecognition"),Hv=class extends EventTarget{constructor(r){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=r}get isSupported(){if(!yi.lib||!this.ai?.vadModel||!rs().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let r=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,r.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),Vu.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new qv(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):(this.voiceDetection=new Bv(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,r.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",n=>{this.ai._voiceTracker=lE.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),Gr(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("speechend",n=>{this.ai._voiceTracker?.("Speech ended");let i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;Gr(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("transcription",n=>{this.ai._voiceTracker?.(`Transcription: ${n.detail.text}`),Gr(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:n.detail.confidence||void 0}}),this.onTranscription(n)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(r){lE.error("Failed to start speech recognition:",r),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(r=>r.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(r){let n=r.detail.text;lE.debug("Heard:",n),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:n,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(r){throw this._skipEvents=!1,r}}}};var Xv=new Ve("AudioSystem"),ym=class t{constructor(e){this.locks=[];if(!e)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=e,this.ai.audio=this,this.speechRecognition=new Hv(this.ai),this.speechOutput=new Uv(this.ai)}static get isSupported(){return!(!yi.lib||!rs().AudioWorkletNode)}static async registerModules(e){await Promise.all([Uu.registerModule(e),Zu.registerModule(e)])}async beginAccess(e){Xv.debug(`Began access for: ${e}`),this.locks.includes(e)||this.locks.push(e),!this.context&&(Xv.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await t.registerModules(this.context))}endAccess(e){Xv.debug(`Ended access for: ${e}`),this.locks=this.locks.filter(r=>r!=e),!this.locks.length&&(Xv.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var un=new Ve("Embed"),al=class extends kn{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
304
459
 
305
460
  <!-- Styling -->
306
461
  <style>
@@ -379,12 +534,19 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
379
534
  #root #fullscreen-header {
380
535
  display: none;
381
536
  width: 100%;
382
- padding: 16px 24px 0 24px;
537
+ max-width: 860px;
538
+ padding: 12px 24px;
383
539
  box-sizing: border-box;
540
+ position: absolute;
541
+ top: 0;
542
+ left: 50%;
543
+ transform: translateX(-50%);
544
+ z-index: 10;
545
+ transition: opacity 0.2s ease;
384
546
  }
385
547
  #root.layout-fullscreen #fullscreen-header {
386
548
  display: flex;
387
- justify-content: flex-end;
549
+ justify-content: space-between;
388
550
  align-items: center;
389
551
  }
390
552
  #root.layout-fullscreen #fullscreen-persona {
@@ -393,14 +555,33 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
393
555
  gap: 10px;
394
556
  font-size: 16px;
395
557
  font-weight: 600;
396
- color: var(--intelliweave-text-color, white);
558
+ color: #333;
397
559
  }
398
560
  #root.layout-fullscreen #fullscreen-logo {
399
561
  width: 32px;
400
562
  height: 32px;
401
- border-radius: 50%;
402
- object-fit: cover;
563
+ border-radius: 8px;
564
+ object-fit: contain;
565
+ }
566
+ #root.layout-fullscreen #fullscreen-branding {
403
567
  display: none;
568
+ align-items: center;
569
+ gap: 6px;
570
+ font-size: 11px;
571
+ color: #666;
572
+ text-transform: uppercase;
573
+ letter-spacing: 0.5px;
574
+ }
575
+ #root.layout-fullscreen #fullscreen-branding.visible {
576
+ display: flex;
577
+ }
578
+ #root.layout-fullscreen #fullscreen-branding .brand-label {
579
+ opacity: 0.6;
580
+ font-weight: 400;
581
+ }
582
+ #root.layout-fullscreen #fullscreen-branding .brand-name {
583
+ font-weight: 600;
584
+ color: #333;
404
585
  }
405
586
 
406
587
  #root.open #web-weaver-logo {
@@ -464,7 +645,7 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
464
645
  line-height: 1.3;
465
646
  }
466
647
  #root.layout-fullscreen #web-weaver-embed-inner {
467
- padding: 24px 24px 16px 24px;
648
+ padding: 56px 24px 16px 24px;
468
649
  display: flex;
469
650
  flex-direction: column;
470
651
  gap: 12px;
@@ -483,10 +664,12 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
483
664
  font-size: 14px;
484
665
  }
485
666
  #root.layout-fullscreen #web-weaver-embed-inner .introduction-message {
486
- padding: 12px 16px;
667
+ padding: 8px 12px;
487
668
  border-radius: 14px;
488
669
  background: var(--intelliweave-persona-bg-muted, rgba(32, 38, 44, 0.8));
489
670
  text-align: center;
671
+ width: 100%;
672
+ box-sizing: border-box;
490
673
  }
491
674
 
492
675
  #web-weaver-embed-inner .suggestion-button {
@@ -544,6 +727,22 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
544
727
  margin-top: 8px;
545
728
  }
546
729
 
730
+ /* Image styles for markdown-rendered images in AI responses */
731
+ #web-weaver-embed-inner .output img {
732
+ max-width: 100%;
733
+ max-height: 300px;
734
+ width: auto;
735
+ height: auto;
736
+ border-radius: 8px;
737
+ margin: 8px 0;
738
+ display: block;
739
+ object-fit: contain;
740
+ }
741
+ #root.layout-fullscreen #web-weaver-embed-inner .output img {
742
+ max-width: 100%;
743
+ max-height: 400px;
744
+ }
745
+
547
746
  /** Info block */
548
747
  #web-weaver-embed-inner .info-block {
549
748
  display: flex;
@@ -637,20 +836,32 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
637
836
  <div id='root' class='hidden'>
638
837
 
639
838
  <!-- Logo -->
640
- ${Y.add({id:"web-weaver-logo",logo:this.attr.logo})}
839
+ ${Fp.add({id:"web-weaver-logo",logo:this.attr.logo})}
641
840
  <div id='pulseanim' class="circle pulse"></div>
642
841
 
643
842
 
644
843
 
844
+ <!-- Fullscreen header -->
845
+ <div id='fullscreen-header'>
846
+ <div id='fullscreen-persona'>
847
+ <img id='fullscreen-logo' src='' alt='' />
848
+ <span id='fullscreen-name'></span>
849
+ </div>
850
+ <div id='fullscreen-branding' class='branding-chatterly'>
851
+ <span class='brand-label'>CREATED WITH</span>
852
+ <span class='brand-name'>Chatterly</span>
853
+ </div>
854
+ </div>
855
+
645
856
  <!-- Inner container contains all the UI when the panel is open -->
646
857
  <div id='web-weaver-embed-inner'>
647
858
  </div>
648
859
 
649
860
  <!-- LLM selector panel -->
650
- ${_.add({id:"llm-selector-panel"})}
861
+ ${mm.add({id:"llm-selector-panel"})}
651
862
 
652
863
  <!-- Interaction panel -->
653
- ${B.add({id:"interaction-bar"})}
864
+ ${Zp.add({id:"interaction-bar"})}
654
865
 
655
866
 
656
867
  <!-- Powered by IW banner -->
@@ -660,9 +871,16 @@ ${s}`,cannotRemove:o.isContext,sortOrder:101,disabled:typeof o.disabled=="functi
660
871
 
661
872
  </div>
662
873
 
663
- `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new W,F.isSupported&&(this.ai.audio=new F(this.ai))}onCreate(){m().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),m().embed=this;let e=m();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.layout&&!this.attr.layout&&(b.debug("[WebWeaverEmbed] Setting layout from client config:",e.layout),this.attr.layout=e.layout),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",s=>this.onContainerClick(s)),this.child("web-weaver-logo").addEventListener("click",s=>this.onLogoClick(s)),this.child("interaction-bar").addEventListener("input-message",s=>this.processInput(s.detail)),this.child("interaction-bar").addEventListener("llm-button-click",s=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",s=>this.onLLMModelSelect(s)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:s=>(this.suggestions.push(s.text),"Suggestion button added")});let o=this.attr.apiKey||m().apiKey;if(!o)return b.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(o).then(s=>{this.config=s.config,m().introductionMessage=this.config.introductionMessage,m().analytics=this.config.analytics!==void 0?!!this.config.analytics:m().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(s=>{b.error("Failed to load AI configuration:",s),this.state.loading=!1;let n=this.child("web-weaver-embed-inner");n&&(n.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(e,i){if(!i){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.removeProperty("--intelliweave-interaction-bg");return}let o=this.parseColorToRGB(i);if(!o){e.style.removeProperty("--intelliweave-persona-bg-muted"),e.style.removeProperty("--intelliweave-assistant-bubble-bg"),e.style.setProperty("--intelliweave-interaction-bg",i);return}let{r:s,g:n,b:a}=o;e.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${s}, ${n}, ${a}, 0.65)`),e.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(s*.85)}, ${Math.round(n*.85)}, ${Math.round(a*.85)}, 0.85)`),e.style.setProperty("--intelliweave-interaction-bg",`rgba(${s}, ${n}, ${a}, 0.9)`)}parseColorToRGB(e){if(!e)return null;let i=e.trim();if(i.startsWith("#")){let o=i.slice(1);if(o.length===3){let s=parseInt(o[0]+o[0],16),n=parseInt(o[1]+o[1],16),a=parseInt(o[2]+o[2],16);return{r:s,g:n,b:a}}if(o.length===6){let s=parseInt(o.slice(0,2),16),n=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16);return{r:s,g:n,b:a}}return null}if(i.startsWith("rgb")){let o=i.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return o?{r:Math.max(0,Math.min(255,Math.round(Number(o[1])))),g:Math.max(0,Math.min(255,Math.round(Number(o[2])))),b:Math.max(0,Math.min(255,Math.round(Number(o[3]))))}:null}return null}applyConfigStylesAndAttributes(){let e=this.config,i=this.child("root");if(!i)return;let o=!1,n=this.attr.logo||e.logo;if(n&&n!==this._lastLogo){this._lastLogo=n,o=!0;let J=this.child("web-weaver-logo");J&&J.setAttribute("logo",n)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=e.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),o=!0),n!==this._lastHeaderLogo&&(this._lastHeaderLogo=n||"",a&&(n?(a.src=n,a.style.display=""):a.style.display="none"),o=!0);let r=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(r){let J=d==="hidden"||d==="none"||d==="false";r.style.display=!J&&(n||c)?"":"none"}let g=this.attr.background||e.background;g!==this._lastBackground&&(this._lastBackground=g,o=!0,g?(i.style.background=g,i.style.setProperty("--intelliweave-persona-bg",g),this.applyPersonaColorVariants(i,g)):(i.style.background="",i.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(i,void 0)));let x=this.attr.textColor||e.textColor,L=this.child("interaction-bar");x!==this._lastTextColor&&(this._lastTextColor=x,o=!0,x?(i.style.color=x,i.style.setProperty("--intelliweave-user-bubble-text",x),i.style.setProperty("--intelliweave-assistant-bubble-text",x),L&&L.setAttribute("textColor",x)):(i.style.color="",i.style.removeProperty("--intelliweave-user-bubble-text"),i.style.removeProperty("--intelliweave-assistant-bubble-text"),L&&L.removeAttribute("textColor")));let H=this.attr.displayMode||e.displayMode||"closed";H!==this._lastDisplayMode&&(this._lastDisplayMode=H,o=!0,H==="open"&&!this.attr.open&&(this.attr.open=!0));let fe=this.attr.layout||e.layout||"widget";fe!==this._lastLayout&&(this._lastLayout=fe,o=!0);let ye=this.attr.positioningMode||e.positioningMode||"fixed";ye!==this._lastPositioningMode&&(this._lastPositioningMode=ye,o=!0);let be=this.attr.positionX||e.positionX||"right";be!==this._lastPositionX&&(this._lastPositionX=be,o=!0);let we=this.attr.positionY||e.positionY||"bottom";we!==this._lastPositionY&&(this._lastPositionY=we,o=!0);let Ce=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ve=Ce!==void 0?Ce:e.offsetX!==void 0?e.offsetX:20;ve!==this._lastOffsetX&&(this._lastOffsetX=ve,o=!0);let Ne=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,xe=Ne!==void 0?Ne:e.offsetY!==void 0?e.offsetY:20;xe!==this._lastOffsetY&&(this._lastOffsetY=xe,o=!0),o&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:n,finalBackground:i.style.background,finalTextColor:i.style.color,finalDisplayMode:H,finalLayout:fe,finalPositioningMode:ye,finalPositionX:be,finalPositionY:we,finalOffsetX:ve,finalOffsetY:xe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),y(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;y(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let e=this.child("root");this.attr.open?e.classList.add("open"):e.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(e.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):e.classList.remove("layout-fullscreen");let o=this._lastPositioningMode||"fixed",s=this._lastPositionX||"right",n=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;o==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),o!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",s==="left"?e.style.left=a+"px":e.style.right=a+"px",n==="top"?e.style.top=l+"px":e.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,r)=>(r.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){m().embed==this&&(m().embed=void 0)}onContainerClick(e){let i=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&i!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let i=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||i==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let i=document.createElement("div");i.className="introduction-message",i.innerHTML=m().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(i),this.ai.insertAssistantMessage(i.innerText);for(let o of m().introductionSuggestions||[]){let s=document.createElement("div");s.className="suggestion-button",s.innerText=o,s.addEventListener("click",n=>this.onSuggestionClick(n,o)),e.appendChild(s)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let i=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(i.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let o=document.createElement("div");o.className="input",o.innerText=e,i.appendChild(o);let s=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",i.appendChild(this.currentOutputElement);let n=Math.ceil(i.clientHeight-300);n<0&&(n=0),n>600&&(n=600),s&&(s.style.minHeight=""),this.currentOutputElement.style.minHeight=n+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(e);for(let c of this.suggestions){let r=document.createElement("div");r.className="suggestion-button",r.innerText=c,r.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(r)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(o){b.error("Failed to process input:",o);let s=document.createElement("div");s.className="output",s.innerText="Sorry, there was a problem getting a response. "+o.message,i.appendChild(s);let n=document.createElement("div");n.className="suggestion-button",n.innerText="Reset conversation",n.addEventListener("click",a=>this.resetConversation()),i.appendChild(n)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e,i){let o=[];for(let s of e)for(let n=0;n<(s.sections?.length||0);n++){let a=s.sections[n],l=`msgelem-${s.id||""}_${n}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
874
+ `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new Cu,ym.isSupported&&(this.ai.audio=new ym(this.ai))}onCreate(){bt().embed&&un.warn("Only one <web-weaver-embed> element should be on the page."),bt().embed=this;let r=bt();un.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(un.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(un.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(un.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(un.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(un.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(un.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(un.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),un.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("web-weaver-embed-inner").addEventListener("scroll",o=>this.onContentScroll(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")}),this.ai.knowledgeBase.addEntry({id:"_iw_image_instructions",type:"info",name:"Using Images",content:`
875
+ You can display images in Markdown format, example: ![filename](url)
876
+ Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let i=this.attr.apiKey||bt().apiKey;if(!i)return un.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,bt().introductionMessage||(bt().introductionMessage=this.config.introductionMessage),bt().analytics=this.config.analytics!==void 0?!!this.config.analytics:bt().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.config.managedBy&&this.updateBrandingFor(this.config.managedBy),this.resetConversation()}).catch(o=>{un.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let ie=this.child("web-weaver-logo");ie&&ie.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),l=this.root?.getElementById("fullscreen-name"),c=r.name||"";c!==this._lastPersonaName&&(this._lastPersonaName=c,l&&(l.textContent=c),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let ie=d==="hidden"||d==="none"||d==="false";u.style.display=!ie&&(s||c)?"":"none"}let f=this.attr.background||r.background;f!==this._lastBackground&&(this._lastBackground=f,i=!0,f?(n.style.background=f,n.style.setProperty("--intelliweave-persona-bg",f),this.applyPersonaColorVariants(n,f)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let h=this.attr.textColor||r.textColor,y=this.child("interaction-bar");h!==this._lastTextColor&&(this._lastTextColor=h,i=!0,h?(n.style.color=h,n.style.setProperty("--intelliweave-user-bubble-text",h),n.style.setProperty("--intelliweave-assistant-bubble-text",h),y&&y.setAttribute("textColor",h)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),y&&y.removeAttribute("textColor")));let _=this.attr.displayMode||r.displayMode||"closed";_!==this._lastDisplayMode&&(this._lastDisplayMode=_,i=!0,_==="open"&&!this.attr.open&&(this.attr.open=!0));let E=this.attr.layout||r.layout||"widget";E!==this._lastLayout&&(this._lastLayout=E,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let V=this.attr.positionX||r.positionX||"right";V!==this._lastPositionX&&(this._lastPositionX=V,i=!0);let L=this.attr.positionY||r.positionY||"bottom";L!==this._lastPositionY&&(this._lastPositionY=L,i=!0);let G=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,H=G!==void 0?G:r.offsetX!==void 0?r.offsetX:20;H!==this._lastOffsetX&&(this._lastOffsetX=H,i=!0);let W=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,Y=W!==void 0?W:r.offsetY!==void 0?r.offsetY:20;Y!==this._lastOffsetY&&(this._lastOffsetY=Y,i=!0),i&&un.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:_,finalLayout:E,finalPositioningMode:P,finalPositionX:V,finalPositionY:L,finalOffsetX:H,finalOffsetY:Y})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.child("interaction-bar").attr.layout=this._lastLayout||"widget",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Gr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let c=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Gr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:c}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,l=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=l+"px":r.style.bottom=l+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((c,u)=>(u.priority||0)-(c.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){bt().embed==this&&(bt().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=bt().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of bt().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let c of Array.from(n.querySelectorAll(".suggestion-button")))c.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"});let a=await this.ai.sendMessage(r);for(let c of this.suggestions){let u=document.createElement("div");u.className="suggestion-button",u.innerText=c,u.addEventListener("click",d=>this.onSuggestionClick(d,c)),this.currentOutputElement.appendChild(u)}let l=a.text()||"";this.ai.audio?.speechRecognition?.isRunning&&this.ai.audio.speechOutput.speak(l)}catch(i){un.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],l=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(l=l.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let c=a.text||"";c.includes(`
664
877
  `)&&(c=c.split(`
665
- `)[0]),this.updateInfoElement(l,c,"thinking-icon"),o.push(l)}else if(a.type=="tool_call"){let r=new E(e).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(r?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+r.toolErrorResponse||"","tool-icon"),o.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&r))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),o.push(l)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let d=a.toolKbID.substring(4),g=`**Ask ${this.ai.subAgents.subagents.find(v=>v.id===d)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(l,g,"tool-icon"),o.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),o.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),o.push(l)}}for(let s of Array.from(this.currentOutputElement.children))o.includes(s.id)||s.remove()}updateTextElement(e,i){let o=this.currentOutputElement.querySelector(`#${e}`);o||(o=document.createElement("div"),o.id=e,o.className="output",this.currentOutputElement.appendChild(o));let s=Qe().use(He).use(Je).use(Ue,{target:"_blank",rel:["noopener","noreferrer"]}).use(Ke).use(Fe).processSync(i||"");o.innerHTML=s.toString("utf-8")}updateInfoElement(e,i,o){let s=this.currentOutputElement.querySelector(`#${e}`);s||(s=document.createElement("div"),s.id=e,s.className="info-block",s.innerHTML=`
878
+ `)[0]),this.updateInfoElement(l,c,"thinking-icon"),i.push(l)}else if(a.type=="tool_call"){let u=new Nu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(l,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(l);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(l,d,"tool-icon"),i.push(l)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let d=a.toolKbID.substring(4),f=`**Ask ${this.ai.subAgents.subagents.find(m=>m.id===d)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(l,f,"tool-icon"),i.push(l)}else this.updateInfoElement(l,a.toolKbName||"","tool-icon"),i.push(l)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(l,a.text||""),i.push(l)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=Dv().use(cm).use(um).use(Jp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Yp).use(rm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
666
879
  <div class='info-block-icon'></div>
667
880
  <div class='info-block-text'></div>
668
- `,this.currentOutputElement.appendChild(s));let n=Qe().use(He).use(Je).use(Ue,{target:"_blank",rel:["noopener","noreferrer"]}).use(Ke).use(Fe).processSync(i||"");s.querySelector(".info-block-icon").className="info-block-icon "+o,s.querySelector(".info-block-text").innerHTML=n.toString("utf-8")}onSuggestionClick(e,i){this.processInput(i)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};A.tagName="intelliweave-embed",A.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];var Ms=A;M.lib=()=>import("onnxruntime-web");A.register();export{Ms as default};
881
+ `,this.currentOutputElement.appendChild(o));let s=Dv().use(cm).use(um).use(Jp,{target:"_blank",rel:["noopener","noreferrer"]}).use(Yp).use(rm).processSync(n||"");o.querySelector(".info-block-icon").className="info-block-icon "+i,o.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(r,n){this.processInput(n)}onLLMModelSelect(r){r.preventDefault(),this.ai.setModel(r.detail),this.state.llmPanelOpen=!1}onContentScroll(r){let n=this.child("fullscreen-header");if(!n)return;let i=r.target.scrollTop,o=0,s=60;if(i<=o)n.style.opacity="1",n.style.pointerEvents="";else if(i>=s)n.style.opacity="0",n.style.pointerEvents="none";else{let a=1-(i-o)/(s-o);n.style.opacity=String(a),n.style.pointerEvents=a<.5?"none":""}}updateBrandingFor(r){if(!r)return;this.root?.querySelectorAll(`.branding-${r}`)?.forEach(i=>{i.classList.add("visible")})}};al.tagName="intelliweave-embed",al.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];var kze=al;yi.lib=()=>import("./ort.bundle.min-5QOPZPPI.js");al.register();export{kze as default};
882
+ /*! Bundled license information:
883
+
884
+ uri-js/dist/es5/uri.all.js:
885
+ (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *)
886
+ */