@drincs/pixi-vn-ink 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/parser.cjs CHANGED
@@ -1,98 +1,98 @@
1
- 'use strict';var zod=require('zod');var gy=Object.create;var zd=Object.defineProperty;var yy=Object.getOwnPropertyDescriptor;var Cy=Object.getOwnPropertyNames;var vy=Object.getPrototypeOf,_y=Object.prototype.hasOwnProperty;var y=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ey=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Cy(e))!_y.call(n,i)&&i!==t&&zd(n,i,{get:()=>e[i],enumerable:!(r=yy(e,i))||r.enumerable});return n};var Bi=(n,e,t)=>(t=n!=null?gy(vy(n)):{},Ey(zd(t,"default",{value:n,enumerable:true}),n));var Ar=y(H=>{Object.defineProperty(H,"__esModule",{value:true});H.regexpCode=H.getEsmExportName=H.getProperty=H.safeStringify=H.stringify=H.strConcat=H.addCodeArg=H.str=H._=H.nil=H._Code=H.Name=H.IDENTIFIER=H._CodeOrName=void 0;var Dr=class{};H._CodeOrName=Dr;H.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var sn=class extends Dr{constructor(e){if(super(),!H.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};H.Name=sn;var ze=class extends Dr{constructor(e){super(),this._items=typeof e=="string"?[e]:e;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;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((t,r)=>`${t}${r}`,"")}get names(){var e;return (e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>(r instanceof sn&&(t[r.str]=(t[r.str]||0)+1),t),{})}};H._Code=ze;H.nil=new ze("");function af(n,...e){let t=[n[0]],r=0;for(;r<e.length;)cu(t,e[r]),t.push(n[++r]);return new ze(t)}H._=af;var lu=new ze("+");function of(n,...e){let t=[wr(n[0])],r=0;for(;r<e.length;)t.push(lu),cu(t,e[r]),t.push(lu,wr(n[++r]));return $y(t),new ze(t)}H.str=of;function cu(n,e){e instanceof ze?n.push(...e._items):e instanceof sn?n.push(e):n.push(qy(e));}H.addCodeArg=cu;function $y(n){let e=1;for(;e<n.length-1;){if(n[e]===lu){let t=Ry(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function Ry(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof sn||n[n.length-1]!=='"'?void 0:typeof e!="string"?`${n.slice(0,-1)}${e}"`:e[0]==='"'?n.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(n instanceof sn))return `"${n}${e.slice(1)}`}function Vy(n,e){return e.emptyStr()?n:n.emptyStr()?e:of`${n}${e}`}H.strConcat=Vy;function qy(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:wr(Array.isArray(n)?n.join(","):n)}function jy(n){return new ze(wr(n))}H.stringify=jy;function wr(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}H.safeStringify=wr;function Ly(n){return typeof n=="string"&&H.IDENTIFIER.test(n)?new ze(`.${n}`):af`[${n}]`}H.getProperty=Ly;function By(n){if(typeof n=="string"&&H.IDENTIFIER.test(n))return new ze(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}H.getEsmExportName=By;function Wy(n){return new ze(n.toString())}H.regexpCode=Wy;});var fu=y(Ve=>{Object.defineProperty(Ve,"__esModule",{value:true});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Re=Ar(),hu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},Hi;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(Hi||(Ve.UsedValueState=Hi={}));Ve.varKinds={const:new Re.Name("const"),let:new Re.Name("let"),var:new Re.Name("var")};var Ki=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof Re.Name?e:this.name(e)}name(e){return new Re.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return `${e}${t.index++}`}_nameGroup(e){var t,r;if(!((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ve.Scope=Ki;var zi=class extends Re.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, Re._)`.${new Re.Name(t)}[${r}]`;}};Ve.ValueScopeName=zi;var My=(0, Re._)`\n`,du=class extends Ki{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?My:Re.nil};}get(){return this._scope}name(e){return new zi(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[a];if(o){let c=o.get(s);if(c)return c}else o=this._values[a]=new Map;o.set(s,i);let u=this._scope[a]||(this._scope[a]=[]),l=u.length;return u[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return (0, Re._)`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let a=Re.nil;for(let s in e){let o=e[s];if(!o)continue;let u=r[s]=r[s]||new Map;o.forEach(l=>{if(u.has(l))return;u.set(l,Hi.Started);let c=t(l);if(c){let h=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;a=(0, Re._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, Re._)`${a}${c}${this.opts._n}`;else throw new hu(l);u.set(l,Hi.Completed);});}return a}};Ve.ValueScope=du;});var I=y(V=>{Object.defineProperty(V,"__esModule",{value:true});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var M=Ar(),ot=fu(),qt=Ar();Object.defineProperty(V,"_",{enumerable:true,get:function(){return qt._}});Object.defineProperty(V,"str",{enumerable:true,get:function(){return qt.str}});Object.defineProperty(V,"strConcat",{enumerable:true,get:function(){return qt.strConcat}});Object.defineProperty(V,"nil",{enumerable:true,get:function(){return qt.nil}});Object.defineProperty(V,"getProperty",{enumerable:true,get:function(){return qt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:true,get:function(){return qt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:true,get:function(){return qt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:true,get:function(){return qt.Name}});var Qi=fu();Object.defineProperty(V,"Scope",{enumerable:true,get:function(){return Qi.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:true,get:function(){return Qi.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:true,get:function(){return Qi.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:true,get:function(){return Qi.varKinds}});V.operators={GT:new M._Code(">"),GTE:new M._Code(">="),LT:new M._Code("<"),LTE:new M._Code("<="),EQ:new M._Code("==="),NEQ:new M._Code("!=="),NOT:new M._Code("!"),OR:new M._Code("||"),AND:new M._Code("&&"),ADD:new M._Code("+")};var Ot=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},pu=class extends Ot{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?ot.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return `${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=In(this.rhs,e,t)),this}get names(){return this.rhs instanceof M._CodeOrName?this.rhs.names:{}}},Ji=class extends Ot{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r;}render({_n:e}){return `${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof M.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=In(this.rhs,e,t),this}get names(){let e=this.lhs instanceof M.Name?{}:{...this.lhs.names};return Xi(e,this.rhs)}},mu=class extends Ji{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},gu=class extends Ot{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},yu=class extends Ot{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},Cu=class extends Ot{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},vu=class extends Ot{constructor(e){super(),this.code=e;}render({_n:e}){return `${this.code};`+e}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(e,t){return this.code=In(this.code,e,t),this}get names(){return this.code instanceof M._CodeOrName?this.code.names:{}}},Pr=class extends Ot{constructor(e=[]){super(),this.nodes=e;}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1);}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(Gy(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>un(e,t.names),{})}},xt=class extends Pr{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},_u=class extends Pr{},Tn=class extends xt{};Tn.kind="else";var an=class n extends xt{constructor(e,t){super(t),this.condition=e;}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===true)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new Tn(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(uf(e),t instanceof n?[t]:t.nodes);if(!(e===false||!this.nodes.length))return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=In(this.condition,e,t),this}get names(){let e=super.names;return Xi(e,this.condition),this.else&&un(e,this.else.names),e}};an.kind="if";var on=class extends xt{};on.kind="for";var Eu=class extends on{constructor(e){super(),this.iteration=e;}render(e){return `for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=In(this.iteration,e,t),this}get names(){return un(super.names,this.iteration.names)}},bu=class extends on{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?ot.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return `for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Xi(super.names,this.from);return Xi(e,this.to)}},Zi=class extends on{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i;}render(e){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=In(this.iterable,e,t),this}get names(){return un(super.names,this.iterable.names)}},Fr=class extends xt{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r;}render(e){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Fr.kind="func";var Or=class extends Pr{render(e){return "return "+super.render(e)}};Or.kind="return";var Su=class extends xt{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&un(e,this.catch.names),this.finally&&un(e,this.finally.names),e}},xr=class extends xt{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};xr.kind="catch";var Nr=class extends xt{render(e){return "finally"+super.render(e)}};Nr.kind="finally";var Du=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
- `:""},this._extScope=e,this._scope=new ot.Scope({parent:e}),this._nodes=[new _u];}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return (this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let a=this._scope.toName(t);return r!==void 0&&i&&(this._constants[a.str]=r),this._leafNode(new pu(e,a,r)),a}const(e,t,r){return this._def(ot.varKinds.const,e,t,r)}let(e,t,r){return this._def(ot.varKinds.let,e,t,r)}var(e,t,r){return this._def(ot.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new Ji(e,t,r))}add(e,t){return this._leafNode(new mu(e,V.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==M.nil&&this._leafNode(new vu(e)),this}object(...e){let t=["{"];for(let[r,i]of e)t.length>1&&t.push(","),t.push(r),(r!==i||this.opts.es5)&&(t.push(":"),(0, M.addCodeArg)(t,i));return t.push("}"),new M._Code(t)}if(e,t,r){if(this._blockNode(new an(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new an(e))}else(){return this._elseNode(new Tn)}endIf(){return this._endBlockNode(an,Tn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Eu(e),t)}forRange(e,t,r,i,a=this.opts.es5?ot.varKinds.var:ot.varKinds.let){let s=this._scope.toName(e);return this._for(new bu(a,s,t,r),()=>i(s))}forOf(e,t,r,i=ot.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof M.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, M._)`${s}.length`,o=>{this.var(a,(0, M._)`${s}[${o}]`),r(a);})}return this._for(new Zi("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?ot.varKinds.var:ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, M._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new Zi("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(on)}label(e){return this._leafNode(new gu(e))}break(e){return this._leafNode(new yu(e))}return(e){let t=new Or;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Or)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Su;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new xr(a),t(a);}return r&&(this._currNode=i.finally=new Nr,this.code(r)),this._endBlockNode(xr,Nr)}throw(e){return this._leafNode(new Cu(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=M.nil,r,i){return this._blockNode(new Fr(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Fr)}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,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof an))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e;}};V.CodeGen=Du;function un(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function Xi(n,e){return e instanceof M._CodeOrName?un(n,e.names):n}function In(n,e,t){if(n instanceof M.Name)return r(n);if(!i(n))return n;return new M._Code(n._items.reduce((a,s)=>(s instanceof M.Name&&(s=r(s)),s instanceof M._Code?a.push(...s._items):a.push(s),a),[]));function r(a){let s=t[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function i(a){return a instanceof M._Code&&a._items.some(s=>s instanceof M.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function Gy(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function uf(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, M._)`!${wu(n)}`}V.not=uf;var Uy=lf(V.operators.AND);function Hy(...n){return n.reduce(Uy)}V.and=Hy;var Ky=lf(V.operators.OR);function zy(...n){return n.reduce(Ky)}V.or=zy;function lf(n){return (e,t)=>e===M.nil?t:t===M.nil?e:(0, M._)`${wu(e)} ${n} ${wu(t)}`}function wu(n){return n instanceof M.Name?n:(0, M._)`(${n})`}});var L=y(j=>{Object.defineProperty(j,"__esModule",{value:true});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var X=I(),Jy=Ar();function Zy(n){let e={};for(let t of n)e[t]=true;return e}j.toHash=Zy;function Xy(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(df(n,e),!ff(e,n.self.RULES.all))}j.alwaysValidSchema=Xy;function df(n,e=n.schema){let{opts:t,self:r}=n;if(!t.strictSchema||typeof e=="boolean")return;let i=r.RULES.keywords;for(let a in e)i[a]||gf(n,`unknown keyword: "${a}"`);}j.checkUnknownRules=df;function ff(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}j.schemaHasRules=ff;function Qy(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}j.schemaHasRulesButRef=Qy;function Yy({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, X._)`${t}`}return (0, X._)`${n}${e}${(0, X.getProperty)(r)}`}j.schemaRefOrVal=Yy;function eC(n){return pf(decodeURIComponent(n))}j.unescapeFragment=eC;function tC(n){return encodeURIComponent(Pu(n))}j.escapeFragment=tC;function Pu(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Pu;function pf(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=pf;function nC(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}j.eachItem=nC;function cf({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof X.Name?(a instanceof X.Name?n(i,a,s):e(i,a,s),s):a instanceof X.Name?(e(i,s,a),a):t(a,s);return o===X.Name&&!(u instanceof X.Name)?r(i,u):u}}j.mergeEvaluated={props:cf({mergeNames:(n,e,t)=>n.if((0, X._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, X._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, X._)`${t} || {}`).code((0, X._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, X._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, X._)`${t} || {}`),Fu(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:mf}),items:cf({mergeNames:(n,e,t)=>n.if((0, X._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, X._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, X._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, X._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function mf(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, X._)`{}`);return e!==void 0&&Fu(n,t,e),t}j.evaluatedPropsToName=mf;function Fu(n,e,t){Object.keys(t).forEach(r=>n.assign((0, X._)`${e}${(0, X.getProperty)(r)}`,true));}j.setEvaluated=Fu;var hf={};function rC(n,e){return n.scopeValue("func",{ref:e,code:hf[e.code]||(hf[e.code]=new Jy._Code(e.code))})}j.useFunc=rC;var Au;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(Au||(j.Type=Au={}));function iC(n,e,t){if(n instanceof X.Name){let r=e===Au.Num;return t?r?(0, X._)`"[" + ${n} + "]"`:(0, X._)`"['" + ${n} + "']"`:r?(0, X._)`"/" + ${n}`:(0, X._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, X.getProperty)(n).toString():"/"+Pu(n)}j.getErrorPath=iC;function gf(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}j.checkStrictMode=gf;});var Je=y(Ou=>{Object.defineProperty(Ou,"__esModule",{value:true});var be=I(),sC={data:new be.Name("data"),valCxt:new be.Name("valCxt"),instancePath:new be.Name("instancePath"),parentData:new be.Name("parentData"),parentDataProperty:new be.Name("parentDataProperty"),rootData:new be.Name("rootData"),dynamicAnchors:new be.Name("dynamicAnchors"),vErrors:new be.Name("vErrors"),errors:new be.Name("errors"),this:new be.Name("this"),self:new be.Name("self"),scope:new be.Name("scope"),json:new be.Name("json"),jsonPos:new be.Name("jsonPos"),jsonLen:new be.Name("jsonLen"),jsonPart:new be.Name("jsonPart")};Ou.default=sC;});var Tr=y(Se=>{Object.defineProperty(Se,"__esModule",{value:true});Se.extendErrors=Se.resetErrorsCount=Se.reportExtraError=Se.reportError=Se.keyword$DataError=Se.keywordError=void 0;var U=I(),Yi=L(),Te=Je();Se.keywordError={message:({keyword:n})=>(0, U.str)`must pass "${n}" keyword validation`};Se.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, U.str)`"${n}" keyword must be ${e} ($data)`:(0, U.str)`"${n}" keyword is invalid ($data)`};function aC(n,e=Se.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=vf(n,e,t);r??(s||o)?yf(a,u):Cf(i,(0, U._)`[${u}]`);}Se.reportError=aC;function oC(n,e=Se.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=vf(n,e,t);yf(i,o),a||s||Cf(r,Te.default.vErrors);}Se.reportExtraError=oC;function uC(n,e){n.assign(Te.default.errors,e),n.if((0, U._)`${Te.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, U._)`${Te.default.vErrors}.length`,e),()=>n.assign(Te.default.vErrors,null)));}Se.resetErrorsCount=uC;function lC({gen:n,keyword:e,schemaValue:t,data:r,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let s=n.name("err");n.forRange("i",i,Te.default.errors,o=>{n.const(s,(0, U._)`${Te.default.vErrors}[${o}]`),n.if((0, U._)`${s}.instancePath === undefined`,()=>n.assign((0, U._)`${s}.instancePath`,(0, U.strConcat)(Te.default.instancePath,a.errorPath))),n.assign((0, U._)`${s}.schemaPath`,(0, U.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, U._)`${s}.schema`,t),n.assign((0, U._)`${s}.data`,r));});}Se.extendErrors=lC;function yf(n,e){let t=n.const("err",e);n.if((0, U._)`${Te.default.vErrors} === null`,()=>n.assign(Te.default.vErrors,(0, U._)`[${t}]`),(0, U._)`${Te.default.vErrors}.push(${t})`),n.code((0, U._)`${Te.default.errors}++`);}function Cf(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, U._)`new ${n.ValidationError}(${e})`):(t.assign((0, U._)`${r}.errors`,e),t.return(false));}var ln={keyword:new U.Name("keyword"),schemaPath:new U.Name("schemaPath"),params:new U.Name("params"),propertyName:new U.Name("propertyName"),message:new U.Name("message"),schema:new U.Name("schema"),parentSchema:new U.Name("parentSchema")};function vf(n,e,t){let{createErrors:r}=n.it;return r===false?(0, U._)`{}`:cC(n,e,t)}function cC(n,e,t={}){let{gen:r,it:i}=n,a=[hC(i,t),dC(n,t)];return fC(n,e,a),r.object(...a)}function hC({errorPath:n},{instancePath:e}){let t=e?(0, U.str)`${n}${(0, Yi.getErrorPath)(e,Yi.Type.Str)}`:n;return [Te.default.instancePath,(0, U.strConcat)(Te.default.instancePath,t)]}function dC({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, U.str)`${e}/${n}`;return t&&(i=(0, U.str)`${i}${(0, Yi.getErrorPath)(t,Yi.Type.Str)}`),[ln.schemaPath,i]}function fC(n,{params:e,message:t},r){let{keyword:i,data:a,schemaValue:s,it:o}=n,{opts:u,propertyName:l,topSchemaRef:c,schemaPath:h}=o;r.push([ln.keyword,i],[ln.params,typeof e=="function"?e(n):e||(0, U._)`{}`]),u.messages&&r.push([ln.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([ln.schema,s],[ln.parentSchema,(0, U._)`${c}${h}`],[Te.default.data,a]),l&&r.push([ln.propertyName,l]);}});var Ef=y(kn=>{Object.defineProperty(kn,"__esModule",{value:true});kn.boolOrEmptySchema=kn.topBoolOrEmptySchema=void 0;var pC=Tr(),mC=I(),gC=Je(),yC={message:"boolean schema is false"};function CC(n){let{gen:e,schema:t,validateName:r}=n;t===false?_f(n,false):typeof t=="object"&&t.$async===true?e.return(gC.default.data):(e.assign((0, mC._)`${r}.errors`,null),e.return(true));}kn.topBoolOrEmptySchema=CC;function vC(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),_f(n)):t.var(e,true);}kn.boolOrEmptySchema=vC;function _f(n,e){let{gen:t,data:r}=n,i={gen:t,keyword:"false schema",data:r,schema:false,schemaCode:false,schemaValue:false,params:{},it:n};(0, pC.reportError)(i,yC,void 0,e);}});var xu=y($n=>{Object.defineProperty($n,"__esModule",{value:true});$n.getRules=$n.isJSONType=void 0;var _C=["string","number","integer","boolean","null","object","array"],EC=new Set(_C);function bC(n){return typeof n=="string"&&EC.has(n)}$n.isJSONType=bC;function SC(){let n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...n,integer:true,boolean:true,null:true},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}$n.getRules=SC;});var Nu=y(jt=>{Object.defineProperty(jt,"__esModule",{value:true});jt.shouldUseRule=jt.shouldUseGroup=jt.schemaHasRulesForType=void 0;function DC({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&bf(n,r)}jt.schemaHasRulesForType=DC;function bf(n,e){return e.rules.some(t=>Sf(n,t))}jt.shouldUseGroup=bf;function Sf(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(r=>n[r]!==void 0))}jt.shouldUseRule=Sf;});var Ir=y(De=>{Object.defineProperty(De,"__esModule",{value:true});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var wC=xu(),AC=Nu(),PC=Tr(),k=I(),Df=L(),Rn;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})(Rn||(De.DataType=Rn={}));function FC(n){let e=wf(n.type);if(e.includes("null")){if(n.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===true&&e.push("null");}return e}De.getSchemaTypes=FC;function wf(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(wC.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=wf;function OC(n,e){let{gen:t,data:r,opts:i}=n,a=xC(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, AC.schemaHasRulesForType)(n,e[0]));if(s){let o=Iu(e,r,i.strictNumbers,Rn.Wrong);t.if(o,()=>{a.length?NC(n,e,a):ku(n);});}return s}De.coerceAndCheckDataType=OC;var Af=new Set(["string","number","integer","boolean","null"]);function xC(n,e){return e?n.filter(t=>Af.has(t)||e==="array"&&t==="array"):[]}function NC(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, k._)`typeof ${i}`),o=r.let("coerced",(0, k._)`undefined`);a.coerceTypes==="array"&&r.if((0, k._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, k._)`${i}[0]`).assign(s,(0, k._)`typeof ${i}`).if(Iu(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, k._)`${o} !== undefined`);for(let l of t)(Af.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),ku(n),r.endIf(),r.if((0, k._)`${o} !== undefined`,()=>{r.assign(i,o),TC(n,o);});function u(l){switch(l){case "string":r.elseIf((0, k._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, k._)`"" + ${i}`).elseIf((0, k._)`${i} === null`).assign(o,(0, k._)`""`);return;case "number":r.elseIf((0, k._)`${s} == "boolean" || ${i} === null
3
- || (${s} == "string" && ${i} && ${i} == +${i})`).assign(o,(0, k._)`+${i}`);return;case "integer":r.elseIf((0, k._)`${s} === "boolean" || ${i} === null
4
- || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(o,(0, k._)`+${i}`);return;case "boolean":r.elseIf((0, k._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(o,false).elseIf((0, k._)`${i} === "true" || ${i} === 1`).assign(o,true);return;case "null":r.elseIf((0, k._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(o,null);return;case "array":r.elseIf((0, k._)`${s} === "string" || ${s} === "number"
5
- || ${s} === "boolean" || ${i} === null`).assign(o,(0, k._)`[${i}]`);}}}function TC({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, k._)`${e} !== undefined`,()=>n.assign((0, k._)`${e}[${t}]`,r));}function Tu(n,e,t,r=Rn.Correct){let i=r===Rn.Correct?k.operators.EQ:k.operators.NEQ,a;switch(n){case "null":return (0, k._)`${e} ${i} null`;case "array":a=(0, k._)`Array.isArray(${e})`;break;case "object":a=(0, k._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, k._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, k._)`typeof ${e} ${i} ${n}`}return r===Rn.Correct?a:(0, k.not)(a);function s(o=k.nil){return (0, k.and)((0, k._)`typeof ${e} == "number"`,o,t?(0, k._)`isFinite(${e})`:k.nil)}}De.checkDataType=Tu;function Iu(n,e,t,r){if(n.length===1)return Tu(n[0],e,t,r);let i,a=(0, Df.toHash)(n);if(a.array&&a.object){let s=(0, k._)`typeof ${e} != "object"`;i=a.null?s:(0, k._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=k.nil;a.number&&delete a.integer;for(let s in a)i=(0, k.and)(i,Tu(s,e,t,r));return i}De.checkDataTypes=Iu;var IC={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, k._)`{type: ${n}}`:(0, k._)`{type: ${e}}`};function ku(n){let e=kC(n);(0, PC.reportError)(e,IC);}De.reportTypeError=ku;function kC(n){let{gen:e,data:t,schema:r}=n,i=(0, Df.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var Ff=y(es=>{Object.defineProperty(es,"__esModule",{value:true});es.assignDefaults=void 0;var Vn=I(),$C=L();function RC(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)Pf(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>Pf(n,a,i.default));}es.assignDefaults=RC;function Pf(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, Vn._)`${a}${(0, Vn.getProperty)(e)}`;if(i){(0, $C.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, Vn._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, Vn._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, Vn._)`${o} = ${(0, Vn.stringify)(t)}`);}});var Ze=y(J=>{Object.defineProperty(J,"__esModule",{value:true});J.validateUnion=J.validateArray=J.usePattern=J.callValidateCode=J.schemaProperties=J.allSchemaProperties=J.noPropertyInData=J.propertyInData=J.isOwnProperty=J.hasPropFunc=J.reportMissingProp=J.checkMissingProp=J.checkReportMissingProp=void 0;var te=I(),$u=L(),Lt=Je(),VC=L();function qC(n,e){let{gen:t,data:r,it:i}=n;t.if(Vu(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, te._)`${e}`},true),n.error();});}J.checkReportMissingProp=qC;function jC({gen:n,data:e,it:{opts:t}},r,i){return (0, te.or)(...r.map(a=>(0, te.and)(Vu(n,e,a,t.ownProperties),(0, te._)`${i} = ${a}`)))}J.checkMissingProp=jC;function LC(n,e){n.setParams({missingProperty:e},true),n.error();}J.reportMissingProp=LC;function Of(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, te._)`Object.prototype.hasOwnProperty`})}J.hasPropFunc=Of;function Ru(n,e,t){return (0, te._)`${Of(n)}.call(${e}, ${t})`}J.isOwnProperty=Ru;function BC(n,e,t,r){let i=(0, te._)`${e}${(0, te.getProperty)(t)} !== undefined`;return r?(0, te._)`${i} && ${Ru(n,e,t)}`:i}J.propertyInData=BC;function Vu(n,e,t,r){let i=(0, te._)`${e}${(0, te.getProperty)(t)} === undefined`;return r?(0, te.or)(i,(0, te.not)(Ru(n,e,t))):i}J.noPropertyInData=Vu;function xf(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}J.allSchemaProperties=xf;function WC(n,e){return xf(e).filter(t=>!(0, $u.alwaysValidSchema)(n,e[t]))}J.schemaProperties=WC;function MC({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, te._)`${n}, ${e}, ${r}${i}`:e,h=[[Lt.default.instancePath,(0, te.strConcat)(Lt.default.instancePath,a)],[Lt.default.parentData,s.parentData],[Lt.default.parentDataProperty,s.parentDataProperty],[Lt.default.rootData,Lt.default.rootData]];s.opts.dynamicRef&&h.push([Lt.default.dynamicAnchors,Lt.default.dynamicAnchors]);let d=(0, te._)`${c}, ${t.object(...h)}`;return u!==te.nil?(0, te._)`${o}.call(${u}, ${d})`:(0, te._)`${o}(${d})`}J.callValidateCode=MC;var GC=(0, te._)`new RegExp`;function UC({gen:n,it:{opts:e}},t){let r=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,r);return n.scopeValue("pattern",{key:a.toString(),ref:a,code:(0, te._)`${i.code==="new RegExp"?GC:(0, VC.useFunc)(n,i)}(${t}, ${r})`})}J.usePattern=UC;function HC(n){let{gen:e,data:t,keyword:r,it:i}=n,a=e.name("valid");if(i.allErrors){let o=e.let("valid",true);return s(()=>e.assign(o,false)),o}return e.var(a,true),s(()=>e.break()),a;function s(o){let u=e.const("len",(0, te._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:$u.Type.Num},a),e.if((0, te.not)(a),o);});}}J.validateArray=HC;function KC(n){let{gen:e,schema:t,keyword:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(u=>(0, $u.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=e.let("valid",false),o=e.name("_valid");e.block(()=>t.forEach((u,l)=>{let c=n.subschema({keyword:r,schemaProp:l,compositeRule:true},o);e.assign(s,(0, te._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, te.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}J.validateUnion=KC;});var If=y(ft=>{Object.defineProperty(ft,"__esModule",{value:true});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Ie=I(),cn=Je(),zC=Ze(),JC=Tr();function ZC(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=Tf(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:Ie.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}ft.macroKeywordCode=ZC;function XC(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;YC(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=Tf(r,i,l),h=r.let("valid");n.block$data(h,d),n.ok((t=e.valid)!==null&&t!==void 0?t:h);function d(){if(e.errors===false)f(),e.modifying&&Nf(n),v(()=>n.error());else {let _=e.async?p():m();e.modifying&&Nf(n),v(()=>QC(n,_));}}function p(){let _=r.let("ruleErrs",null);return r.try(()=>f((0, Ie._)`await `),b=>r.assign(h,false).if((0, Ie._)`${b} instanceof ${u.ValidationError}`,()=>r.assign(_,(0, Ie._)`${b}.errors`),()=>r.throw(b))),_}function m(){let _=(0, Ie._)`${c}.errors`;return r.assign(_,null),f(Ie.nil),_}function f(_=e.async?(0, Ie._)`await `:Ie.nil){let b=u.opts.passContext?cn.default.this:cn.default.self,E=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, Ie._)`${_}${(0, zC.callValidateCode)(n,c,b,E)}`,e.modifying);}function v(_){var b;r.if((0, Ie.not)((b=e.valid)!==null&&b!==void 0?b:h),_);}}ft.funcKeywordCode=XC;function Nf(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, Ie._)`${r.parentData}[${r.parentDataProperty}]`));}function QC(n,e){let{gen:t}=n;t.if((0, Ie._)`Array.isArray(${e})`,()=>{t.assign(cn.default.vErrors,(0, Ie._)`${cn.default.vErrors} === null ? ${e} : ${cn.default.vErrors}.concat(${e})`).assign(cn.default.errors,(0, Ie._)`${cn.default.vErrors}.length`),(0, JC.extendErrors)(n);},()=>n.error());}function YC({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function Tf(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0, Ie.stringify)(t)})}function ev(n,e,t=false){return !e.length||e.some(r=>r==="array"?Array.isArray(n):r==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==r||t&&typeof n>"u")}ft.validSchemaType=ev;function tv({schema:n,opts:e,self:t,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(o=>!Object.prototype.hasOwnProperty.call(n,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[a])){let u=`keyword "${a}" value is invalid at path "${r}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(u);else throw new Error(u)}}ft.validateKeywordUsage=tv;});var $f=y(Bt=>{Object.defineProperty(Bt,"__esModule",{value:true});Bt.extendSubschemaMode=Bt.extendSubschemaData=Bt.getSubschema=void 0;var pt=I(),kf=L();function nv(n,{keyword:e,schemaProp:t,schema:r,schemaPath:i,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let o=n.schema[e];return t===void 0?{schema:o,schemaPath:(0, pt._)`${n.schemaPath}${(0, pt.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, pt._)`${n.schemaPath}${(0, pt.getProperty)(e)}${(0, pt.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, kf.escapeFragment)(t)}`}}if(r!==void 0){if(i===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:r,schemaPath:i,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Bt.getSubschema=nv;function rv(n,e,{dataProp:t,dataPropType:r,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(t!==void 0){let{errorPath:l,dataPathArr:c,opts:h}=e,d=o.let("data",(0, pt._)`${e.data}${(0, pt.getProperty)(t)}`,true);u(d),n.errorPath=(0, pt.str)`${l}${(0, kf.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, pt._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof pt.Name?i:o.let("data",i,true);u(l),s!==void 0&&(n.propertyName=s);}a&&(n.dataTypes=a);function u(l){n.data=l,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,l];}}Bt.extendSubschemaData=rv;function iv(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(n.compositeRule=r),i!==void 0&&(n.createErrors=i),a!==void 0&&(n.allErrors=a),n.jtdDiscriminator=e,n.jtdMetadata=t;}Bt.extendSubschemaMode=iv;});var qu=y((mO,Rf)=>{Rf.exports=function n(e,t){if(e===t)return true;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return false;var r,i,a;if(Array.isArray(e)){if(r=e.length,r!=t.length)return false;for(i=r;i--!==0;)if(!n(e[i],t[i]))return false;return true}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),r=a.length,r!==Object.keys(t).length)return false;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return false;for(i=r;i--!==0;){var s=a[i];if(!n(e[s],t[s]))return false}return true}return e!==e&&t!==t};});var qf=y((gO,Vf)=>{var Wt=Vf.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var r=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};ts(e,r,i,n,"",n);};Wt.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};Wt.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};Wt.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};Wt.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function ts(n,e,t,r,i,a,s,o,u,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,i,a,s,o,u,l);for(var c in r){var h=r[c];if(Array.isArray(h)){if(c in Wt.arrayKeywords)for(var d=0;d<h.length;d++)ts(n,e,t,h[d],i+"/"+c+"/"+d,a,i,c,r,d);}else if(c in Wt.propsKeywords){if(h&&typeof h=="object")for(var p in h)ts(n,e,t,h[p],i+"/"+c+"/"+sv(p),a,i,c,r,p);}else (c in Wt.keywords||n.allKeys&&!(c in Wt.skipKeywords))&&ts(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function sv(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var kr=y(qe=>{Object.defineProperty(qe,"__esModule",{value:true});qe.getSchemaRefs=qe.resolveUrl=qe.normalizeId=qe._getFullPath=qe.getFullPath=qe.inlineRef=void 0;var av=L(),ov=qu(),uv=qf(),lv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cv(n,e=true){return typeof n=="boolean"?true:e===true?!ju(n):e?jf(n)<=e:false}qe.inlineRef=cv;var hv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ju(n){for(let e in n){if(hv.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(ju)||typeof t=="object"&&ju(t))return true}return false}function jf(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!lv.has(t)&&(typeof n[t]=="object"&&(0, av.eachItem)(n[t],r=>e+=jf(r)),e===1/0))return 1/0}return e}function Lf(n,e="",t){t!==false&&(e=qn(e));let r=n.parse(e);return Bf(n,r)}qe.getFullPath=Lf;function Bf(n,e){return n.serialize(e).split("#")[0]+"#"}qe._getFullPath=Bf;var dv=/#\/?$/;function qn(n){return n?n.replace(dv,""):""}qe.normalizeId=qn;function fv(n,e,t){return t=qn(t),n.resolve(e,t)}qe.resolveUrl=fv;var pv=/^[a-z_][-a-z0-9._]*$/i;function mv(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=qn(n[t]||e),a={"":i},s=Lf(r,i,false),o={},u=new Set;return uv(n,{allKeys:true},(h,d,p,m)=>{if(m===void 0)return;let f=s+d,v=a[m];typeof h[t]=="string"&&(v=_.call(this,h[t])),b.call(this,h.$anchor),b.call(this,h.$dynamicAnchor),a[d]=v;function _(E){let g=this.opts.uriResolver.resolve;if(E=qn(v?g(v,E):E),u.has(E))throw c(E);u.add(E);let C=this.refs[E];return typeof C=="string"&&(C=this.refs[C]),typeof C=="object"?l(h,C.schema,E):E!==qn(f)&&(E[0]==="#"?(l(h,o[E],E),o[E]=h):this.refs[E]=f),E}function b(E){if(typeof E=="string"){if(!pv.test(E))throw new Error(`invalid anchor "${E}"`);_.call(this,`#${E}`);}}}),o;function l(h,d,p){if(d!==void 0&&!ov(h,d))throw c(p)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}qe.getSchemaRefs=mv;});var jn=y(Mt=>{Object.defineProperty(Mt,"__esModule",{value:true});Mt.getData=Mt.KeywordCxt=Mt.validateFunctionCode=void 0;var Hf=Ef(),Wf=Ir(),Bu=Nu(),ns=Ir(),gv=Ff(),Rr=If(),Lu=$f(),P=I(),N=Je(),yv=kr(),Nt=L(),$r=Tr();function Cv(n){if(Jf(n)&&(Zf(n),zf(n))){Ev(n);return}Kf(n,()=>(0, Hf.topBoolOrEmptySchema)(n));}Mt.validateFunctionCode=Cv;function Kf({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, P._)`${N.default.data}, ${N.default.valCxt}`,r.$async,()=>{n.code((0, P._)`"use strict"; ${Mf(t,i)}`),_v(n,i),n.code(a);}):n.func(e,(0, P._)`${N.default.data}, ${vv(i)}`,r.$async,()=>n.code(Mf(t,i)).code(a));}function vv(n){return (0, P._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${n.dynamicRef?(0, P._)`, ${N.default.dynamicAnchors}={}`:P.nil}}={}`}function _v(n,e){n.if(N.default.valCxt,()=>{n.var(N.default.instancePath,(0, P._)`${N.default.valCxt}.${N.default.instancePath}`),n.var(N.default.parentData,(0, P._)`${N.default.valCxt}.${N.default.parentData}`),n.var(N.default.parentDataProperty,(0, P._)`${N.default.valCxt}.${N.default.parentDataProperty}`),n.var(N.default.rootData,(0, P._)`${N.default.valCxt}.${N.default.rootData}`),e.dynamicRef&&n.var(N.default.dynamicAnchors,(0, P._)`${N.default.valCxt}.${N.default.dynamicAnchors}`);},()=>{n.var(N.default.instancePath,(0, P._)`""`),n.var(N.default.parentData,(0, P._)`undefined`),n.var(N.default.parentDataProperty,(0, P._)`undefined`),n.var(N.default.rootData,N.default.data),e.dynamicRef&&n.var(N.default.dynamicAnchors,(0, P._)`{}`);});}function Ev(n){let{schema:e,opts:t,gen:r}=n;Kf(n,()=>{t.$comment&&e.$comment&&Qf(n),Av(n),r.let(N.default.vErrors,null),r.let(N.default.errors,0),t.unevaluated&&bv(n),Xf(n),Ov(n);});}function bv(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, P._)`${t}.evaluated`),e.if((0, P._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, P._)`${n.evaluated}.props`,(0, P._)`undefined`)),e.if((0, P._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, P._)`${n.evaluated}.items`,(0, P._)`undefined`));}function Mf(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, P._)`/*# sourceURL=${t} */`:P.nil}function Sv(n,e){if(Jf(n)&&(Zf(n),zf(n))){Dv(n,e);return}(0, Hf.boolOrEmptySchema)(n,e);}function zf({schema:n,self:e}){if(typeof n=="boolean")return !n;for(let t in n)if(e.RULES.all[t])return true;return false}function Jf(n){return typeof n.schema!="boolean"}function Dv(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&Qf(n),Pv(n),Fv(n);let a=r.const("_errs",N.default.errors);Xf(n,a),r.var(e,(0, P._)`${a} === ${N.default.errors}`);}function Zf(n){(0, Nt.checkUnknownRules)(n),wv(n);}function Xf(n,e){if(n.opts.jtd)return Gf(n,[],false,e);let t=(0, Wf.getSchemaTypes)(n.schema),r=(0, Wf.coerceAndCheckDataType)(n,t);Gf(n,t,!r,e);}function wv(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, Nt.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function Av(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, Nt.checkStrictMode)(n,"default is ignored in the schema root");}function Pv(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, yv.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function Fv(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qf({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, P._)`${N.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, P.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, P._)`${N.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function Ov(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, P._)`${N.default.errors} === 0`,()=>e.return(N.default.data),()=>e.throw((0, P._)`new ${i}(${N.default.vErrors})`)):(e.assign((0, P._)`${r}.errors`,N.default.vErrors),a.unevaluated&&xv(n),e.return((0, P._)`${N.default.errors} === 0`));}function xv({gen:n,evaluated:e,props:t,items:r}){t instanceof P.Name&&n.assign((0, P._)`${e}.props`,t),r instanceof P.Name&&n.assign((0, P._)`${e}.items`,r);}function Gf(n,e,t,r){let{gen:i,schema:a,data:s,allErrors:o,opts:u,self:l}=n,{RULES:c}=l;if(a.$ref&&(u.ignoreKeywordsWithRef||!(0, Nt.schemaHasRulesButRef)(a,c))){i.block(()=>ep(n,"$ref",c.all.$ref.definition));return}u.jtd||Nv(n,e),i.block(()=>{for(let d of c.rules)h(d);h(c.post);});function h(d){(0, Bu.shouldUseGroup)(a,d)&&(d.type?(i.if((0, ns.checkDataType)(d.type,s,u.strictNumbers)),Uf(n,d),e.length===1&&e[0]===d.type&&t&&(i.else(),(0, ns.reportTypeError)(n)),i.endIf()):Uf(n,d),o||i.if((0, P._)`${N.default.errors} === ${r||0}`));}}function Uf(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, gv.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, Bu.shouldUseRule)(r,a)&&ep(n,a.keyword,a.definition,e.type);});}function Nv(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(Tv(n,e),n.opts.allowUnionTypes||Iv(n,e),kv(n,n.dataTypes));}function Tv(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{Yf(n.dataTypes,t)||Wu(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),Rv(n,e);}}function Iv(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Wu(n,"use allowUnionTypes to allow union type keyword");}function kv(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, Bu.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>$v(e,s))&&Wu(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function $v(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function Yf(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function Rv(n,e){let t=[];for(let r of n.dataTypes)Yf(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function Wu(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, Nt.checkStrictMode)(n,e,n.opts.strictTypes);}var rs=class{constructor(e,t,r){if((0, Rr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, Nt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",tp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, Rr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==false)&&(this.errsCount=e.gen.const("_errs",N.default.errors));}result(e,t,r){this.failResult((0, P.not)(e),t,r);}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(e,t){this.failResult((0, P.not)(e),void 0,t);}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(false);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:t}=this;this.fail((0, P._)`${t} !== undefined && (${(0, P.or)(this.invalid$data(),e)})`);}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r);}_error(e,t){(e?$r.reportExtraError:$r.reportError)(this,this.def.error,t);}$dataError(){(0, $r.reportError)(this,this.def.$dataError||$r.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, $r.resetErrorsCount)(this.gen,this.errsCount);}ok(e){this.allErrors||this.gen.if(e);}setParams(e,t){t?Object.assign(this.params,e):this.params=e;}block$data(e,t,r=P.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=P.nil,t=P.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, P.or)((0, P._)`${i} === undefined`,t)),e!==P.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==P.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, P.or)(s(),o());function s(){if(r.length){if(!(t instanceof P.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, P._)`${(0, ns.checkDataTypes)(u,t,a.opts.strictNumbers,ns.DataType.Wrong)}`}return P.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, P._)`!${u}(${t})`}return P.nil}}subschema(e,t){let r=(0, Lu.getSubschema)(this.it,e);(0, Lu.extendSubschemaData)(r,this.it,e),(0, Lu.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return Sv(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=Nt.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=Nt.mergeEvaluated.items(i,e.items,r.items,t)));}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==true||r.items!==true))return i.if(t,()=>this.mergeEvaluated(e,P.Name)),true}};Mt.KeywordCxt=rs;function ep(n,e,t,r){let i=new rs(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, Rr.funcKeywordCode)(i,t):"macro"in t?(0, Rr.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, Rr.funcKeywordCode)(i,t);}var Vv=/^\/(?:[^~]|~0|~1)*$/,qv=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function tp(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return N.default.rootData;if(n[0]==="/"){if(!Vv.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=N.default.rootData;}else {let l=qv.exec(n);if(!l)throw new Error(`Invalid JSON-pointer: ${n}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(u("property/index",c));return r[e-c]}if(c>e)throw new Error(u("data",c));if(a=t[e-c],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0, P._)`${a}${(0, P.getProperty)((0, Nt.unescapeJsonPointer)(l))}`,s=(0, P._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}Mt.getData=tp;});var Vr=y(Gu=>{Object.defineProperty(Gu,"__esModule",{value:true});var Mu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};Gu.default=Mu;});var Ln=y(Ku=>{Object.defineProperty(Ku,"__esModule",{value:true});var Uu=kr(),Hu=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Uu.resolveUrl)(e,t,r),this.missingSchema=(0, Uu.normalizeId)((0, Uu.getFullPath)(e,this.missingRef));}};Ku.default=Hu;});var qr=y(Xe=>{Object.defineProperty(Xe,"__esModule",{value:true});Xe.resolveSchema=Xe.getCompilingSchema=Xe.resolveRef=Xe.compileSchema=Xe.SchemaEnv=void 0;var ut=I(),jv=Vr(),hn=Je(),lt=kr(),np=L(),Lv=jn(),Bn=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0, lt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};Xe.SchemaEnv=Bn;function Ju(n){let e=rp.call(this,n);if(e)return e;let t=(0, lt.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new ut.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:jv.default,code:(0, ut._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:hn.default.data,parentData:hn.default.parentData,parentDataProperty:hn.default.parentDataProperty,dataNames:[hn.default.data],dataPathArr:[ut.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, ut.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:ut.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, ut._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,Lv.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs(hn.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let p=new Function(`${hn.default.self}`,`${hn.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:p}),p.errors=null,p.schema=n.schema,p.schemaEnv=n,n.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:f}=l;p.evaluated={props:m instanceof ut.Name?void 0:m,items:f instanceof ut.Name?void 0:f,dynamicProps:m instanceof ut.Name,dynamicItems:f instanceof ut.Name},p.source&&(p.source.evaluated=(0,ut.stringify)(p.evaluated));}return n.validate=p,n}catch(h){throw delete n.validate,delete n.validateName,c&&this.logger.error("Error compiling schema, function code:",c),h}finally{this._compilations.delete(n);}}Xe.compileSchema=Ju;function Bv(n,e,t){var r;t=(0, lt.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=Gv.call(this,n,t);if(a===void 0){let s=(r=n.localRefs)===null||r===void 0?void 0:r[t],{schemaId:o}=this.opts;s&&(a=new Bn({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=Wv.call(this,a)}Xe.resolveRef=Bv;function Wv(n){return (0, lt.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:Ju.call(this,n)}function rp(n){for(let e of this._compilations)if(Mv(e,n))return e}Xe.getCompilingSchema=rp;function Mv(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function Gv(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||is.call(this,n,e)}function is(n,e){let t=this.opts.uriResolver.parse(e),r=(0, lt._getFullPath)(this.opts.uriResolver,t),i=(0, lt.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return zu.call(this,t,n);let a=(0, lt.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=is.call(this,n,s);return typeof o?.schema!="object"?void 0:zu.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||Ju.call(this,s),a===(0, lt.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, lt.resolveUrl)(this.opts.uriResolver,i,l)),new Bn({schema:o,schemaId:u,root:n,baseId:i})}return zu.call(this,t,s)}}Xe.resolveSchema=is;var Uv=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zu(n,{baseId:e,schema:t,root:r}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let u=t[(0, np.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!Uv.has(o)&&l&&(e=(0, lt.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, np.schemaHasRulesButRef)(t,this.RULES)){let o=(0, lt.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=is.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new Bn({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var ip=y((bO,Hv)=>{Hv.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:false};});var tl=y((SO,hp)=>{var Kv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xu=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),dn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Qu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ap=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Yu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),zv=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),je=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)je[e]="%"+n[e>>4]+n[e&15];}function we(n){return n<2048?je[192|n>>6]+je[128|n&63]:n<65536?je[224|n>>12]+je[128|n>>6&63]+je[128|n&63]:je[240|n>>18]+je[128|n>>12&63]+je[128|n>>6&63]+je[128|n&63]}function Jv(n){let e="",t=0,r=0;for(r=0;r<n.length;r++)if(t=n[r].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];break}for(r+=1;r<n.length;r++){if(t=n[r].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];}return e}var Zv=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Xv=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Qv=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Yv=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function e_(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!Qv(n[e])){if(n[e]==="%"&&e+2<n.length&&dn(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function sp(n){let e=-1,t=0,r=-1,i=0;for(let o=0;o<n.length;o++)n[o]==="0"?(r===-1&&(r=o),i++,i>t&&(t=i,e=r)):(r=-1,i=0);if(t<2)return n.join(":");let a=n.slice(0,e).join(":"),s=n.slice(e+t).join(":");return a+"::"+s}function t_(n){let e=n.indexOf("::");if(e!==-1&&n.indexOf("::",e+1)!==-1)return;let t=e===-1?n.split(":"):n.slice(0,e).split(":"),r=e===-1?[]:n.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),r.length===1&&r[0]===""&&(r.length=0));let i=t.concat(r),a=0;for(let o=0;o<i.length;o++){let u=i[o];if(u==="")return;if(u.indexOf(".")!==-1){if(o!==i.length-1||e!==-1&&r.length===0||!Xu(u))return;a+=2;continue}if(!Zv(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:sp(i);if(a>=8)return;let s=i.slice(0,t.length);for(let o=a;o<8;o++)s.push("0");for(let o=t.length;o<i.length;o++)s.push(i[o]);return sp(s)}function Zu(n){let e=n[0]==="["&&n[n.length-1]==="]";if((n[0]==="["||n[n.length-1]==="]")&&!e)return {host:n,isIPV6:false,error:true};let r=e?n.slice(1,-1):n;if(e&&Xv(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(n_(r,":")<2)return {host:n,isIPV6:false,error:e};let i="",a=r.indexOf("%");if(a!==-1){let o=r.slice(a,a+3).toLowerCase()==="%25"?3:1;if(i=r.slice(a+o),!e_(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=t_(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function n_(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function r_(n){let e=n,t=[],r=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else {t.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]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.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),t.length!==0&&t.pop();continue}}if((r=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,r)),e=e.slice(r);}return t.join("")}var i_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},s_=/[@/?#:]/g,a_=/[@/?#]/g;function op(n,e){let t=e?a_:s_;return t.lastIndex=0,n.replace(t,r=>i_[r])}function up(n,e=false){if(n.indexOf("%")===-1)return n;let t="";for(let r=0;r<n.length;r++){if(n[r]==="%"&&r+2<n.length){let i=n.slice(r+1,r+3);if(dn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&Qu(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function o_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(dn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&Qu(s)?e+=s:e+="%"+a,t+=2;continue}}if(ap(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=cp(i)?r:je[i];else if(i<55296||i>57343)e+=we(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=we(65536+(i-55296<<10)+(a-56320)),t++):e+=we(65533);}else e+=we(65533);}}return e}function u_(n,e=false){let t="",r=e&&n[0]!=="/";for(let i=0;i<n.length;i++){let a=n[i];if(a==="%"&&i+2<n.length){let s=n.slice(i+1,i+3);if(dn(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),ap(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=je[s];else if(s<55296||s>57343)t+=we(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=we(65536+(s-55296<<10)+(o-56320)),i++):t+=we(65533);}else t+=we(65533);}}return t}function el(n,e){let t="";for(let r=0;r<n.length;r++){let i=n[r];if(i==="%"&&r+2<n.length){let a=n.slice(r+1,r+3);if(dn(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=je[a];else if(a<55296||a>57343)t+=we(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=we(65536+(a-55296<<10)+(s-56320)),r++):t+=we(65533);}else t+=we(65533);}}return t}function lp(n){return el(n,zv)}function l_(n){return el(n,Yu)}function c_(n){return el(n,Yu)}function cp(n){return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===42||n===43||n===45||n===46||n===47||n===64||n===95}function h_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(dn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));Qu(s)?e+=s:e+="%"+a,t+=2;continue}}if(Yu(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=cp(i)?r:je[i];else if(i<55296||i>57343)e+=we(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=we(65536+(i-55296<<10)+(a-56320)),t++):e+=we(65533);}else e+=we(65533);}}return e}function d_(n){let e="";for(let t=0;t<n.length;t++){if(n[t]==="%"&&t+2<n.length){let r=n.slice(t+1,t+3);if(dn(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function f_(n){let e=[];if(n.userinfo!==void 0&&(e.push(lp(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Xu(t)){let r=Zu(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=up(t,true),r=Zu(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=op(t,false);}e.push(t);}return (typeof n.port=="number"||typeof n.port=="string")&&(e.push(":"),e.push(String(n.port))),e.length?e.join(""):void 0}hp.exports={nonSimpleDomain:Yv,recomposeAuthority:f_,reescapeHostDelimiters:op,normalizePercentEncoding:up,normalizePathEncoding:o_,serializePathEncoding:u_,normalizeQueryFragmentEncoding:h_,encodeUserinfo:lp,encodeQuery:l_,encodeFragment:c_,escapePreservingEscapes:d_,removeDotSegments:r_,isIPv4:Xu,isUUID:Kv,normalizeIPv6:Zu,stringArrayToHexStripped:Jv};});var gp=y((DO,mp)=>{var{isUUID:p_}=tl(),m_=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,g_=["http","https","ws","wss","urn","urn:uuid"];function y_(n){return g_.indexOf(n)!==-1}function nl(n){return n.secure===true?true:n.secure===false?false:n.scheme?n.scheme.length===3&&(n.scheme[0]==="w"||n.scheme[0]==="W")&&(n.scheme[1]==="s"||n.scheme[1]==="S")&&(n.scheme[2]==="s"||n.scheme[2]==="S"):false}function dp(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function fp(n){let e=String(n.scheme).toLowerCase()==="https";return (n.port===(e?443:80)||n.port==="")&&(n.port=void 0),n.path||(n.path="/"),n}function C_(n){return n.secure=nl(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function v_(n){if((n.port===(nl(n)?443:80)||n.port==="")&&(n.port=void 0),typeof n.secure=="boolean"&&(n.scheme=n.secure?"wss":"ws",n.secure=void 0),n.resourceName){let e=n.resourceName.indexOf("?"),t=e===-1?n.resourceName:n.resourceName.slice(0,e);n.path=t&&t!=="/"?t:void 0,n.query=e===-1?void 0:n.resourceName.slice(e+1),n.resourceName=void 0;}return n.fragment=void 0,n}function __(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(m_);if(t&&t[0]===n.path){let r=e.scheme||n.scheme||"urn";n.nid=t[1].toLowerCase(),n.nss=t[2];let i=`${r}:${e.nid||n.nid}`,a=rl(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function E_(n,e){if(n.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||n.scheme||"urn",r=n.nid.toLowerCase(),i=`${t}:${e.nid||r}`,a=rl(i);a&&(n=a.serialize(n,e));let s=n,o=n.nss;return s.path=`${r||e.nid}:${o}`,e.skipEscape=true,s}function b_(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!p_(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function S_(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var pp={scheme:"http",domainHost:true,parse:dp,serialize:fp},D_={scheme:"https",domainHost:pp.domainHost,parse:dp,serialize:fp},ss={scheme:"ws",domainHost:true,parse:C_,serialize:v_},w_={scheme:"wss",domainHost:ss.domainHost,parse:ss.parse,serialize:ss.serialize},A_={scheme:"urn",parse:__,serialize:E_,skipNormalize:true},P_={scheme:"urn:uuid",parse:b_,serialize:S_,skipNormalize:true},as={http:pp,https:D_,ws:ss,wss:w_,urn:A_,"urn:uuid":P_};Object.setPrototypeOf(as,null);function rl(n){return n&&(as[n]||as[n.toLowerCase()])||void 0}mp.exports={wsIsSecure:nl,SCHEMES:as,isValidSchemeName:y_,getSchemeHandler:rl};});var xp=y((wO,ls)=>{var{normalizeIPv6:Ep,removeDotSegments:Lr,recomposeAuthority:F_,normalizePercentEncoding:bp,normalizePathEncoding:O_,serializePathEncoding:yp,normalizeQueryFragmentEncoding:Cp,encodeQuery:x_,encodeFragment:N_,reescapeHostDelimiters:T_,isIPv4:Sp,nonSimpleDomain:I_}=tl(),{SCHEMES:Dp,getSchemeHandler:il}=gp(),wp=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ap="URI scheme is malformed.";function vp(n){let e=unescape(String(n));if(!wp.test(e))throw new TypeError(Ap);return e}function k_(n,e){return typeof n=="string"?n=W_(n,e):typeof n=="object"&&(n=us(fn(n,e),e)),n}function $_(n,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:u,malformedScheme:l}=os(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:d,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:f}=os(e,r);if(a||h||s||d||o||p||u||m||l||f)throw new Error(i.error||c.error||"URI is malformed.");let v=Pp(i,c,r,true),_=il(t&&t.scheme||v.scheme),b=v.host,E=b!==void 0&&b!==""&&(Sp(b)||Ep(b).isIPV6);Fp(v,t||{},_,E);let g=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(v.error&&!g)throw new Error(v.error);return r.skipEscape=true,fn(v,r)}function Pp(n,e,t,r){let i={};return r||(n=us(fn(n,t),t),e=us(fn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Lr(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=Lr(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Lr(e.path):((n.userinfo!==void 0||n.host!==void 0||n.port!==void 0)&&!n.path?i.path="/"+e.path:n.path?i.path=n.path.slice(0,n.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Lr(i.path)),i.query=e.query):(i.path=n.path,e.query!==void 0?i.query=e.query:i.query=n.query),i.userinfo=n.userinfo,i.host=n.host,i.port=n.port),i.scheme=n.scheme),i.fragment=e.fragment,i}function R_(n,e,t){let r=_p(n,t),i=_p(e,t);return r!==void 0&&i!==void 0&&r===i}function fn(n,e){let t={host:n.host,scheme:n.scheme,userinfo:n.userinfo,port:n.port,path:n.path,query:n.query,nid:n.nid,nss:n.nss,uuid:n.uuid,fragment:n.fragment,reference:n.reference,resourceName:n.resourceName,secure:n.secure,error:""},r=Object.assign({},e),i=[];t.scheme&&(t.scheme=vp(t.scheme));let a=il(r.scheme||t.scheme);a&&a.serialize&&a.serialize(t,r);let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,o=!r.skipEscape&&t.scheme===void 0&&!s;t.path!==void 0&&(r.skipEscape?t.path=bp(t.path):t.path=yp(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=vp(t.scheme),i.push(t.scheme,":"));let u=F_(t);if(u!==void 0&&(r.reference!=="suffix"&&i.push("//"),i.push(u),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!r.absolutePath&&(!a||!a.absolutePath)&&(l=Lr(l)),o&&(l=yp(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",x_(t.query)),t.fragment!==void 0&&i.push("#",N_(t.fragment)),i.join("")}var V_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,q_=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,j_=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function L_(n,e){if(e[2]!==void 0&&n.path&&n.path[0]!=="/")return 'URI path must start with "/" when authority is present.';if(typeof n.port=="number"&&(n.port<0||n.port>65535))return "URI port is malformed."}function jr(n){if(n===void 0)return false;let e=n.indexOf("%");for(;e!==-1;){if(e+2>=n.length||!/^[\da-f]{2}$/iu.test(n.slice(e+1,e+3)))return true;e=n.indexOf("%",e+3);}return false}function B_(n){let e=n[4];return jr(n[3])||e!==void 0&&!(e[0]==="["&&e[e.length-1]==="]")&&jr(e)||jr(n[6])||jr(n[7])||jr(n[8])}function Fp(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&n.host[0]!=="["&&(e.domainHost||t&&t.domainHost)&&r===false&&I_(n.host))try{n.host=new URL("http://"+n.host).hostname;}catch(i){return n.error=n.error||"Host's domain name can not be converted to ASCII: "+i,true}return false}function os(n,e){let t=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=false,a=false,s=false,o=false,u=false,l=false,c=false;t.reference==="suffix"&&(t.scheme?n=t.scheme+":"+n:n="//"+n);let h=n.match(q_);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let d=n.match(j_);if(d!==null){let m=d[1],f=m.replace(/[\t\n\r]/g,"");f.length>=2&&(f.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):m.length!==f.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let p=n.match(V_);if(p){if(r.scheme=p[1],r.userinfo=p[3],r.host=p[4],r.port=parseInt(p[5],10),r.path=p[6]||"",r.query=p[7],r.fragment=p[8],r.scheme!==void 0){let v=unescape(r.scheme);wp.test(v)?r.scheme=v.toLowerCase():(r.error=r.error||Ap,l=true);}a=B_(p),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=p[5]);let m=L_(r,p);if(m!==void 0&&(r.error=r.error||m,i=true),r.host)if(Sp(r.host)===false){let _=r.host[0]==="["&&r.host[r.host.length-1]==="]",b=Ep(r.host);c=b.isIPV6||b.isIPVFuture===true,u=_&&b.error===true,r.host=c?b.host:b.host.toLowerCase(),u&&(r.error=r.error||"URI host is malformed.",i=true);}else c=true;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");let f=il(t.scheme||r.scheme);if(o=Fp(r,t,f,c),!f||f&&!f.skipNormalize){if(n.indexOf("%")!==-1&&r.host!==void 0&&!u){let v=c?r.host:bp(r.host,true);r.host=T_(v,c);}r.path&&(r.path=O_(r.path)),r.query&&(r.query=Cp(r.query)),r.fragment&&(r.fragment=Cp(r.fragment));}f&&f.parse&&(f.parse(r,t),f===Dp.urn&&r.nid===void 0&&(s=true));}else r.error=r.error||"URI can not be parsed.";return {parsed:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:l}}function us(n,e){return os(n,e).parsed}function W_(n,e){return Op(n,e).normalized}function Op(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=os(n,e);return {normalized:r||i||a||s||o?n:fn(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function _p(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:fn(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=Op(t,e);return i||a||s||o||u?void 0:r}var sl={SCHEMES:Dp,normalize:k_,resolve:$_,resolveComponent:Pp,equal:R_,serialize:fn,parse:us};ls.exports=sl;ls.exports.default=sl;ls.exports.fastUri=sl;});var Tp=y(al=>{Object.defineProperty(al,"__esModule",{value:true});var Np=xp();Np.code='require("ajv/dist/runtime/uri").default';al.default=Np;});var ll=y(Ce=>{Object.defineProperty(Ce,"__esModule",{value:true});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var M_=jn();Object.defineProperty(Ce,"KeywordCxt",{enumerable:true,get:function(){return M_.KeywordCxt}});var Wn=I();Object.defineProperty(Ce,"_",{enumerable:true,get:function(){return Wn._}});Object.defineProperty(Ce,"str",{enumerable:true,get:function(){return Wn.str}});Object.defineProperty(Ce,"stringify",{enumerable:true,get:function(){return Wn.stringify}});Object.defineProperty(Ce,"nil",{enumerable:true,get:function(){return Wn.nil}});Object.defineProperty(Ce,"Name",{enumerable:true,get:function(){return Wn.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:true,get:function(){return Wn.CodeGen}});var G_=Vr(),Vp=Ln(),U_=xu(),Br=qr(),H_=I(),Wr=kr(),cs=Ir(),ul=L(),Ip=ip(),K_=Tp(),qp=(n,e)=>new RegExp(n,e);qp.code="new RegExp";var z_=["removeAdditional","useDefaults","coerceTypes"],J_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Z_={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."},X_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},kp=200;function Q_(n){var e,t,r,i,a,s,o,u,l,c,h,d,p,m,f,v,_,b,E,g,C,S,w,O,A;let $=n.strict,Ee=(e=n.code)===null||e===void 0?void 0:e.optimize,Rt=Ee===true||Ee===void 0?1:Ee||0,Er=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:qp,xn=(i=n.uriResolver)!==null&&i!==void 0?i:K_.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:$)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:$)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:$)!==null&&c!==void 0?c:"log",strictTuples:(d=(h=n.strictTuples)!==null&&h!==void 0?h:$)!==null&&d!==void 0?d:"log",strictRequired:(m=(p=n.strictRequired)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:false,code:n.code?{...n.code,optimize:Rt,regExp:Er}:{optimize:Rt,regExp:Er},loopRequired:(f=n.loopRequired)!==null&&f!==void 0?f:kp,loopEnum:(v=n.loopEnum)!==null&&v!==void 0?v:kp,meta:(_=n.meta)!==null&&_!==void 0?_:true,messages:(b=n.messages)!==null&&b!==void 0?b:true,inlineRefs:(E=n.inlineRefs)!==null&&E!==void 0?E:true,schemaId:(g=n.schemaId)!==null&&g!==void 0?g:"$id",addUsedSchema:(C=n.addUsedSchema)!==null&&C!==void 0?C:true,validateSchema:(S=n.validateSchema)!==null&&S!==void 0?S:true,validateFormats:(w=n.validateFormats)!==null&&w!==void 0?w:true,unicodeRegExp:(O=n.unicodeRegExp)!==null&&O!==void 0?O:true,int32range:(A=n.int32range)!==null&&A!==void 0?A:true,uriResolver:xn}}var Mr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Q_(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new H_.ValueScope({scope:{},prefixes:J_,es5:t,lines:r}),this.logger=iE(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, U_.getRules)(),$p.call(this,Z_,e,"NOT SUPPORTED"),$p.call(this,X_,e,"DEPRECATED","warn"),this._metaOpts=nE.call(this),e.formats&&eE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&tE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Y_.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=Ip;r==="id"&&(i={...Ip},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[r],false);}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);return "$async"in r||(this.errors=r.errors),i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(c,h){await a.call(this,c.$schema);let d=this._addSchema(c,h);return d.validate||s.call(this,d)}async function a(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},true);}async function s(c){try{return this._compileSchemaEnv(c)}catch(h){if(!(h instanceof Vp.default))throw h;return o.call(this,h),await u.call(this,h.missingSchema),s.call(this,c)}}function o({missingSchema:c,missingRef:h}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${h} cannot be resolved`)}async function u(c){let h=await l.call(this,c);this.refs[c]||await a.call(this,h.$schema),this.refs[c]||this.addSchema(h,c,t);}async function l(c){let h=this._loading[c];if(h)return h;try{return await(this._loading[c]=r(c))}finally{delete this._loading[c];}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return t=(0, Wr.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,true),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,true,r),this}validateSchema(e,t){if(typeof e=="boolean")return true;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,true;let i=this.validate(r,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=Rp.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new Br.SchemaEnv({schema:{},schemaId:r});if(t=Br.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t;}return t.validate||this._compileSchemaEnv(t)}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 t=Rp.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case "object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0, Wr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string")r=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(aE.call(this,r,t),!t)return (0, ul.eachItem)(r,a=>ol.call(this,a)),this;uE.call(this,t);let i={...t,type:(0, cs.getJSONTypes)(t.type),schemaType:(0, cs.getJSONTypes)(t.schemaType)};return (0, ul.eachItem)(r,i.type.length===0?a=>ol.call(this,a,i):a=>i.type.forEach(s=>ol.call(this,a,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex(a=>a.keyword===e);i>=0&&r.rules.splice(i,1);}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return !e||e.length===0?"No errors":e.map(i=>`${r}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in r){let u=r[o];if(typeof u!="object")continue;let{$data:l}=u.definition,c=s[o];l&&c&&(s[o]=jp(c));}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];(!t||t.test(r))&&(typeof i=="string"?delete e[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[r]));}}_addSchema(e,t,r,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];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 u=this._cache.get(e);if(u!==void 0)return u;r=(0, Wr.normalizeId)(s||r);let l=Wr.getSchemaRefs.call(this,e,r);return u=new Br.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),i&&this.validateSchema(e,true),u}_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):Br.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Br.compileSchema.call(this,e);}finally{this.opts=t;}}};Mr.ValidationError=G_.default;Mr.MissingRefError=Vp.default;Ce.default=Mr;function $p(n,e,t,r="error"){for(let i in n){let a=i;a in e&&this.logger[r](`${t}: option ${i}. ${n[a]}`);}}function Rp(n){return n=(0, Wr.normalizeId)(n),this.schemas[n]||this.refs[n]}function Y_(){let n=this.opts.schemas;if(n)if(Array.isArray(n))this.addSchema(n);else for(let e in n)this.addSchema(n[e],e);}function eE(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function tE(n){if(Array.isArray(n)){this.addVocabulary(n);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in n){let t=n[e];t.keyword||(t.keyword=e),this.addKeyword(t);}}function nE(){let n={...this.opts};for(let e of z_)delete n[e];return n}var rE={log(){},warn(){},error(){}};function iE(n){if(n===false)return rE;if(n===void 0)return console;if(n.log&&n.warn&&n.error)return n;throw new Error("logger must implement log, warn and error methods")}var sE=/^[a-z_$][a-z0-9_$:-]*$/i;function aE(n,e){let{RULES:t}=this;if((0, ul.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!sE.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ol(n,e,t){var r;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:u})=>u===t);if(s||(s={type:t,rules:[]},a.rules.push(s)),a.keywords[n]=true,!e)return;let o={keyword:n,definition:{...e,type:(0, cs.getJSONTypes)(e.type),schemaType:(0, cs.getJSONTypes)(e.schemaType)}};e.before?oE.call(this,s,o,e.before):s.rules.push(o),a.all[n]=o,(r=e.implements)===null||r===void 0||r.forEach(u=>this.addKeyword(u));}function oE(n,e,t){let r=n.rules.findIndex(i=>i.keyword===t);r>=0?n.rules.splice(r,0,e):(n.rules.push(e),this.logger.warn(`rule ${t} is not defined`));}function uE(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=jp(e)),n.validateSchema=this.compile(e,true));}var lE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jp(n){return {anyOf:[n,lE]}}});var Lp=y(cl=>{Object.defineProperty(cl,"__esModule",{value:true});var cE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};cl.default=cE;});var fs=y(pn=>{Object.defineProperty(pn,"__esModule",{value:true});pn.callRef=pn.getValidate=void 0;var hE=Ln(),Bp=Ze(),Le=I(),Mn=Je(),Wp=qr(),hs=L(),dE={keyword:"$ref",schemaType:"string",code(n){let{gen:e,schema:t,it:r}=n,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:u}=r,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return h();let c=Wp.resolveRef.call(u,l,i,t);if(c===void 0)throw new hE.default(r.opts.uriResolver,i,t);if(c instanceof Wp.SchemaEnv)return d(c);return p(c);function h(){if(a===l)return ds(n,s,a,a.$async);let m=e.scopeValue("root",{ref:l});return ds(n,(0, Le._)`${m}.validate`,l,l.$async)}function d(m){let f=Mp(n,m);ds(n,f,m,m.$async);}function p(m){let f=e.scopeValue("schema",o.code.source===true?{ref:m,code:(0, Le.stringify)(m)}:{ref:m}),v=e.name("valid"),_=n.subschema({schema:m,dataTypes:[],schemaPath:Le.nil,topSchemaRef:f,errSchemaPath:t},v);n.mergeEvaluated(_),n.ok(v);}}};function Mp(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, Le._)`${t.scopeValue("wrapper",{ref:e})}.validate`}pn.getValidate=Mp;function ds(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?Mn.default.this:Le.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0, Le._)`await ${(0, Bp.callValidateCode)(n,e,l)}`),p(e),s||i.assign(m,true);},f=>{i.if((0, Le._)`!(${f} instanceof ${a.ValidationError})`,()=>i.throw(f)),d(f),s||i.assign(m,false);}),n.ok(m);}function h(){n.result((0, Bp.callValidateCode)(n,e,l),()=>p(e),()=>d(e));}function d(m){let f=(0, Le._)`${m}.errors`;i.assign(Mn.default.vErrors,(0, Le._)`${Mn.default.vErrors} === null ? ${f} : ${Mn.default.vErrors}.concat(${f})`),i.assign(Mn.default.errors,(0, Le._)`${Mn.default.vErrors}.length`);}function p(m){var f;if(!a.opts.unevaluated)return;let v=(f=t?.validate)===null||f===void 0?void 0:f.evaluated;if(a.props!==true)if(v&&!v.dynamicProps)v.props!==void 0&&(a.props=hs.mergeEvaluated.props(i,v.props,a.props));else {let _=i.var("props",(0, Le._)`${m}.evaluated.props`);a.props=hs.mergeEvaluated.props(i,_,a.props,Le.Name);}if(a.items!==true)if(v&&!v.dynamicItems)v.items!==void 0&&(a.items=hs.mergeEvaluated.items(i,v.items,a.items));else {let _=i.var("items",(0, Le._)`${m}.evaluated.items`);a.items=hs.mergeEvaluated.items(i,_,a.items,Le.Name);}}}pn.callRef=ds;pn.default=dE;});var dl=y(hl=>{Object.defineProperty(hl,"__esModule",{value:true});var fE=Lp(),pE=fs(),mE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fE.default,pE.default];hl.default=mE;});var Gp=y(fl=>{Object.defineProperty(fl,"__esModule",{value:true});var ps=I(),Gt=ps.operators,ms={maximum:{okStr:"<=",ok:Gt.LTE,fail:Gt.GT},minimum:{okStr:">=",ok:Gt.GTE,fail:Gt.LT},exclusiveMaximum:{okStr:"<",ok:Gt.LT,fail:Gt.GTE},exclusiveMinimum:{okStr:">",ok:Gt.GT,fail:Gt.LTE}},gE={message:({keyword:n,schemaCode:e})=>(0, ps.str)`must be ${ms[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, ps._)`{comparison: ${ms[n].okStr}, limit: ${e}}`},yE={keyword:Object.keys(ms),type:"number",schemaType:"number",$data:true,error:gE,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, ps._)`${t} ${ms[e].fail} ${r} || isNaN(${t})`);}};fl.default=yE;});var Up=y(pl=>{Object.defineProperty(pl,"__esModule",{value:true});var Gr=I(),CE={message:({schemaCode:n})=>(0, Gr.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, Gr._)`{multipleOf: ${n}}`},vE={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:CE,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, Gr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, Gr._)`${s} !== parseInt(${s})`;n.fail$data((0, Gr._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};pl.default=vE;});var Kp=y(ml=>{Object.defineProperty(ml,"__esModule",{value:true});function Hp(n){let e=n.length,t=0,r=0,i;for(;r<e;)t++,i=n.charCodeAt(r++),i>=55296&&i<=56319&&r<e&&(i=n.charCodeAt(r),(i&64512)===56320&&r++);return t}ml.default=Hp;Hp.code='require("ajv/dist/runtime/ucs2length").default';});var zp=y(gl=>{Object.defineProperty(gl,"__esModule",{value:true});var mn=I(),_E=L(),EE=Kp(),bE={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, mn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, mn._)`{limit: ${n}}`},SE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:bE,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?mn.operators.GT:mn.operators.LT,s=i.opts.unicode===false?(0, mn._)`${t}.length`:(0, mn._)`${(0, _E.useFunc)(n.gen,EE.default)}(${t})`;n.fail$data((0, mn._)`${s} ${a} ${r}`);}};gl.default=SE;});var Jp=y(yl=>{Object.defineProperty(yl,"__esModule",{value:true});var DE=Ze(),wE=L(),Gn=I(),AE={message:({schemaCode:n})=>(0, Gn.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, Gn._)`{pattern: ${n}}`},PE={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:AE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n,o=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:u}=s.opts.code,l=u.code==="new RegExp"?(0, Gn._)`new RegExp`:(0, wE.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, Gn._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, Gn._)`!${c}`);}else {let u=(0, DE.usePattern)(n,i);n.fail$data((0, Gn._)`!${u}.test(${t})`);}}};yl.default=PE;});var Zp=y(Cl=>{Object.defineProperty(Cl,"__esModule",{value:true});var Ur=I(),FE={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Ur.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Ur._)`{limit: ${n}}`},OE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:FE,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Ur.operators.GT:Ur.operators.LT;n.fail$data((0, Ur._)`Object.keys(${t}).length ${i} ${r}`);}};Cl.default=OE;});var Xp=y(vl=>{Object.defineProperty(vl,"__esModule",{value:true});var Hr=Ze(),Kr=I(),xE=L(),NE={message:({params:{missingProperty:n}})=>(0, Kr.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, Kr._)`{missingProperty: ${n}}`},TE={keyword:"required",type:"object",schemaType:"array",$data:true,error:NE,code(n){let{gen:e,schema:t,schemaCode:r,data:i,$data:a,it:s}=n,{opts:o}=s;if(!a&&t.length===0)return;let u=t.length>=o.loopRequired;if(s.allErrors?l():c(),o.strictRequired){let p=n.parentSchema.properties,{definedProperties:m}=n.it;for(let f of t)if(p?.[f]===void 0&&!m.has(f)){let v=s.schemaEnv.baseId+s.errSchemaPath,_=`required property "${f}" is not defined at "${v}" (strictRequired)`;(0, xE.checkStrictMode)(s,_,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(Kr.nil,h);else for(let p of t)(0, Hr.checkReportMissingProp)(n,p);}function c(){let p=e.let("missing");if(u||a){let m=e.let("valid",true);n.block$data(m,()=>d(p,m)),n.ok(m);}else e.if((0, Hr.checkMissingProp)(n,t,p)),(0, Hr.reportMissingProp)(n,p),e.else();}function h(){e.forOf("prop",r,p=>{n.setParams({missingProperty:p}),e.if((0, Hr.noPropertyInData)(e,i,p,o.ownProperties),()=>n.error());});}function d(p,m){n.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(m,(0, Hr.propertyInData)(e,i,p,o.ownProperties)),e.if((0, Kr.not)(m),()=>{n.error(),e.break();});},Kr.nil);}}};vl.default=TE;});var Qp=y(_l=>{Object.defineProperty(_l,"__esModule",{value:true});var zr=I(),IE={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, zr.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, zr._)`{limit: ${n}}`},kE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:IE,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?zr.operators.GT:zr.operators.LT;n.fail$data((0, zr._)`${t}.length ${i} ${r}`);}};_l.default=kE;});var gs=y(El=>{Object.defineProperty(El,"__esModule",{value:true});var Yp=qu();Yp.code='require("ajv/dist/runtime/equal").default';El.default=Yp;});var em=y(Sl=>{Object.defineProperty(Sl,"__esModule",{value:true});var bl=Ir(),ve=I(),$E=L(),RE=gs(),VE={message:({params:{i:n,j:e}})=>(0, ve.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, ve._)`{i: ${n}, j: ${e}}`},qE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:VE,code(n){let{gen:e,data:t,$data:r,schema:i,parentSchema:a,schemaCode:s,it:o}=n;if(!r&&!i)return;let u=e.let("valid"),l=a.items?(0, bl.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, ve._)`${s} === false`),n.ok(u);function c(){let m=e.let("i",(0, ve._)`${t}.length`),f=e.let("j");n.setParams({i:m,j:f}),e.assign(u,true),e.if((0, ve._)`${m} > 1`,()=>(h()?d:p)(m,f));}function h(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function d(m,f){let v=e.name("item"),_=(0, bl.checkDataTypes)(l,v,o.opts.strictNumbers,bl.DataType.Wrong),b=e.const("indices",(0, ve._)`{}`);e.for((0, ve._)`;${m}--;`,()=>{e.let(v,(0, ve._)`${t}[${m}]`),e.if(_,(0, ve._)`continue`),l.length>1&&e.if((0, ve._)`typeof ${v} == "string"`,(0, ve._)`${v} += "_"`),e.if((0, ve._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(f,(0, ve._)`${b}[${v}]`),n.error(),e.assign(u,false).break();}).code((0, ve._)`${b}[${v}] = ${m}`);});}function p(m,f){let v=(0, $E.useFunc)(e,RE.default),_=e.name("outer");e.label(_).for((0, ve._)`;${m}--;`,()=>e.for((0, ve._)`${f} = ${m}; ${f}--;`,()=>e.if((0, ve._)`${v}(${t}[${m}], ${t}[${f}])`,()=>{n.error(),e.assign(u,false).break(_);})));}}};Sl.default=qE;});var tm=y(wl=>{Object.defineProperty(wl,"__esModule",{value:true});var Dl=I(),jE=L(),LE=gs(),BE={message:"must be equal to constant",params:({schemaCode:n})=>(0, Dl._)`{allowedValue: ${n}}`},WE={keyword:"const",$data:true,error:BE,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, Dl._)`!${(0, jE.useFunc)(e,LE.default)}(${t}, ${i})`):n.fail((0, Dl._)`${a} !== ${t}`);}};wl.default=WE;});var nm=y(Al=>{Object.defineProperty(Al,"__esModule",{value:true});var Jr=I(),ME=L(),GE=gs(),UE={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, Jr._)`{allowedValues: ${n}}`},HE={keyword:"enum",schemaType:"array",$data:true,error:UE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n;if(!r&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,u,l=()=>u??(u=(0, ME.useFunc)(e,GE.default)),c;if(o||r)c=e.let("valid"),n.block$data(c,h);else {if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",a);c=(0, Jr.or)(...i.map((m,f)=>d(p,f)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,p=>e.if((0, Jr._)`${l()}(${t}, ${p})`,()=>e.assign(c,true).break()));}function d(p,m){let f=i[m];return typeof f=="object"&&f!==null?(0, Jr._)`${l()}(${t}, ${p}[${m}])`:(0, Jr._)`${t} === ${f}`}}};Al.default=HE;});var Fl=y(Pl=>{Object.defineProperty(Pl,"__esModule",{value:true});var KE=Gp(),zE=Up(),JE=zp(),ZE=Jp(),XE=Zp(),QE=Xp(),YE=Qp(),eb=em(),tb=tm(),nb=nm(),rb=[KE.default,zE.default,JE.default,ZE.default,XE.default,QE.default,YE.default,eb.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},tb.default,nb.default];Pl.default=rb;});var xl=y(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.validateAdditionalItems=void 0;var gn=I(),Ol=L(),ib={message:({params:{len:n}})=>(0, gn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, gn._)`{limit: ${n}}`},sb={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ib,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, Ol.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}rm(n,r);}};function rm(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, gn._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, gn._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, Ol.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, gn._)`${o} <= ${e.length}`);t.if((0, gn.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:Ol.Type.Num},l),s.allErrors||t.if((0, gn.not)(l),()=>t.break());});}}Zr.validateAdditionalItems=rm;Zr.default=sb;});var Nl=y(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.validateTuple=void 0;var im=I(),ys=L(),ab=Ze(),ob={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return sm(n,"additionalItems",e);t.items=true,!(0, ys.alwaysValidSchema)(t,e)&&n.ok((0, ab.validateArray)(n));}};function sm(n,e,t=n.schema){let{gen:r,parentSchema:i,data:a,keyword:s,it:o}=n;c(i),o.opts.unevaluated&&t.length&&o.items!==true&&(o.items=ys.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, im._)`${a}.length`);t.forEach((h,d)=>{(0, ys.alwaysValidSchema)(o,h)||(r.if((0, im._)`${l} > ${d}`,()=>n.subschema({keyword:s,schemaProp:d,dataProp:d},u)),n.ok(u));});function c(h){let{opts:d,errSchemaPath:p}=o,m=t.length,f=m===h.minItems&&(m===h.maxItems||h[e]===false);if(d.strictTuples&&!f){let v=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0, ys.checkStrictMode)(o,v,d.strictTuples);}}}Xr.validateTuple=sm;Xr.default=ob;});var am=y(Tl=>{Object.defineProperty(Tl,"__esModule",{value:true});var ub=Nl(),lb={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, ub.validateTuple)(n,"items")};Tl.default=lb;});var um=y(Il=>{Object.defineProperty(Il,"__esModule",{value:true});var om=I(),cb=L(),hb=Ze(),db=xl(),fb={message:({params:{len:n}})=>(0, om.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, om._)`{limit: ${n}}`},pb={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:fb,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, cb.alwaysValidSchema)(r,e)&&(i?(0, db.validateAdditionalItems)(n,i):n.ok((0, hb.validateArray)(n)));}};Il.default=pb;});var lm=y(kl=>{Object.defineProperty(kl,"__esModule",{value:true});var Qe=I(),Cs=L(),mb={message:({params:{min:n,max:e}})=>e===void 0?(0, Qe.str)`must contain at least ${n} valid item(s)`:(0, Qe.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, Qe._)`{minContains: ${n}}`:(0, Qe._)`{minContains: ${n}, maxContains: ${e}}`},gb={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:mb,code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n,s,o,{minContains:u,maxContains:l}=r;a.opts.next?(s=u===void 0?1:u,o=l):s=1;let c=e.const("len",(0, Qe._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, Cs.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, Cs.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, Cs.alwaysValidSchema)(a,t)){let f=(0, Qe._)`${c} >= ${s}`;o!==void 0&&(f=(0, Qe._)`${f} && ${c} <= ${o}`),n.pass(f);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?p(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, Qe._)`${i}.length > 0`,d)):(e.let(h,false),d()),n.result(h,()=>n.reset());function d(){let f=e.name("_valid"),v=e.let("count",0);p(f,()=>e.if(f,()=>m(v)));}function p(f,v){e.forRange("i",0,c,_=>{n.subschema({keyword:"contains",dataProp:_,dataPropType:Cs.Type.Num,compositeRule:true},f),v();});}function m(f){e.code((0, Qe._)`${f}++`),o===void 0?e.if((0, Qe._)`${f} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, Qe._)`${f} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, Qe._)`${f} >= ${s}`,()=>e.assign(h,true)));}}};kl.default=gb;});var vs=y(mt=>{Object.defineProperty(mt,"__esModule",{value:true});mt.validateSchemaDeps=mt.validatePropertyDeps=mt.error=void 0;var $l=I(),yb=L(),Qr=Ze();mt.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, $l.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, $l._)`{property: ${n},
1
+ 'use strict';var zod=require('zod');var yy=Object.create;var Zd=Object.defineProperty;var Cy=Object.getOwnPropertyDescriptor;var vy=Object.getOwnPropertyNames;var _y=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var C=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var by=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vy(e))!Ey.call(n,i)&&i!==t&&Zd(n,i,{get:()=>e[i],enumerable:!(r=Cy(e,i))||r.enumerable});return n};var Bi=(n,e,t)=>(t=n!=null?yy(_y(n)):{},by(Zd(t,"default",{value:n,enumerable:true}),n));var Ar=C(U=>{Object.defineProperty(U,"__esModule",{value:true});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Dr=class{};U._CodeOrName=Dr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rn=class extends Dr{constructor(e){if(super(),!U.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};U.Name=rn;var ze=class extends Dr{constructor(e){super(),this._items=typeof e=="string"?[e]:e;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;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((t,r)=>`${t}${r}`,"")}get names(){var e;return (e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>(r instanceof rn&&(t[r.str]=(t[r.str]||0)+1),t),{})}};U._Code=ze;U.nil=new ze("");function uf(n,...e){let t=[n[0]],r=0;for(;r<e.length;)cu(t,e[r]),t.push(n[++r]);return new ze(t)}U._=uf;var lu=new ze("+");function lf(n,...e){let t=[wr(n[0])],r=0;for(;r<e.length;)t.push(lu),cu(t,e[r]),t.push(lu,wr(n[++r]));return Ry(t),new ze(t)}U.str=lf;function cu(n,e){e instanceof ze?n.push(...e._items):e instanceof rn?n.push(e):n.push(jy(e));}U.addCodeArg=cu;function Ry(n){let e=1;for(;e<n.length-1;){if(n[e]===lu){let t=Vy(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function Vy(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof rn||n[n.length-1]!=='"'?void 0:typeof e!="string"?`${n.slice(0,-1)}${e}"`:e[0]==='"'?n.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(n instanceof rn))return `"${n}${e.slice(1)}`}function qy(n,e){return e.emptyStr()?n:n.emptyStr()?e:lf`${n}${e}`}U.strConcat=qy;function jy(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:wr(Array.isArray(n)?n.join(","):n)}function Ly(n){return new ze(wr(n))}U.stringify=Ly;function wr(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=wr;function By(n){return typeof n=="string"&&U.IDENTIFIER.test(n)?new ze(`.${n}`):uf`[${n}]`}U.getProperty=By;function Wy(n){if(typeof n=="string"&&U.IDENTIFIER.test(n))return new ze(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}U.getEsmExportName=Wy;function My(n){return new ze(n.toString())}U.regexpCode=My;});var fu=C(Ve=>{Object.defineProperty(Ve,"__esModule",{value:true});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Re=Ar(),hu=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},Hi;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(Hi||(Ve.UsedValueState=Hi={}));Ve.varKinds={const:new Re.Name("const"),let:new Re.Name("let"),var:new Re.Name("var")};var Ki=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof Re.Name?e:this.name(e)}name(e){return new Re.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return `${e}${t.index++}`}_nameGroup(e){var t,r;if(!((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ve.Scope=Ki;var zi=class extends Re.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, Re._)`.${new Re.Name(t)}[${r}]`;}};Ve.ValueScopeName=zi;var Gy=(0, Re._)`\n`,du=class extends Ki{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Gy:Re.nil};}get(){return this._scope}name(e){return new zi(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:a}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[a];if(o){let c=o.get(s);if(c)return c}else o=this._values[a]=new Map;o.set(s,i);let u=this._scope[a]||(this._scope[a]=[]),l=u.length;return u[l]=t.ref,i.setValue(t,{property:a,itemIndex:l}),i}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return (0, Re._)`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let a=Re.nil;for(let s in e){let o=e[s];if(!o)continue;let u=r[s]=r[s]||new Map;o.forEach(l=>{if(u.has(l))return;u.set(l,Hi.Started);let c=t(l);if(c){let h=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;a=(0, Re._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, Re._)`${a}${c}${this.opts._n}`;else throw new hu(l);u.set(l,Hi.Completed);});}return a}};Ve.ValueScope=du;});var T=C(R=>{Object.defineProperty(R,"__esModule",{value:true});R.or=R.and=R.not=R.CodeGen=R.operators=R.varKinds=R.ValueScopeName=R.ValueScope=R.Scope=R.Name=R.regexpCode=R.stringify=R.getProperty=R.nil=R.strConcat=R.str=R._=void 0;var W=Ar(),ot=fu(),Vt=Ar();Object.defineProperty(R,"_",{enumerable:true,get:function(){return Vt._}});Object.defineProperty(R,"str",{enumerable:true,get:function(){return Vt.str}});Object.defineProperty(R,"strConcat",{enumerable:true,get:function(){return Vt.strConcat}});Object.defineProperty(R,"nil",{enumerable:true,get:function(){return Vt.nil}});Object.defineProperty(R,"getProperty",{enumerable:true,get:function(){return Vt.getProperty}});Object.defineProperty(R,"stringify",{enumerable:true,get:function(){return Vt.stringify}});Object.defineProperty(R,"regexpCode",{enumerable:true,get:function(){return Vt.regexpCode}});Object.defineProperty(R,"Name",{enumerable:true,get:function(){return Vt.Name}});var Qi=fu();Object.defineProperty(R,"Scope",{enumerable:true,get:function(){return Qi.Scope}});Object.defineProperty(R,"ValueScope",{enumerable:true,get:function(){return Qi.ValueScope}});Object.defineProperty(R,"ValueScopeName",{enumerable:true,get:function(){return Qi.ValueScopeName}});Object.defineProperty(R,"varKinds",{enumerable:true,get:function(){return Qi.varKinds}});R.operators={GT:new W._Code(">"),GTE:new W._Code(">="),LT:new W._Code("<"),LTE:new W._Code("<="),EQ:new W._Code("==="),NEQ:new W._Code("!=="),NOT:new W._Code("!"),OR:new W._Code("||"),AND:new W._Code("&&"),ADD:new W._Code("+")};var Ot=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},pu=class extends Ot{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?ot.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return `${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Tn(this.rhs,e,t)),this}get names(){return this.rhs instanceof W._CodeOrName?this.rhs.names:{}}},Ji=class extends Ot{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r;}render({_n:e}){return `${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof W.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Tn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof W.Name?{}:{...this.lhs.names};return Xi(e,this.rhs)}},mu=class extends Ji{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},gu=class extends Ot{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},yu=class extends Ot{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},Cu=class extends Ot{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},vu=class extends Ot{constructor(e){super(),this.code=e;}render({_n:e}){return `${this.code};`+e}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Tn(this.code,e,t),this}get names(){return this.code instanceof W._CodeOrName?this.code.names:{}}},Pr=class extends Ot{constructor(e=[]){super(),this.nodes=e;}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1);}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;for(;i--;){let a=r[i];a.optimizeNames(e,t)||(Uy(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>on(e,t.names),{})}},xt=class extends Pr{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},_u=class extends Pr{},Nn=class extends xt{};Nn.kind="else";var sn=class n extends xt{constructor(e,t){super(t),this.condition=e;}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===true)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new Nn(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(cf(e),t instanceof n?[t]:t.nodes);if(!(e===false||!this.nodes.length))return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=Tn(this.condition,e,t),this}get names(){let e=super.names;return Xi(e,this.condition),this.else&&on(e,this.else.names),e}};sn.kind="if";var an=class extends xt{};an.kind="for";var Eu=class extends an{constructor(e){super(),this.iteration=e;}render(e){return `for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Tn(this.iteration,e,t),this}get names(){return on(super.names,this.iteration.names)}},bu=class extends an{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?ot.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return `for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){let e=Xi(super.names,this.from);return Xi(e,this.to)}},Zi=class extends an{constructor(e,t,r,i){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=i;}render(e){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Tn(this.iterable,e,t),this}get names(){return on(super.names,this.iterable.names)}},Fr=class extends xt{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r;}render(e){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Fr.kind="func";var Or=class extends Pr{render(e){return "return "+super.render(e)}};Or.kind="return";var Su=class extends xt{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&on(e,this.catch.names),this.finally&&on(e,this.finally.names),e}},xr=class extends xt{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};xr.kind="catch";var Nr=class extends xt{render(e){return "finally"+super.render(e)}};Nr.kind="finally";var Du=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
+ `:""},this._extScope=e,this._scope=new ot.Scope({parent:e}),this._nodes=[new _u];}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return (this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let a=this._scope.toName(t);return r!==void 0&&i&&(this._constants[a.str]=r),this._leafNode(new pu(e,a,r)),a}const(e,t,r){return this._def(ot.varKinds.const,e,t,r)}let(e,t,r){return this._def(ot.varKinds.let,e,t,r)}var(e,t,r){return this._def(ot.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new Ji(e,t,r))}add(e,t){return this._leafNode(new mu(e,R.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==W.nil&&this._leafNode(new vu(e)),this}object(...e){let t=["{"];for(let[r,i]of e)t.length>1&&t.push(","),t.push(r),(r!==i||this.opts.es5)&&(t.push(":"),(0, W.addCodeArg)(t,i));return t.push("}"),new W._Code(t)}if(e,t,r){if(this._blockNode(new sn(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new sn(e))}else(){return this._elseNode(new Nn)}endIf(){return this._endBlockNode(sn,Nn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Eu(e),t)}forRange(e,t,r,i,a=this.opts.es5?ot.varKinds.var:ot.varKinds.let){let s=this._scope.toName(e);return this._for(new bu(a,s,t,r),()=>i(s))}forOf(e,t,r,i=ot.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof W.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, W._)`${s}.length`,o=>{this.var(a,(0, W._)`${s}[${o}]`),r(a);})}return this._for(new Zi("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?ot.varKinds.var:ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, W._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new Zi("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(an)}label(e){return this._leafNode(new gu(e))}break(e){return this._leafNode(new yu(e))}return(e){let t=new Or;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Or)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Su;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new xr(a),t(a);}return r&&(this._currNode=i.finally=new Nr,this.code(r)),this._endBlockNode(xr,Nr)}throw(e){return this._leafNode(new Cu(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=W.nil,r,i){return this._blockNode(new Fr(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Fr)}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,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof sn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e;}};R.CodeGen=Du;function on(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function Xi(n,e){return e instanceof W._CodeOrName?on(n,e.names):n}function Tn(n,e,t){if(n instanceof W.Name)return r(n);if(!i(n))return n;return new W._Code(n._items.reduce((a,s)=>(s instanceof W.Name&&(s=r(s)),s instanceof W._Code?a.push(...s._items):a.push(s),a),[]));function r(a){let s=t[a.str];return s===void 0||e[a.str]!==1?a:(delete e[a.str],s)}function i(a){return a instanceof W._Code&&a._items.some(s=>s instanceof W.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function Uy(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function cf(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, W._)`!${wu(n)}`}R.not=cf;var Hy=hf(R.operators.AND);function Ky(...n){return n.reduce(Hy)}R.and=Ky;var zy=hf(R.operators.OR);function Jy(...n){return n.reduce(zy)}R.or=Jy;function hf(n){return (e,t)=>e===W.nil?t:t===W.nil?e:(0, W._)`${wu(e)} ${n} ${wu(t)}`}function wu(n){return n instanceof W.Name?n:(0, W._)`(${n})`}});var j=C(q=>{Object.defineProperty(q,"__esModule",{value:true});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var Z=T(),Zy=Ar();function Xy(n){let e={};for(let t of n)e[t]=true;return e}q.toHash=Xy;function Qy(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(pf(n,e),!mf(e,n.self.RULES.all))}q.alwaysValidSchema=Qy;function pf(n,e=n.schema){let{opts:t,self:r}=n;if(!t.strictSchema||typeof e=="boolean")return;let i=r.RULES.keywords;for(let a in e)i[a]||Cf(n,`unknown keyword: "${a}"`);}q.checkUnknownRules=pf;function mf(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}q.schemaHasRules=mf;function Yy(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}q.schemaHasRulesButRef=Yy;function eC({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, Z._)`${t}`}return (0, Z._)`${n}${e}${(0, Z.getProperty)(r)}`}q.schemaRefOrVal=eC;function tC(n){return gf(decodeURIComponent(n))}q.unescapeFragment=tC;function nC(n){return encodeURIComponent(Pu(n))}q.escapeFragment=nC;function Pu(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=Pu;function gf(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=gf;function rC(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}q.eachItem=rC;function df({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof Z.Name?(a instanceof Z.Name?n(i,a,s):e(i,a,s),s):a instanceof Z.Name?(e(i,s,a),a):t(a,s);return o===Z.Name&&!(u instanceof Z.Name)?r(i,u):u}}q.mergeEvaluated={props:df({mergeNames:(n,e,t)=>n.if((0, Z._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, Z._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, Z._)`${t} || {}`).code((0, Z._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, Z._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, Z._)`${t} || {}`),Fu(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:yf}),items:df({mergeNames:(n,e,t)=>n.if((0, Z._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, Z._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, Z._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, Z._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function yf(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, Z._)`{}`);return e!==void 0&&Fu(n,t,e),t}q.evaluatedPropsToName=yf;function Fu(n,e,t){Object.keys(t).forEach(r=>n.assign((0, Z._)`${e}${(0, Z.getProperty)(r)}`,true));}q.setEvaluated=Fu;var ff={};function iC(n,e){return n.scopeValue("func",{ref:e,code:ff[e.code]||(ff[e.code]=new Zy._Code(e.code))})}q.useFunc=iC;var Au;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(Au||(q.Type=Au={}));function sC(n,e,t){if(n instanceof Z.Name){let r=e===Au.Num;return t?r?(0, Z._)`"[" + ${n} + "]"`:(0, Z._)`"['" + ${n} + "']"`:r?(0, Z._)`"/" + ${n}`:(0, Z._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, Z.getProperty)(n).toString():"/"+Pu(n)}q.getErrorPath=sC;function Cf(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}q.checkStrictMode=Cf;});var Je=C(Ou=>{Object.defineProperty(Ou,"__esModule",{value:true});var be=T(),aC={data:new be.Name("data"),valCxt:new be.Name("valCxt"),instancePath:new be.Name("instancePath"),parentData:new be.Name("parentData"),parentDataProperty:new be.Name("parentDataProperty"),rootData:new be.Name("rootData"),dynamicAnchors:new be.Name("dynamicAnchors"),vErrors:new be.Name("vErrors"),errors:new be.Name("errors"),this:new be.Name("this"),self:new be.Name("self"),scope:new be.Name("scope"),json:new be.Name("json"),jsonPos:new be.Name("jsonPos"),jsonLen:new be.Name("jsonLen"),jsonPart:new be.Name("jsonPart")};Ou.default=aC;});var Tr=C(Se=>{Object.defineProperty(Se,"__esModule",{value:true});Se.extendErrors=Se.resetErrorsCount=Se.reportExtraError=Se.reportError=Se.keyword$DataError=Se.keywordError=void 0;var G=T(),Yi=j(),Te=Je();Se.keywordError={message:({keyword:n})=>(0, G.str)`must pass "${n}" keyword validation`};Se.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, G.str)`"${n}" keyword must be ${e} ($data)`:(0, G.str)`"${n}" keyword is invalid ($data)`};function oC(n,e=Se.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=Ef(n,e,t);r??(s||o)?vf(a,u):_f(i,(0, G._)`[${u}]`);}Se.reportError=oC;function uC(n,e=Se.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=Ef(n,e,t);vf(i,o),a||s||_f(r,Te.default.vErrors);}Se.reportExtraError=uC;function lC(n,e){n.assign(Te.default.errors,e),n.if((0, G._)`${Te.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, G._)`${Te.default.vErrors}.length`,e),()=>n.assign(Te.default.vErrors,null)));}Se.resetErrorsCount=lC;function cC({gen:n,keyword:e,schemaValue:t,data:r,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let s=n.name("err");n.forRange("i",i,Te.default.errors,o=>{n.const(s,(0, G._)`${Te.default.vErrors}[${o}]`),n.if((0, G._)`${s}.instancePath === undefined`,()=>n.assign((0, G._)`${s}.instancePath`,(0, G.strConcat)(Te.default.instancePath,a.errorPath))),n.assign((0, G._)`${s}.schemaPath`,(0, G.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, G._)`${s}.schema`,t),n.assign((0, G._)`${s}.data`,r));});}Se.extendErrors=cC;function vf(n,e){let t=n.const("err",e);n.if((0, G._)`${Te.default.vErrors} === null`,()=>n.assign(Te.default.vErrors,(0, G._)`[${t}]`),(0, G._)`${Te.default.vErrors}.push(${t})`),n.code((0, G._)`${Te.default.errors}++`);}function _f(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, G._)`new ${n.ValidationError}(${e})`):(t.assign((0, G._)`${r}.errors`,e),t.return(false));}var un={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function Ef(n,e,t){let{createErrors:r}=n.it;return r===false?(0, G._)`{}`:hC(n,e,t)}function hC(n,e,t={}){let{gen:r,it:i}=n,a=[dC(i,t),fC(n,t)];return pC(n,e,a),r.object(...a)}function dC({errorPath:n},{instancePath:e}){let t=e?(0, G.str)`${n}${(0, Yi.getErrorPath)(e,Yi.Type.Str)}`:n;return [Te.default.instancePath,(0, G.strConcat)(Te.default.instancePath,t)]}function fC({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, G.str)`${e}/${n}`;return t&&(i=(0, G.str)`${i}${(0, Yi.getErrorPath)(t,Yi.Type.Str)}`),[un.schemaPath,i]}function pC(n,{params:e,message:t},r){let{keyword:i,data:a,schemaValue:s,it:o}=n,{opts:u,propertyName:l,topSchemaRef:c,schemaPath:h}=o;r.push([un.keyword,i],[un.params,typeof e=="function"?e(n):e||(0, G._)`{}`]),u.messages&&r.push([un.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([un.schema,s],[un.parentSchema,(0, G._)`${c}${h}`],[Te.default.data,a]),l&&r.push([un.propertyName,l]);}});var Sf=C(In=>{Object.defineProperty(In,"__esModule",{value:true});In.boolOrEmptySchema=In.topBoolOrEmptySchema=void 0;var mC=Tr(),gC=T(),yC=Je(),CC={message:"boolean schema is false"};function vC(n){let{gen:e,schema:t,validateName:r}=n;t===false?bf(n,false):typeof t=="object"&&t.$async===true?e.return(yC.default.data):(e.assign((0, gC._)`${r}.errors`,null),e.return(true));}In.topBoolOrEmptySchema=vC;function _C(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),bf(n)):t.var(e,true);}In.boolOrEmptySchema=_C;function bf(n,e){let{gen:t,data:r}=n,i={gen:t,keyword:"false schema",data:r,schema:false,schemaCode:false,schemaValue:false,params:{},it:n};(0, mC.reportError)(i,CC,void 0,e);}});var xu=C(kn=>{Object.defineProperty(kn,"__esModule",{value:true});kn.getRules=kn.isJSONType=void 0;var EC=["string","number","integer","boolean","null","object","array"],bC=new Set(EC);function SC(n){return typeof n=="string"&&bC.has(n)}kn.isJSONType=SC;function DC(){let n={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...n,integer:true,boolean:true,null:true},rules:[{rules:[]},n.number,n.string,n.array,n.object],post:{rules:[]},all:{},keywords:{}}}kn.getRules=DC;});var Nu=C(qt=>{Object.defineProperty(qt,"__esModule",{value:true});qt.shouldUseRule=qt.shouldUseGroup=qt.schemaHasRulesForType=void 0;function wC({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&Df(n,r)}qt.schemaHasRulesForType=wC;function Df(n,e){return e.rules.some(t=>wf(n,t))}qt.shouldUseGroup=Df;function wf(n,e){var t;return n[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(r=>n[r]!==void 0))}qt.shouldUseRule=wf;});var Ir=C(De=>{Object.defineProperty(De,"__esModule",{value:true});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var AC=xu(),PC=Nu(),FC=Tr(),I=T(),Af=j(),$n;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})($n||(De.DataType=$n={}));function OC(n){let e=Pf(n.type);if(e.includes("null")){if(n.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!e.length&&n.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');n.nullable===true&&e.push("null");}return e}De.getSchemaTypes=OC;function Pf(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(AC.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}De.getJSONTypes=Pf;function xC(n,e){let{gen:t,data:r,opts:i}=n,a=NC(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, PC.schemaHasRulesForType)(n,e[0]));if(s){let o=Iu(e,r,i.strictNumbers,$n.Wrong);t.if(o,()=>{a.length?TC(n,e,a):ku(n);});}return s}De.coerceAndCheckDataType=xC;var Ff=new Set(["string","number","integer","boolean","null"]);function NC(n,e){return e?n.filter(t=>Ff.has(t)||e==="array"&&t==="array"):[]}function TC(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, I._)`typeof ${i}`),o=r.let("coerced",(0, I._)`undefined`);a.coerceTypes==="array"&&r.if((0, I._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, I._)`${i}[0]`).assign(s,(0, I._)`typeof ${i}`).if(Iu(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, I._)`${o} !== undefined`);for(let l of t)(Ff.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),ku(n),r.endIf(),r.if((0, I._)`${o} !== undefined`,()=>{r.assign(i,o),IC(n,o);});function u(l){switch(l){case "string":r.elseIf((0, I._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, I._)`"" + ${i}`).elseIf((0, I._)`${i} === null`).assign(o,(0, I._)`""`);return;case "number":r.elseIf((0, I._)`${s} == "boolean" || ${i} === null
3
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(o,(0, I._)`+${i}`);return;case "integer":r.elseIf((0, I._)`${s} === "boolean" || ${i} === null
4
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(o,(0, I._)`+${i}`);return;case "boolean":r.elseIf((0, I._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(o,false).elseIf((0, I._)`${i} === "true" || ${i} === 1`).assign(o,true);return;case "null":r.elseIf((0, I._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(o,null);return;case "array":r.elseIf((0, I._)`${s} === "string" || ${s} === "number"
5
+ || ${s} === "boolean" || ${i} === null`).assign(o,(0, I._)`[${i}]`);}}}function IC({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, I._)`${e} !== undefined`,()=>n.assign((0, I._)`${e}[${t}]`,r));}function Tu(n,e,t,r=$n.Correct){let i=r===$n.Correct?I.operators.EQ:I.operators.NEQ,a;switch(n){case "null":return (0, I._)`${e} ${i} null`;case "array":a=(0, I._)`Array.isArray(${e})`;break;case "object":a=(0, I._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, I._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, I._)`typeof ${e} ${i} ${n}`}return r===$n.Correct?a:(0, I.not)(a);function s(o=I.nil){return (0, I.and)((0, I._)`typeof ${e} == "number"`,o,t?(0, I._)`isFinite(${e})`:I.nil)}}De.checkDataType=Tu;function Iu(n,e,t,r){if(n.length===1)return Tu(n[0],e,t,r);let i,a=(0, Af.toHash)(n);if(a.array&&a.object){let s=(0, I._)`typeof ${e} != "object"`;i=a.null?s:(0, I._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=I.nil;a.number&&delete a.integer;for(let s in a)i=(0, I.and)(i,Tu(s,e,t,r));return i}De.checkDataTypes=Iu;var kC={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, I._)`{type: ${n}}`:(0, I._)`{type: ${e}}`};function ku(n){let e=$C(n);(0, FC.reportError)(e,kC);}De.reportTypeError=ku;function $C(n){let{gen:e,data:t,schema:r}=n,i=(0, Af.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var xf=C(es=>{Object.defineProperty(es,"__esModule",{value:true});es.assignDefaults=void 0;var Rn=T(),RC=j();function VC(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)Of(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>Of(n,a,i.default));}es.assignDefaults=VC;function Of(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, Rn._)`${a}${(0, Rn.getProperty)(e)}`;if(i){(0, RC.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, Rn._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, Rn._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, Rn._)`${o} = ${(0, Rn.stringify)(t)}`);}});var Ze=C(z=>{Object.defineProperty(z,"__esModule",{value:true});z.validateUnion=z.validateArray=z.usePattern=z.callValidateCode=z.schemaProperties=z.allSchemaProperties=z.noPropertyInData=z.propertyInData=z.isOwnProperty=z.hasPropFunc=z.reportMissingProp=z.checkMissingProp=z.checkReportMissingProp=void 0;var te=T(),$u=j(),jt=Je(),qC=j();function jC(n,e){let{gen:t,data:r,it:i}=n;t.if(Vu(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, te._)`${e}`},true),n.error();});}z.checkReportMissingProp=jC;function LC({gen:n,data:e,it:{opts:t}},r,i){return (0, te.or)(...r.map(a=>(0, te.and)(Vu(n,e,a,t.ownProperties),(0, te._)`${i} = ${a}`)))}z.checkMissingProp=LC;function BC(n,e){n.setParams({missingProperty:e},true),n.error();}z.reportMissingProp=BC;function Nf(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, te._)`Object.prototype.hasOwnProperty`})}z.hasPropFunc=Nf;function Ru(n,e,t){return (0, te._)`${Nf(n)}.call(${e}, ${t})`}z.isOwnProperty=Ru;function WC(n,e,t,r){let i=(0, te._)`${e}${(0, te.getProperty)(t)} !== undefined`;return r?(0, te._)`${i} && ${Ru(n,e,t)}`:i}z.propertyInData=WC;function Vu(n,e,t,r){let i=(0, te._)`${e}${(0, te.getProperty)(t)} === undefined`;return r?(0, te.or)(i,(0, te.not)(Ru(n,e,t))):i}z.noPropertyInData=Vu;function Tf(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}z.allSchemaProperties=Tf;function MC(n,e){return Tf(e).filter(t=>!(0, $u.alwaysValidSchema)(n,e[t]))}z.schemaProperties=MC;function GC({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, te._)`${n}, ${e}, ${r}${i}`:e,h=[[jt.default.instancePath,(0, te.strConcat)(jt.default.instancePath,a)],[jt.default.parentData,s.parentData],[jt.default.parentDataProperty,s.parentDataProperty],[jt.default.rootData,jt.default.rootData]];s.opts.dynamicRef&&h.push([jt.default.dynamicAnchors,jt.default.dynamicAnchors]);let f=(0, te._)`${c}, ${t.object(...h)}`;return u!==te.nil?(0, te._)`${o}.call(${u}, ${f})`:(0, te._)`${o}(${f})`}z.callValidateCode=GC;var UC=(0, te._)`new RegExp`;function HC({gen:n,it:{opts:e}},t){let r=e.unicodeRegExp?"u":"",{regExp:i}=e.code,a=i(t,r);return n.scopeValue("pattern",{key:a.toString(),ref:a,code:(0, te._)`${i.code==="new RegExp"?UC:(0, qC.useFunc)(n,i)}(${t}, ${r})`})}z.usePattern=HC;function KC(n){let{gen:e,data:t,keyword:r,it:i}=n,a=e.name("valid");if(i.allErrors){let o=e.let("valid",true);return s(()=>e.assign(o,false)),o}return e.var(a,true),s(()=>e.break()),a;function s(o){let u=e.const("len",(0, te._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:$u.Type.Num},a),e.if((0, te.not)(a),o);});}}z.validateArray=KC;function zC(n){let{gen:e,schema:t,keyword:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(u=>(0, $u.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=e.let("valid",false),o=e.name("_valid");e.block(()=>t.forEach((u,l)=>{let c=n.subschema({keyword:r,schemaProp:l,compositeRule:true},o);e.assign(s,(0, te._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, te.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}z.validateUnion=zC;});var $f=C(ft=>{Object.defineProperty(ft,"__esModule",{value:true});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Ie=T(),ln=Je(),JC=Ze(),ZC=Tr();function XC(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=kf(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:Ie.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}ft.macroKeywordCode=XC;function QC(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;ev(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=kf(r,i,l),h=r.let("valid");n.block$data(h,f),n.ok((t=e.valid)!==null&&t!==void 0?t:h);function f(){if(e.errors===false)p(),e.modifying&&If(n),v(()=>n.error());else {let _=e.async?m():g();e.modifying&&If(n),v(()=>YC(n,_));}}function m(){let _=r.let("ruleErrs",null);return r.try(()=>p((0, Ie._)`await `),b=>r.assign(h,false).if((0, Ie._)`${b} instanceof ${u.ValidationError}`,()=>r.assign(_,(0, Ie._)`${b}.errors`),()=>r.throw(b))),_}function g(){let _=(0, Ie._)`${c}.errors`;return r.assign(_,null),p(Ie.nil),_}function p(_=e.async?(0, Ie._)`await `:Ie.nil){let b=u.opts.passContext?ln.default.this:ln.default.self,d=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, Ie._)`${_}${(0, JC.callValidateCode)(n,c,b,d)}`,e.modifying);}function v(_){var b;r.if((0, Ie.not)((b=e.valid)!==null&&b!==void 0?b:h),_);}}ft.funcKeywordCode=QC;function If(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, Ie._)`${r.parentData}[${r.parentDataProperty}]`));}function YC(n,e){let{gen:t}=n;t.if((0, Ie._)`Array.isArray(${e})`,()=>{t.assign(ln.default.vErrors,(0, Ie._)`${ln.default.vErrors} === null ? ${e} : ${ln.default.vErrors}.concat(${e})`).assign(ln.default.errors,(0, Ie._)`${ln.default.vErrors}.length`),(0, ZC.extendErrors)(n);},()=>n.error());}function ev({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function kf(n,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return n.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0, Ie.stringify)(t)})}function tv(n,e,t=false){return !e.length||e.some(r=>r==="array"?Array.isArray(n):r==="object"?n&&typeof n=="object"&&!Array.isArray(n):typeof n==r||t&&typeof n>"u")}ft.validSchemaType=tv;function nv({schema:n,opts:e,self:t,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(o=>!Object.prototype.hasOwnProperty.call(n,o)))throw new Error(`parent schema must have dependencies of ${a}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(n[a])){let u=`keyword "${a}" value is invalid at path "${r}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(u);else throw new Error(u)}}ft.validateKeywordUsage=nv;});var Vf=C(Lt=>{Object.defineProperty(Lt,"__esModule",{value:true});Lt.extendSubschemaMode=Lt.extendSubschemaData=Lt.getSubschema=void 0;var pt=T(),Rf=j();function rv(n,{keyword:e,schemaProp:t,schema:r,schemaPath:i,errSchemaPath:a,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let o=n.schema[e];return t===void 0?{schema:o,schemaPath:(0, pt._)`${n.schemaPath}${(0, pt.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, pt._)`${n.schemaPath}${(0, pt.getProperty)(e)}${(0, pt.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, Rf.escapeFragment)(t)}`}}if(r!==void 0){if(i===void 0||a===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:r,schemaPath:i,topSchemaRef:s,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Lt.getSubschema=rv;function iv(n,e,{dataProp:t,dataPropType:r,data:i,dataTypes:a,propertyName:s}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:o}=e;if(t!==void 0){let{errorPath:l,dataPathArr:c,opts:h}=e,f=o.let("data",(0, pt._)`${e.data}${(0, pt.getProperty)(t)}`,true);u(f),n.errorPath=(0, pt.str)`${l}${(0, Rf.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, pt._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof pt.Name?i:o.let("data",i,true);u(l),s!==void 0&&(n.propertyName=s);}a&&(n.dataTypes=a);function u(l){n.data=l,n.dataLevel=e.dataLevel+1,n.dataTypes=[],e.definedProperties=new Set,n.parentData=e.data,n.dataNames=[...e.dataNames,l];}}Lt.extendSubschemaData=iv;function sv(n,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(n.compositeRule=r),i!==void 0&&(n.createErrors=i),a!==void 0&&(n.allErrors=a),n.jtdDiscriminator=e,n.jtdMetadata=t;}Lt.extendSubschemaMode=sv;});var qu=C((yO,qf)=>{qf.exports=function n(e,t){if(e===t)return true;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return false;var r,i,a;if(Array.isArray(e)){if(r=e.length,r!=t.length)return false;for(i=r;i--!==0;)if(!n(e[i],t[i]))return false;return true}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(a=Object.keys(e),r=a.length,r!==Object.keys(t).length)return false;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[i]))return false;for(i=r;i--!==0;){var s=a[i];if(!n(e[s],t[s]))return false}return true}return e!==e&&t!==t};});var Lf=C((CO,jf)=>{var Bt=jf.exports=function(n,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var r=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};ts(e,r,i,n,"",n);};Bt.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};Bt.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};Bt.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};Bt.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function ts(n,e,t,r,i,a,s,o,u,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,i,a,s,o,u,l);for(var c in r){var h=r[c];if(Array.isArray(h)){if(c in Bt.arrayKeywords)for(var f=0;f<h.length;f++)ts(n,e,t,h[f],i+"/"+c+"/"+f,a,i,c,r,f);}else if(c in Bt.propsKeywords){if(h&&typeof h=="object")for(var m in h)ts(n,e,t,h[m],i+"/"+c+"/"+av(m),a,i,c,r,m);}else (c in Bt.keywords||n.allKeys&&!(c in Bt.skipKeywords))&&ts(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function av(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var kr=C(qe=>{Object.defineProperty(qe,"__esModule",{value:true});qe.getSchemaRefs=qe.resolveUrl=qe.normalizeId=qe._getFullPath=qe.getFullPath=qe.inlineRef=void 0;var ov=j(),uv=qu(),lv=Lf(),cv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function hv(n,e=true){return typeof n=="boolean"?true:e===true?!ju(n):e?Bf(n)<=e:false}qe.inlineRef=hv;var dv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ju(n){for(let e in n){if(dv.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(ju)||typeof t=="object"&&ju(t))return true}return false}function Bf(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!cv.has(t)&&(typeof n[t]=="object"&&(0, ov.eachItem)(n[t],r=>e+=Bf(r)),e===1/0))return 1/0}return e}function Wf(n,e="",t){t!==false&&(e=Vn(e));let r=n.parse(e);return Mf(n,r)}qe.getFullPath=Wf;function Mf(n,e){return n.serialize(e).split("#")[0]+"#"}qe._getFullPath=Mf;var fv=/#\/?$/;function Vn(n){return n?n.replace(fv,""):""}qe.normalizeId=Vn;function pv(n,e,t){return t=Vn(t),n.resolve(e,t)}qe.resolveUrl=pv;var mv=/^[a-z_][-a-z0-9._]*$/i;function gv(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=Vn(n[t]||e),a={"":i},s=Wf(r,i,false),o={},u=new Set;return lv(n,{allKeys:true},(h,f,m,g)=>{if(g===void 0)return;let p=s+f,v=a[g];typeof h[t]=="string"&&(v=_.call(this,h[t])),b.call(this,h.$anchor),b.call(this,h.$dynamicAnchor),a[f]=v;function _(d){let E=this.opts.uriResolver.resolve;if(d=Vn(v?E(v,d):d),u.has(d))throw c(d);u.add(d);let y=this.refs[d];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?l(h,y.schema,d):d!==Vn(p)&&(d[0]==="#"?(l(h,o[d],d),o[d]=h):this.refs[d]=p),d}function b(d){if(typeof d=="string"){if(!mv.test(d))throw new Error(`invalid anchor "${d}"`);_.call(this,`#${d}`);}}}),o;function l(h,f,m){if(f!==void 0&&!uv(h,f))throw c(m)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}qe.getSchemaRefs=gv;});var qn=C(Wt=>{Object.defineProperty(Wt,"__esModule",{value:true});Wt.getData=Wt.KeywordCxt=Wt.validateFunctionCode=void 0;var zf=Sf(),Gf=Ir(),Bu=Nu(),ns=Ir(),yv=xf(),Rr=$f(),Lu=Vf(),A=T(),x=Je(),Cv=kr(),Nt=j(),$r=Tr();function vv(n){if(Xf(n)&&(Qf(n),Zf(n))){bv(n);return}Jf(n,()=>(0, zf.topBoolOrEmptySchema)(n));}Wt.validateFunctionCode=vv;function Jf({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, A._)`${x.default.data}, ${x.default.valCxt}`,r.$async,()=>{n.code((0, A._)`"use strict"; ${Uf(t,i)}`),Ev(n,i),n.code(a);}):n.func(e,(0, A._)`${x.default.data}, ${_v(i)}`,r.$async,()=>n.code(Uf(t,i)).code(a));}function _v(n){return (0, A._)`{${x.default.instancePath}="", ${x.default.parentData}, ${x.default.parentDataProperty}, ${x.default.rootData}=${x.default.data}${n.dynamicRef?(0, A._)`, ${x.default.dynamicAnchors}={}`:A.nil}}={}`}function Ev(n,e){n.if(x.default.valCxt,()=>{n.var(x.default.instancePath,(0, A._)`${x.default.valCxt}.${x.default.instancePath}`),n.var(x.default.parentData,(0, A._)`${x.default.valCxt}.${x.default.parentData}`),n.var(x.default.parentDataProperty,(0, A._)`${x.default.valCxt}.${x.default.parentDataProperty}`),n.var(x.default.rootData,(0, A._)`${x.default.valCxt}.${x.default.rootData}`),e.dynamicRef&&n.var(x.default.dynamicAnchors,(0, A._)`${x.default.valCxt}.${x.default.dynamicAnchors}`);},()=>{n.var(x.default.instancePath,(0, A._)`""`),n.var(x.default.parentData,(0, A._)`undefined`),n.var(x.default.parentDataProperty,(0, A._)`undefined`),n.var(x.default.rootData,x.default.data),e.dynamicRef&&n.var(x.default.dynamicAnchors,(0, A._)`{}`);});}function bv(n){let{schema:e,opts:t,gen:r}=n;Jf(n,()=>{t.$comment&&e.$comment&&ep(n),Pv(n),r.let(x.default.vErrors,null),r.let(x.default.errors,0),t.unevaluated&&Sv(n),Yf(n),xv(n);});}function Sv(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, A._)`${t}.evaluated`),e.if((0, A._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, A._)`${n.evaluated}.props`,(0, A._)`undefined`)),e.if((0, A._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, A._)`${n.evaluated}.items`,(0, A._)`undefined`));}function Uf(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, A._)`/*# sourceURL=${t} */`:A.nil}function Dv(n,e){if(Xf(n)&&(Qf(n),Zf(n))){wv(n,e);return}(0, zf.boolOrEmptySchema)(n,e);}function Zf({schema:n,self:e}){if(typeof n=="boolean")return !n;for(let t in n)if(e.RULES.all[t])return true;return false}function Xf(n){return typeof n.schema!="boolean"}function wv(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&ep(n),Fv(n),Ov(n);let a=r.const("_errs",x.default.errors);Yf(n,a),r.var(e,(0, A._)`${a} === ${x.default.errors}`);}function Qf(n){(0, Nt.checkUnknownRules)(n),Av(n);}function Yf(n,e){if(n.opts.jtd)return Hf(n,[],false,e);let t=(0, Gf.getSchemaTypes)(n.schema),r=(0, Gf.coerceAndCheckDataType)(n,t);Hf(n,t,!r,e);}function Av(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, Nt.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function Pv(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, Nt.checkStrictMode)(n,"default is ignored in the schema root");}function Fv(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, Cv.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function Ov(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function ep({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, A._)`${x.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, A.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, A._)`${x.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function xv(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, A._)`${x.default.errors} === 0`,()=>e.return(x.default.data),()=>e.throw((0, A._)`new ${i}(${x.default.vErrors})`)):(e.assign((0, A._)`${r}.errors`,x.default.vErrors),a.unevaluated&&Nv(n),e.return((0, A._)`${x.default.errors} === 0`));}function Nv({gen:n,evaluated:e,props:t,items:r}){t instanceof A.Name&&n.assign((0, A._)`${e}.props`,t),r instanceof A.Name&&n.assign((0, A._)`${e}.items`,r);}function Hf(n,e,t,r){let{gen:i,schema:a,data:s,allErrors:o,opts:u,self:l}=n,{RULES:c}=l;if(a.$ref&&(u.ignoreKeywordsWithRef||!(0, Nt.schemaHasRulesButRef)(a,c))){i.block(()=>np(n,"$ref",c.all.$ref.definition));return}u.jtd||Tv(n,e),i.block(()=>{for(let f of c.rules)h(f);h(c.post);});function h(f){(0, Bu.shouldUseGroup)(a,f)&&(f.type?(i.if((0, ns.checkDataType)(f.type,s,u.strictNumbers)),Kf(n,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0, ns.reportTypeError)(n)),i.endIf()):Kf(n,f),o||i.if((0, A._)`${x.default.errors} === ${r||0}`));}}function Kf(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, yv.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, Bu.shouldUseRule)(r,a)&&np(n,a.keyword,a.definition,e.type);});}function Tv(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(Iv(n,e),n.opts.allowUnionTypes||kv(n,e),$v(n,n.dataTypes));}function Iv(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{tp(n.dataTypes,t)||Wu(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),Vv(n,e);}}function kv(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Wu(n,"use allowUnionTypes to allow union type keyword");}function $v(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, Bu.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>Rv(e,s))&&Wu(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function Rv(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function tp(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function Vv(n,e){let t=[];for(let r of n.dataTypes)tp(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function Wu(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, Nt.checkStrictMode)(n,e,n.opts.strictTypes);}var rs=class{constructor(e,t,r){if((0, Rr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, Nt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",rp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, Rr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==false)&&(this.errsCount=e.gen.const("_errs",x.default.errors));}result(e,t,r){this.failResult((0, A.not)(e),t,r);}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(e,t){this.failResult((0, A.not)(e),void 0,t);}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(false);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:t}=this;this.fail((0, A._)`${t} !== undefined && (${(0, A.or)(this.invalid$data(),e)})`);}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r);}_error(e,t){(e?$r.reportExtraError:$r.reportError)(this,this.def.error,t);}$dataError(){(0, $r.reportError)(this,this.def.$dataError||$r.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, $r.resetErrorsCount)(this.gen,this.errsCount);}ok(e){this.allErrors||this.gen.if(e);}setParams(e,t){t?Object.assign(this.params,e):this.params=e;}block$data(e,t,r=A.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=A.nil,t=A.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, A.or)((0, A._)`${i} === undefined`,t)),e!==A.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, A.or)(s(),o());function s(){if(r.length){if(!(t instanceof A.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, A._)`${(0, ns.checkDataTypes)(u,t,a.opts.strictNumbers,ns.DataType.Wrong)}`}return A.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, A._)`!${u}(${t})`}return A.nil}}subschema(e,t){let r=(0, Lu.getSubschema)(this.it,e);(0, Lu.extendSubschemaData)(r,this.it,e),(0, Lu.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return Dv(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=Nt.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=Nt.mergeEvaluated.items(i,e.items,r.items,t)));}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==true||r.items!==true))return i.if(t,()=>this.mergeEvaluated(e,A.Name)),true}};Wt.KeywordCxt=rs;function np(n,e,t,r){let i=new rs(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, Rr.funcKeywordCode)(i,t):"macro"in t?(0, Rr.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, Rr.funcKeywordCode)(i,t);}var qv=/^\/(?:[^~]|~0|~1)*$/,jv=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function rp(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return x.default.rootData;if(n[0]==="/"){if(!qv.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=x.default.rootData;}else {let l=jv.exec(n);if(!l)throw new Error(`Invalid JSON-pointer: ${n}`);let c=+l[1];if(i=l[2],i==="#"){if(c>=e)throw new Error(u("property/index",c));return r[e-c]}if(c>e)throw new Error(u("data",c));if(a=t[e-c],!i)return a}let s=a,o=i.split("/");for(let l of o)l&&(a=(0, A._)`${a}${(0, A.getProperty)((0, Nt.unescapeJsonPointer)(l))}`,s=(0, A._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}Wt.getData=rp;});var Vr=C(Gu=>{Object.defineProperty(Gu,"__esModule",{value:true});var Mu=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};Gu.default=Mu;});var jn=C(Ku=>{Object.defineProperty(Ku,"__esModule",{value:true});var Uu=kr(),Hu=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Uu.resolveUrl)(e,t,r),this.missingSchema=(0, Uu.normalizeId)((0, Uu.getFullPath)(e,this.missingRef));}};Ku.default=Hu;});var qr=C(Xe=>{Object.defineProperty(Xe,"__esModule",{value:true});Xe.resolveSchema=Xe.getCompilingSchema=Xe.resolveRef=Xe.compileSchema=Xe.SchemaEnv=void 0;var ut=T(),Lv=Vr(),cn=Je(),lt=kr(),ip=j(),Bv=qn(),Ln=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0, lt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};Xe.SchemaEnv=Ln;function Ju(n){let e=sp.call(this,n);if(e)return e;let t=(0, lt.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new ut.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:Lv.default,code:(0, ut._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:cn.default.data,parentData:cn.default.parentData,parentDataProperty:cn.default.parentDataProperty,dataNames:[cn.default.data],dataPathArr:[ut.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, ut.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:ut.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, ut._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,Bv.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs(cn.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let m=new Function(`${cn.default.self}`,`${cn.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:m}),m.errors=null,m.schema=n.schema,m.schemaEnv=n,n.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:g,items:p}=l;m.evaluated={props:g instanceof ut.Name?void 0:g,items:p instanceof ut.Name?void 0:p,dynamicProps:g instanceof ut.Name,dynamicItems:p instanceof ut.Name},m.source&&(m.source.evaluated=(0,ut.stringify)(m.evaluated));}return n.validate=m,n}catch(h){throw delete n.validate,delete n.validateName,c&&this.logger.error("Error compiling schema, function code:",c),h}finally{this._compilations.delete(n);}}Xe.compileSchema=Ju;function Wv(n,e,t){var r;t=(0, lt.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=Uv.call(this,n,t);if(a===void 0){let s=(r=n.localRefs)===null||r===void 0?void 0:r[t],{schemaId:o}=this.opts;s&&(a=new Ln({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=Mv.call(this,a)}Xe.resolveRef=Wv;function Mv(n){return (0, lt.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:Ju.call(this,n)}function sp(n){for(let e of this._compilations)if(Gv(e,n))return e}Xe.getCompilingSchema=sp;function Gv(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function Uv(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||is.call(this,n,e)}function is(n,e){let t=this.opts.uriResolver.parse(e),r=(0, lt._getFullPath)(this.opts.uriResolver,t),i=(0, lt.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return zu.call(this,t,n);let a=(0, lt.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=is.call(this,n,s);return typeof o?.schema!="object"?void 0:zu.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||Ju.call(this,s),a===(0, lt.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, lt.resolveUrl)(this.opts.uriResolver,i,l)),new Ln({schema:o,schemaId:u,root:n,baseId:i})}return zu.call(this,t,s)}}Xe.resolveSchema=is;var Hv=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zu(n,{baseId:e,schema:t,root:r}){var i;if(((i=n.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let o of n.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let u=t[(0, ip.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!Hv.has(o)&&l&&(e=(0, lt.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, ip.schemaHasRulesButRef)(t,this.RULES)){let o=(0, lt.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=is.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new Ln({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var ap=C((DO,Kv)=>{Kv.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:false};});var tl=C((wO,fp)=>{var zv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xu=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),Jv=RegExp.prototype.test.bind(/^\d*$/u),hn=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Qu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),up=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Yu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Zv=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),je=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)je[e]="%"+n[e>>4]+n[e&15];}function we(n){return n<2048?je[192|n>>6]+je[128|n&63]:n<65536?je[224|n>>12]+je[128|n>>6&63]+je[128|n&63]:je[240|n>>18]+je[128|n>>12&63]+je[128|n>>6&63]+je[128|n&63]}function Xv(n){let e="",t=0,r=0;for(r=0;r<n.length;r++)if(t=n[r].charCodeAt(0),t!==48){if(!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];break}for(r+=1;r<n.length;r++){if(t=n[r].charCodeAt(0),!(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return "";e+=n[r];}return e}var Qv=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),Yv=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),e_=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),t_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function n_(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!e_(n[e])){if(n[e]==="%"&&e+2<n.length&&hn(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function op(n){let e=-1,t=0,r=-1,i=0;for(let o=0;o<n.length;o++)n[o]==="0"?(r===-1&&(r=o),i++,i>t&&(t=i,e=r)):(r=-1,i=0);if(t<2)return n.join(":");let a=n.slice(0,e).join(":"),s=n.slice(e+t).join(":");return a+"::"+s}function r_(n){let e=n.indexOf("::");if(e!==-1&&n.indexOf("::",e+1)!==-1)return;let t=e===-1?n.split(":"):n.slice(0,e).split(":"),r=e===-1?[]:n.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),r.length===1&&r[0]===""&&(r.length=0));let i=t.concat(r),a=0;for(let o=0;o<i.length;o++){let u=i[o];if(u==="")return;if(u.indexOf(".")!==-1){if(o!==i.length-1||e!==-1&&r.length===0||!Xu(u))return;a+=2;continue}if(!Qv(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:op(i);if(a>=8)return;let s=i.slice(0,t.length);for(let o=a;o<8;o++)s.push("0");for(let o=t.length;o<i.length;o++)s.push(i[o]);return op(s)}function Zu(n){let e=n[0]==="["&&n[n.length-1]==="]";if((n[0]==="["||n[n.length-1]==="]")&&!e)return {host:n,isIPV6:false,error:true};let r=e?n.slice(1,-1):n;if(e&&Yv(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(i_(r,":")<2)return {host:n,isIPV6:false,error:e};let i="",a=r.indexOf("%");if(a!==-1){let o=r.slice(a,a+3).toLowerCase()==="%25"?3:1;if(i=r.slice(a+o),!n_(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=r_(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function i_(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function s_(n){let e=n,t=[],r=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){t.push("/");break}else {t.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]==="/")){t.push("/");break}}else if(i===3&&e==="/.."){t.length!==0&&t.pop(),t.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),t.length!==0&&t.pop();continue}}if((r=e.indexOf("/",1))===-1){t.push(e);break}else t.push(e.slice(0,r)),e=e.slice(r);}return t.join("")}var a_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},o_=/[@/?#:]/g,u_=/[@/?#]/g;function lp(n,e){let t=e?u_:o_;return t.lastIndex=0,n.replace(t,r=>a_[r])}function cp(n,e=false){if(n.indexOf("%")===-1)return n;let t="";for(let r=0;r<n.length;r++){if(n[r]==="%"&&r+2<n.length){let i=n.slice(r+1,r+3);if(hn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&Qu(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function l_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(hn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&Qu(s)?e+=s:e+="%"+a,t+=2;continue}}if(up(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=dp(i)?r:je[i];else if(i<55296||i>57343)e+=we(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=we(65536+(i-55296<<10)+(a-56320)),t++):e+=we(65533);}else e+=we(65533);}}return e}function c_(n,e=false){let t="",r=e&&n[0]!=="/";for(let i=0;i<n.length;i++){let a=n[i];if(a==="%"&&i+2<n.length){let s=n.slice(i+1,i+3);if(hn(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),up(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=je[s];else if(s<55296||s>57343)t+=we(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=we(65536+(s-55296<<10)+(o-56320)),i++):t+=we(65533);}else t+=we(65533);}}return t}function el(n,e){let t="";for(let r=0;r<n.length;r++){let i=n[r];if(i==="%"&&r+2<n.length){let a=n.slice(r+1,r+3);if(hn(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=je[a];else if(a<55296||a>57343)t+=we(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=we(65536+(a-55296<<10)+(s-56320)),r++):t+=we(65533);}else t+=we(65533);}}return t}function hp(n){return el(n,Zv)}function h_(n){return el(n,Yu)}function d_(n){return el(n,Yu)}function dp(n){return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===42||n===43||n===45||n===46||n===47||n===64||n===95}function f_(n){let e="";for(let t=0;t<n.length;t++){let r=n[t];if(r==="%"&&t+2<n.length){let i=n.slice(t+1,t+3);if(hn(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));Qu(s)?e+=s:e+="%"+a,t+=2;continue}}if(Yu(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=dp(i)?r:je[i];else if(i<55296||i>57343)e+=we(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=we(65536+(i-55296<<10)+(a-56320)),t++):e+=we(65533);}else e+=we(65533);}}return e}function p_(n){let e="";for(let t=0;t<n.length;t++){if(n[t]==="%"&&t+2<n.length){let r=n.slice(t+1,t+3);if(hn(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function m_(n){let e=[];if(n.userinfo!==void 0&&(e.push(hp(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Xu(t)){let r=Zu(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=cp(t,true),r=Zu(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=lp(t,false);}e.push(t);}if(typeof n.port=="number"||typeof n.port=="string"){let t=String(n.port);if(!Jv(t))throw new TypeError("URI port is malformed.");e.push(":"),e.push(t);}return e.length?e.join(""):void 0}fp.exports={nonSimpleDomain:t_,recomposeAuthority:m_,reescapeHostDelimiters:lp,normalizePercentEncoding:cp,normalizePathEncoding:l_,serializePathEncoding:c_,normalizeQueryFragmentEncoding:f_,encodeUserinfo:hp,encodeQuery:h_,encodeFragment:d_,escapePreservingEscapes:p_,removeDotSegments:s_,isIPv4:Xu,isUUID:zv,normalizeIPv6:Zu,stringArrayToHexStripped:Xv};});var Cp=C((AO,yp)=>{var{isUUID:g_}=tl(),y_=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,C_=["http","https","ws","wss","urn","urn:uuid"];function v_(n){return C_.indexOf(n)!==-1}function nl(n){return n.secure===true?true:n.secure===false?false:n.scheme?n.scheme.length===3&&(n.scheme[0]==="w"||n.scheme[0]==="W")&&(n.scheme[1]==="s"||n.scheme[1]==="S")&&(n.scheme[2]==="s"||n.scheme[2]==="S"):false}function pp(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function mp(n){let e=String(n.scheme).toLowerCase()==="https";return (n.port===(e?443:80)||n.port==="")&&(n.port=void 0),n.path||(n.path="/"),n}function __(n){return n.secure=nl(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function E_(n){if((n.port===(nl(n)?443:80)||n.port==="")&&(n.port=void 0),typeof n.secure=="boolean"&&(n.scheme=n.secure?"wss":"ws",n.secure=void 0),n.resourceName){let e=n.resourceName.indexOf("?"),t=e===-1?n.resourceName:n.resourceName.slice(0,e);n.path=t&&t!=="/"?t:void 0,n.query=e===-1?void 0:n.resourceName.slice(e+1),n.resourceName=void 0;}return n.fragment=void 0,n}function b_(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(y_);if(t&&t[0]===n.path){let r=e.scheme||n.scheme||"urn";n.nid=t[1].toLowerCase(),n.nss=t[2];let i=`${r}:${e.nid||n.nid}`,a=rl(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function S_(n,e){if(n.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||n.scheme||"urn",r=n.nid.toLowerCase(),i=`${t}:${e.nid||r}`,a=rl(i);a&&(n=a.serialize(n,e));let s=n,o=n.nss;return s.path=`${r||e.nid}:${o}`,e.skipEscape=true,s}function D_(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!g_(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function w_(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var gp={scheme:"http",domainHost:true,parse:pp,serialize:mp},A_={scheme:"https",domainHost:gp.domainHost,parse:pp,serialize:mp},ss={scheme:"ws",domainHost:true,parse:__,serialize:E_},P_={scheme:"wss",domainHost:ss.domainHost,parse:ss.parse,serialize:ss.serialize},F_={scheme:"urn",parse:b_,serialize:S_,skipNormalize:true},O_={scheme:"urn:uuid",parse:D_,serialize:w_,skipNormalize:true},as={http:gp,https:A_,ws:ss,wss:P_,urn:F_,"urn:uuid":O_};Object.setPrototypeOf(as,null);function rl(n){return n&&(as[n]||as[n.toLowerCase()])||void 0}yp.exports={wsIsSecure:nl,SCHEMES:as,isValidSchemeName:v_,getSchemeHandler:rl};});var Np=C((PO,ls)=>{var{normalizeIPv6:Sp,removeDotSegments:Lr,recomposeAuthority:x_,normalizePercentEncoding:il,normalizePathEncoding:N_,serializePathEncoding:vp,normalizeQueryFragmentEncoding:_p,encodeQuery:T_,encodeFragment:I_,reescapeHostDelimiters:k_,isIPv4:Dp,nonSimpleDomain:$_}=tl(),{SCHEMES:wp,getSchemeHandler:sl}=Cp(),Ap=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Pp="URI scheme is malformed.";function Ep(n){let e=unescape(String(n));if(!Ap.test(e))throw new TypeError(Pp);return e}function R_(n,e){return typeof n=="string"?n=G_(n,e):typeof n=="object"&&(n=us(dn(n,e),e)),n}function V_(n,e,t){let r=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:u,malformedScheme:l}=os(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:f,malformedSchemeSpecific:m,malformedHost:g,malformedScheme:p}=os(e,r);if(a||h||s||f||o||m||u||g||l||p)throw new Error(i.error||c.error||"URI is malformed.");let v=Fp(i,c,r,true),_=sl(t&&t.scheme||v.scheme),b=v.host,d=b!==void 0&&b!==""&&(Dp(b)||Sp(b).isIPV6);Op(v,t||{},_,d);let E=b&&b.indexOf("%")!==-1&&!/\P{ASCII}/u.test(b);if(v.error&&!E)throw new Error(v.error);return r.skipEscape=true,dn(v,r)}function Fp(n,e,t,r){let i={};return r||(n=us(dn(n,t),t),e=us(dn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Lr(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=Lr(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Lr(e.path):((n.userinfo!==void 0||n.host!==void 0||n.port!==void 0)&&!n.path?i.path="/"+e.path:n.path?i.path=n.path.slice(0,n.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Lr(i.path)),i.query=e.query):(i.path=n.path,e.query!==void 0?i.query=e.query:i.query=n.query),i.userinfo=n.userinfo,i.host=n.host,i.port=n.port),i.scheme=n.scheme),i.fragment=e.fragment,i}function q_(n,e,t){let r=bp(n,t),i=bp(e,t);return r!==void 0&&i!==void 0&&r===i}function dn(n,e){let t={host:n.host,scheme:n.scheme,userinfo:n.userinfo,port:n.port,path:n.path,query:n.query,nid:n.nid,nss:n.nss,uuid:n.uuid,fragment:n.fragment,reference:n.reference,resourceName:n.resourceName,secure:n.secure,error:""},r=Object.assign({},e),i=[];t.scheme&&(t.scheme=Ep(t.scheme));let a=sl(r.scheme||t.scheme);a&&a.serialize&&a.serialize(t,r);let s=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,o=!r.skipEscape&&t.scheme===void 0&&!s;t.path!==void 0&&(r.skipEscape?t.path=il(t.path):t.path=vp(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=Ep(t.scheme),i.push(t.scheme,":"));let u=x_(t);if(u!==void 0&&(r.reference!=="suffix"&&i.push("//"),i.push(u),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!r.absolutePath&&(!a||!a.absolutePath)&&(l=Lr(l)),o&&(l=vp(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",T_(t.query)),t.fragment!==void 0&&i.push("#",I_(t.fragment)),i.join("")}var j_=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,L_=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,B_=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function W_(n,e){if(e[2]!==void 0&&n.path&&n.path[0]!=="/")return 'URI path must start with "/" when authority is present.';if(typeof n.port=="number"&&(n.port<0||n.port>65535))return "URI port is malformed."}function jr(n){if(n===void 0)return false;let e=n.indexOf("%");for(;e!==-1;){if(e+2>=n.length||!/^[\da-f]{2}$/iu.test(n.slice(e+1,e+3)))return true;e=n.indexOf("%",e+3);}return false}function al(n){return n[0]==="["&&n[n.length-1]==="]"}function M_(n){let e=n[4];return jr(n[3])||e!==void 0&&!al(e)&&jr(e)||jr(n[6])||jr(n[7])||jr(n[8])}function Op(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&!al(n.host)&&(e.domainHost||t&&t.domainHost)&&r===false&&$_(n.host))try{n.host=new URL("http://"+n.host).hostname;}catch(i){return n.error=n.error||"Host's domain name can not be converted to ASCII: "+i,true}return false}function os(n,e){let t=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=false,a=false,s=false,o=false,u=false,l=false,c=false;t.reference==="suffix"&&(t.scheme?n=t.scheme+":"+n:n="//"+n);let h=n.match(L_);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let f=n.match(B_);if(f!==null){let g=f[1],p=g.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):g.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let m=n.match(j_);if(m){if(r.scheme=m[1],r.userinfo=m[3],r.host=m[4],r.port=parseInt(m[5],10),r.path=m[6]||"",r.query=m[7],r.fragment=m[8],r.scheme!==void 0){let v=unescape(r.scheme);Ap.test(v)?r.scheme=v.toLowerCase():(r.error=r.error||Pp,l=true);}a=M_(m),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=m[5]);let g=W_(r,m);if(g!==void 0&&(r.error=r.error||g,i=true),r.host)if(Dp(r.host)===false){let _=al(r.host),b=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,d=Sp(r.host);c=d.isIPV6||d.isIPVFuture===true,u=b&&(!_||d.error===true),r.host=c?d.host:d.host.toLowerCase(),u&&(r.error=r.error||"URI host is malformed.",i=true);}else c=true;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");let p=sl(t.scheme||r.scheme);if(u||(o=Op(r,t,p,c)),n.indexOf("%")!==-1&&r.host!==void 0&&!u){let v=c?r.host:il(r.host,true);c||(v=il(v.toLowerCase())),r.host=k_(v,c);}(!p||p&&!p.skipNormalize)&&(r.path&&(r.path=N_(r.path)),r.query&&(r.query=_p(r.query)),r.fragment&&(r.fragment=_p(r.fragment))),p&&p.parse&&(p.parse(r,t),p===wp.urn&&r.nid===void 0&&(s=true));}else r.error=r.error||"URI can not be parsed.";return {parsed:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:l}}function us(n,e){return os(n,e).parsed}function G_(n,e){return xp(n,e).normalized}function xp(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=os(n,e);return {normalized:r||i||a||s||o?n:dn(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function bp(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:dn(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=xp(t,e);return i||a||s||o||u?void 0:r}var ol={SCHEMES:wp,normalize:R_,resolve:V_,resolveComponent:Fp,equal:q_,serialize:dn,parse:us};ls.exports=ol;ls.exports.default=ol;ls.exports.fastUri=ol;});var Ip=C(ul=>{Object.defineProperty(ul,"__esModule",{value:true});var Tp=Np();Tp.code='require("ajv/dist/runtime/uri").default';ul.default=Tp;});var hl=C(Ce=>{Object.defineProperty(Ce,"__esModule",{value:true});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var U_=qn();Object.defineProperty(Ce,"KeywordCxt",{enumerable:true,get:function(){return U_.KeywordCxt}});var Bn=T();Object.defineProperty(Ce,"_",{enumerable:true,get:function(){return Bn._}});Object.defineProperty(Ce,"str",{enumerable:true,get:function(){return Bn.str}});Object.defineProperty(Ce,"stringify",{enumerable:true,get:function(){return Bn.stringify}});Object.defineProperty(Ce,"nil",{enumerable:true,get:function(){return Bn.nil}});Object.defineProperty(Ce,"Name",{enumerable:true,get:function(){return Bn.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:true,get:function(){return Bn.CodeGen}});var H_=Vr(),qp=jn(),K_=xu(),Br=qr(),z_=T(),Wr=kr(),cs=Ir(),cl=j(),kp=ap(),J_=Ip(),jp=(n,e)=>new RegExp(n,e);jp.code="new RegExp";var Z_=["removeAdditional","useDefaults","coerceTypes"],X_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Q_={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."},Y_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$p=200;function eE(n){var e,t,r,i,a,s,o,u,l,c,h,f,m,g,p,v,_,b,d,E,y,D,w,F,$;let X=n.strict,Ee=(e=n.code)===null||e===void 0?void 0:e.optimize,_r=Ee===true||Ee===void 0?1:Ee||0,Er=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:jp,On=(i=n.uriResolver)!==null&&i!==void 0?i:J_.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:X)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:X)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:X)!==null&&c!==void 0?c:"log",strictTuples:(f=(h=n.strictTuples)!==null&&h!==void 0?h:X)!==null&&f!==void 0?f:"log",strictRequired:(g=(m=n.strictRequired)!==null&&m!==void 0?m:X)!==null&&g!==void 0?g:false,code:n.code?{...n.code,optimize:_r,regExp:Er}:{optimize:_r,regExp:Er},loopRequired:(p=n.loopRequired)!==null&&p!==void 0?p:$p,loopEnum:(v=n.loopEnum)!==null&&v!==void 0?v:$p,meta:(_=n.meta)!==null&&_!==void 0?_:true,messages:(b=n.messages)!==null&&b!==void 0?b:true,inlineRefs:(d=n.inlineRefs)!==null&&d!==void 0?d:true,schemaId:(E=n.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(y=n.addUsedSchema)!==null&&y!==void 0?y:true,validateSchema:(D=n.validateSchema)!==null&&D!==void 0?D:true,validateFormats:(w=n.validateFormats)!==null&&w!==void 0?w:true,unicodeRegExp:(F=n.unicodeRegExp)!==null&&F!==void 0?F:true,int32range:($=n.int32range)!==null&&$!==void 0?$:true,uriResolver:On}}var Mr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...eE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new z_.ValueScope({scope:{},prefixes:X_,es5:t,lines:r}),this.logger=aE(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, K_.getRules)(),Rp.call(this,Q_,e,"NOT SUPPORTED"),Rp.call(this,Y_,e,"DEPRECATED","warn"),this._metaOpts=iE.call(this),e.formats&&nE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&rE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),tE.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=kp;r==="id"&&(i={...kp},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[r],false);}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);return "$async"in r||(this.errors=r.errors),i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(c,h){await a.call(this,c.$schema);let f=this._addSchema(c,h);return f.validate||s.call(this,f)}async function a(c){c&&!this.getSchema(c)&&await i.call(this,{$ref:c},true);}async function s(c){try{return this._compileSchemaEnv(c)}catch(h){if(!(h instanceof qp.default))throw h;return o.call(this,h),await u.call(this,h.missingSchema),s.call(this,c)}}function o({missingSchema:c,missingRef:h}){if(this.refs[c])throw new Error(`AnySchema ${c} is loaded but ${h} cannot be resolved`)}async function u(c){let h=await l.call(this,c);this.refs[c]||await a.call(this,h.$schema),this.refs[c]||this.addSchema(h,c,t);}async function l(c){let h=this._loading[c];if(h)return h;try{return await(this._loading[c]=r(c))}finally{delete this._loading[c];}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let a;if(typeof e=="object"){let{schemaId:s}=this.opts;if(a=e[s],a!==void 0&&typeof a!="string")throw new Error(`schema ${s} must be string`)}return t=(0, Wr.normalizeId)(t||a),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,true),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,true,r),this}validateSchema(e,t){if(typeof e=="boolean")return true;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,true;let i=this.validate(r,e);if(!i&&t){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(e){let t;for(;typeof(t=Vp.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new Br.SchemaEnv({schema:{},schemaId:r});if(t=Br.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t;}return t.validate||this._compileSchemaEnv(t)}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 t=Vp.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case "object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0, Wr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string")r=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(uE.call(this,r,t),!t)return (0, cl.eachItem)(r,a=>ll.call(this,a)),this;cE.call(this,t);let i={...t,type:(0, cs.getJSONTypes)(t.type),schemaType:(0, cs.getJSONTypes)(t.schemaType)};return (0, cl.eachItem)(r,i.type.length===0?a=>ll.call(this,a,i):a=>i.type.forEach(s=>ll.call(this,a,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex(a=>a.keyword===e);i>=0&&r.rules.splice(i,1);}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return !e||e.length===0?"No errors":e.map(i=>`${r}${i.instancePath} ${i.message}`).reduce((i,a)=>i+t+a)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let a=i.split("/").slice(1),s=e;for(let o of a)s=s[o];for(let o in r){let u=r[o];if(typeof u!="object")continue;let{$data:l}=u.definition,c=s[o];l&&c&&(s[o]=Lp(c));}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];(!t||t.test(r))&&(typeof i=="string"?delete e[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[r]));}}_addSchema(e,t,r,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];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 u=this._cache.get(e);if(u!==void 0)return u;r=(0, Wr.normalizeId)(s||r);let l=Wr.getSchemaRefs.call(this,e,r);return u=new Br.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(u.schema,u),a&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=u),i&&this.validateSchema(e,true),u}_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):Br.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Br.compileSchema.call(this,e);}finally{this.opts=t;}}};Mr.ValidationError=H_.default;Mr.MissingRefError=qp.default;Ce.default=Mr;function Rp(n,e,t,r="error"){for(let i in n){let a=i;a in e&&this.logger[r](`${t}: option ${i}. ${n[a]}`);}}function Vp(n){return n=(0, Wr.normalizeId)(n),this.schemas[n]||this.refs[n]}function tE(){let n=this.opts.schemas;if(n)if(Array.isArray(n))this.addSchema(n);else for(let e in n)this.addSchema(n[e],e);}function nE(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function rE(n){if(Array.isArray(n)){this.addVocabulary(n);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in n){let t=n[e];t.keyword||(t.keyword=e),this.addKeyword(t);}}function iE(){let n={...this.opts};for(let e of Z_)delete n[e];return n}var sE={log(){},warn(){},error(){}};function aE(n){if(n===false)return sE;if(n===void 0)return console;if(n.log&&n.warn&&n.error)return n;throw new Error("logger must implement log, warn and error methods")}var oE=/^[a-z_$][a-z0-9_$:-]*$/i;function uE(n,e){let{RULES:t}=this;if((0, cl.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!oE.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ll(n,e,t){var r;let i=e?.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,s=i?a.post:a.rules.find(({type:u})=>u===t);if(s||(s={type:t,rules:[]},a.rules.push(s)),a.keywords[n]=true,!e)return;let o={keyword:n,definition:{...e,type:(0, cs.getJSONTypes)(e.type),schemaType:(0, cs.getJSONTypes)(e.schemaType)}};e.before?lE.call(this,s,o,e.before):s.rules.push(o),a.all[n]=o,(r=e.implements)===null||r===void 0||r.forEach(u=>this.addKeyword(u));}function lE(n,e,t){let r=n.rules.findIndex(i=>i.keyword===t);r>=0?n.rules.splice(r,0,e):(n.rules.push(e),this.logger.warn(`rule ${t} is not defined`));}function cE(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=Lp(e)),n.validateSchema=this.compile(e,true));}var hE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Lp(n){return {anyOf:[n,hE]}}});var Bp=C(dl=>{Object.defineProperty(dl,"__esModule",{value:true});var dE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};dl.default=dE;});var fs=C(fn=>{Object.defineProperty(fn,"__esModule",{value:true});fn.callRef=fn.getValidate=void 0;var fE=jn(),Wp=Ze(),Le=T(),Wn=Je(),Mp=qr(),hs=j(),pE={keyword:"$ref",schemaType:"string",code(n){let{gen:e,schema:t,it:r}=n,{baseId:i,schemaEnv:a,validateName:s,opts:o,self:u}=r,{root:l}=a;if((t==="#"||t==="#/")&&i===l.baseId)return h();let c=Mp.resolveRef.call(u,l,i,t);if(c===void 0)throw new fE.default(r.opts.uriResolver,i,t);if(c instanceof Mp.SchemaEnv)return f(c);return m(c);function h(){if(a===l)return ds(n,s,a,a.$async);let g=e.scopeValue("root",{ref:l});return ds(n,(0, Le._)`${g}.validate`,l,l.$async)}function f(g){let p=Gp(n,g);ds(n,p,g,g.$async);}function m(g){let p=e.scopeValue("schema",o.code.source===true?{ref:g,code:(0, Le.stringify)(g)}:{ref:g}),v=e.name("valid"),_=n.subschema({schema:g,dataTypes:[],schemaPath:Le.nil,topSchemaRef:p,errSchemaPath:t},v);n.mergeEvaluated(_),n.ok(v);}}};function Gp(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, Le._)`${t.scopeValue("wrapper",{ref:e})}.validate`}fn.getValidate=Gp;function ds(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?Wn.default.this:Le.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let g=i.let("valid");i.try(()=>{i.code((0, Le._)`await ${(0, Wp.callValidateCode)(n,e,l)}`),m(e),s||i.assign(g,true);},p=>{i.if((0, Le._)`!(${p} instanceof ${a.ValidationError})`,()=>i.throw(p)),f(p),s||i.assign(g,false);}),n.ok(g);}function h(){n.result((0, Wp.callValidateCode)(n,e,l),()=>m(e),()=>f(e));}function f(g){let p=(0, Le._)`${g}.errors`;i.assign(Wn.default.vErrors,(0, Le._)`${Wn.default.vErrors} === null ? ${p} : ${Wn.default.vErrors}.concat(${p})`),i.assign(Wn.default.errors,(0, Le._)`${Wn.default.vErrors}.length`);}function m(g){var p;if(!a.opts.unevaluated)return;let v=(p=t?.validate)===null||p===void 0?void 0:p.evaluated;if(a.props!==true)if(v&&!v.dynamicProps)v.props!==void 0&&(a.props=hs.mergeEvaluated.props(i,v.props,a.props));else {let _=i.var("props",(0, Le._)`${g}.evaluated.props`);a.props=hs.mergeEvaluated.props(i,_,a.props,Le.Name);}if(a.items!==true)if(v&&!v.dynamicItems)v.items!==void 0&&(a.items=hs.mergeEvaluated.items(i,v.items,a.items));else {let _=i.var("items",(0, Le._)`${g}.evaluated.items`);a.items=hs.mergeEvaluated.items(i,_,a.items,Le.Name);}}}fn.callRef=ds;fn.default=pE;});var pl=C(fl=>{Object.defineProperty(fl,"__esModule",{value:true});var mE=Bp(),gE=fs(),yE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",mE.default,gE.default];fl.default=yE;});var Up=C(ml=>{Object.defineProperty(ml,"__esModule",{value:true});var ps=T(),Mt=ps.operators,ms={maximum:{okStr:"<=",ok:Mt.LTE,fail:Mt.GT},minimum:{okStr:">=",ok:Mt.GTE,fail:Mt.LT},exclusiveMaximum:{okStr:"<",ok:Mt.LT,fail:Mt.GTE},exclusiveMinimum:{okStr:">",ok:Mt.GT,fail:Mt.LTE}},CE={message:({keyword:n,schemaCode:e})=>(0, ps.str)`must be ${ms[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, ps._)`{comparison: ${ms[n].okStr}, limit: ${e}}`},vE={keyword:Object.keys(ms),type:"number",schemaType:"number",$data:true,error:CE,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, ps._)`${t} ${ms[e].fail} ${r} || isNaN(${t})`);}};ml.default=vE;});var Hp=C(gl=>{Object.defineProperty(gl,"__esModule",{value:true});var Gr=T(),_E={message:({schemaCode:n})=>(0, Gr.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, Gr._)`{multipleOf: ${n}}`},EE={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:_E,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, Gr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, Gr._)`${s} !== parseInt(${s})`;n.fail$data((0, Gr._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};gl.default=EE;});var zp=C(yl=>{Object.defineProperty(yl,"__esModule",{value:true});function Kp(n){let e=n.length,t=0,r=0,i;for(;r<e;)t++,i=n.charCodeAt(r++),i>=55296&&i<=56319&&r<e&&(i=n.charCodeAt(r),(i&64512)===56320&&r++);return t}yl.default=Kp;Kp.code='require("ajv/dist/runtime/ucs2length").default';});var Jp=C(Cl=>{Object.defineProperty(Cl,"__esModule",{value:true});var pn=T(),bE=j(),SE=zp(),DE={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, pn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, pn._)`{limit: ${n}}`},wE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:DE,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?pn.operators.GT:pn.operators.LT,s=i.opts.unicode===false?(0, pn._)`${t}.length`:(0, pn._)`${(0, bE.useFunc)(n.gen,SE.default)}(${t})`;n.fail$data((0, pn._)`${s} ${a} ${r}`);}};Cl.default=wE;});var Zp=C(vl=>{Object.defineProperty(vl,"__esModule",{value:true});var AE=Ze(),PE=j(),Mn=T(),FE={message:({schemaCode:n})=>(0, Mn.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, Mn._)`{pattern: ${n}}`},OE={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:FE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n,o=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:u}=s.opts.code,l=u.code==="new RegExp"?(0, Mn._)`new RegExp`:(0, PE.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, Mn._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, Mn._)`!${c}`);}else {let u=(0, AE.usePattern)(n,i);n.fail$data((0, Mn._)`!${u}.test(${t})`);}}};vl.default=OE;});var Xp=C(_l=>{Object.defineProperty(_l,"__esModule",{value:true});var Ur=T(),xE={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Ur.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Ur._)`{limit: ${n}}`},NE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:xE,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Ur.operators.GT:Ur.operators.LT;n.fail$data((0, Ur._)`Object.keys(${t}).length ${i} ${r}`);}};_l.default=NE;});var Qp=C(El=>{Object.defineProperty(El,"__esModule",{value:true});var Hr=Ze(),Kr=T(),TE=j(),IE={message:({params:{missingProperty:n}})=>(0, Kr.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, Kr._)`{missingProperty: ${n}}`},kE={keyword:"required",type:"object",schemaType:"array",$data:true,error:IE,code(n){let{gen:e,schema:t,schemaCode:r,data:i,$data:a,it:s}=n,{opts:o}=s;if(!a&&t.length===0)return;let u=t.length>=o.loopRequired;if(s.allErrors?l():c(),o.strictRequired){let m=n.parentSchema.properties,{definedProperties:g}=n.it;for(let p of t)if(m?.[p]===void 0&&!g.has(p)){let v=s.schemaEnv.baseId+s.errSchemaPath,_=`required property "${p}" is not defined at "${v}" (strictRequired)`;(0, TE.checkStrictMode)(s,_,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(Kr.nil,h);else for(let m of t)(0, Hr.checkReportMissingProp)(n,m);}function c(){let m=e.let("missing");if(u||a){let g=e.let("valid",true);n.block$data(g,()=>f(m,g)),n.ok(g);}else e.if((0, Hr.checkMissingProp)(n,t,m)),(0, Hr.reportMissingProp)(n,m),e.else();}function h(){e.forOf("prop",r,m=>{n.setParams({missingProperty:m}),e.if((0, Hr.noPropertyInData)(e,i,m,o.ownProperties),()=>n.error());});}function f(m,g){n.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(g,(0, Hr.propertyInData)(e,i,m,o.ownProperties)),e.if((0, Kr.not)(g),()=>{n.error(),e.break();});},Kr.nil);}}};El.default=kE;});var Yp=C(bl=>{Object.defineProperty(bl,"__esModule",{value:true});var zr=T(),$E={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, zr.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, zr._)`{limit: ${n}}`},RE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:$E,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?zr.operators.GT:zr.operators.LT;n.fail$data((0, zr._)`${t}.length ${i} ${r}`);}};bl.default=RE;});var gs=C(Sl=>{Object.defineProperty(Sl,"__esModule",{value:true});var em=qu();em.code='require("ajv/dist/runtime/equal").default';Sl.default=em;});var tm=C(wl=>{Object.defineProperty(wl,"__esModule",{value:true});var Dl=Ir(),ve=T(),VE=j(),qE=gs(),jE={message:({params:{i:n,j:e}})=>(0, ve.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, ve._)`{i: ${n}, j: ${e}}`},LE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:jE,code(n){let{gen:e,data:t,$data:r,schema:i,parentSchema:a,schemaCode:s,it:o}=n;if(!r&&!i)return;let u=e.let("valid"),l=a.items?(0, Dl.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, ve._)`${s} === false`),n.ok(u);function c(){let g=e.let("i",(0, ve._)`${t}.length`),p=e.let("j");n.setParams({i:g,j:p}),e.assign(u,true),e.if((0, ve._)`${g} > 1`,()=>(h()?f:m)(g,p));}function h(){return l.length>0&&!l.some(g=>g==="object"||g==="array")}function f(g,p){let v=e.name("item"),_=(0, Dl.checkDataTypes)(l,v,o.opts.strictNumbers,Dl.DataType.Wrong),b=e.const("indices",(0, ve._)`{}`);e.for((0, ve._)`;${g}--;`,()=>{e.let(v,(0, ve._)`${t}[${g}]`),e.if(_,(0, ve._)`continue`),l.length>1&&e.if((0, ve._)`typeof ${v} == "string"`,(0, ve._)`${v} += "_"`),e.if((0, ve._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(p,(0, ve._)`${b}[${v}]`),n.error(),e.assign(u,false).break();}).code((0, ve._)`${b}[${v}] = ${g}`);});}function m(g,p){let v=(0, VE.useFunc)(e,qE.default),_=e.name("outer");e.label(_).for((0, ve._)`;${g}--;`,()=>e.for((0, ve._)`${p} = ${g}; ${p}--;`,()=>e.if((0, ve._)`${v}(${t}[${g}], ${t}[${p}])`,()=>{n.error(),e.assign(u,false).break(_);})));}}};wl.default=LE;});var nm=C(Pl=>{Object.defineProperty(Pl,"__esModule",{value:true});var Al=T(),BE=j(),WE=gs(),ME={message:"must be equal to constant",params:({schemaCode:n})=>(0, Al._)`{allowedValue: ${n}}`},GE={keyword:"const",$data:true,error:ME,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, Al._)`!${(0, BE.useFunc)(e,WE.default)}(${t}, ${i})`):n.fail((0, Al._)`${a} !== ${t}`);}};Pl.default=GE;});var rm=C(Fl=>{Object.defineProperty(Fl,"__esModule",{value:true});var Jr=T(),UE=j(),HE=gs(),KE={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, Jr._)`{allowedValues: ${n}}`},zE={keyword:"enum",schemaType:"array",$data:true,error:KE,code(n){let{gen:e,data:t,$data:r,schema:i,schemaCode:a,it:s}=n;if(!r&&i.length===0)throw new Error("enum must have non-empty array");let o=i.length>=s.opts.loopEnum,u,l=()=>u??(u=(0, UE.useFunc)(e,HE.default)),c;if(o||r)c=e.let("valid"),n.block$data(c,h);else {if(!Array.isArray(i))throw new Error("ajv implementation error");let m=e.const("vSchema",a);c=(0, Jr.or)(...i.map((g,p)=>f(m,p)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,m=>e.if((0, Jr._)`${l()}(${t}, ${m})`,()=>e.assign(c,true).break()));}function f(m,g){let p=i[g];return typeof p=="object"&&p!==null?(0, Jr._)`${l()}(${t}, ${m}[${g}])`:(0, Jr._)`${t} === ${p}`}}};Fl.default=zE;});var xl=C(Ol=>{Object.defineProperty(Ol,"__esModule",{value:true});var JE=Up(),ZE=Hp(),XE=Jp(),QE=Zp(),YE=Xp(),eb=Qp(),tb=Yp(),nb=tm(),rb=nm(),ib=rm(),sb=[JE.default,ZE.default,XE.default,QE.default,YE.default,eb.default,tb.default,nb.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rb.default,ib.default];Ol.default=sb;});var Tl=C(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.validateAdditionalItems=void 0;var mn=T(),Nl=j(),ab={message:({params:{len:n}})=>(0, mn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, mn._)`{limit: ${n}}`},ob={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ab,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, Nl.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}im(n,r);}};function im(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, mn._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, mn._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, Nl.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, mn._)`${o} <= ${e.length}`);t.if((0, mn.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:Nl.Type.Num},l),s.allErrors||t.if((0, mn.not)(l),()=>t.break());});}}Zr.validateAdditionalItems=im;Zr.default=ob;});var Il=C(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.validateTuple=void 0;var sm=T(),ys=j(),ub=Ze(),lb={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return am(n,"additionalItems",e);t.items=true,!(0, ys.alwaysValidSchema)(t,e)&&n.ok((0, ub.validateArray)(n));}};function am(n,e,t=n.schema){let{gen:r,parentSchema:i,data:a,keyword:s,it:o}=n;c(i),o.opts.unevaluated&&t.length&&o.items!==true&&(o.items=ys.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, sm._)`${a}.length`);t.forEach((h,f)=>{(0, ys.alwaysValidSchema)(o,h)||(r.if((0, sm._)`${l} > ${f}`,()=>n.subschema({keyword:s,schemaProp:f,dataProp:f},u)),n.ok(u));});function c(h){let{opts:f,errSchemaPath:m}=o,g=t.length,p=g===h.minItems&&(g===h.maxItems||h[e]===false);if(f.strictTuples&&!p){let v=`"${s}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0, ys.checkStrictMode)(o,v,f.strictTuples);}}}Xr.validateTuple=am;Xr.default=lb;});var om=C(kl=>{Object.defineProperty(kl,"__esModule",{value:true});var cb=Il(),hb={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, cb.validateTuple)(n,"items")};kl.default=hb;});var lm=C($l=>{Object.defineProperty($l,"__esModule",{value:true});var um=T(),db=j(),fb=Ze(),pb=Tl(),mb={message:({params:{len:n}})=>(0, um.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, um._)`{limit: ${n}}`},gb={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mb,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, db.alwaysValidSchema)(r,e)&&(i?(0, pb.validateAdditionalItems)(n,i):n.ok((0, fb.validateArray)(n)));}};$l.default=gb;});var cm=C(Rl=>{Object.defineProperty(Rl,"__esModule",{value:true});var Qe=T(),Cs=j(),yb={message:({params:{min:n,max:e}})=>e===void 0?(0, Qe.str)`must contain at least ${n} valid item(s)`:(0, Qe.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, Qe._)`{minContains: ${n}}`:(0, Qe._)`{minContains: ${n}, maxContains: ${e}}`},Cb={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:yb,code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n,s,o,{minContains:u,maxContains:l}=r;a.opts.next?(s=u===void 0?1:u,o=l):s=1;let c=e.const("len",(0, Qe._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, Cs.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, Cs.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, Cs.alwaysValidSchema)(a,t)){let p=(0, Qe._)`${c} >= ${s}`;o!==void 0&&(p=(0, Qe._)`${p} && ${c} <= ${o}`),n.pass(p);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?m(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, Qe._)`${i}.length > 0`,f)):(e.let(h,false),f()),n.result(h,()=>n.reset());function f(){let p=e.name("_valid"),v=e.let("count",0);m(p,()=>e.if(p,()=>g(v)));}function m(p,v){e.forRange("i",0,c,_=>{n.subschema({keyword:"contains",dataProp:_,dataPropType:Cs.Type.Num,compositeRule:true},p),v();});}function g(p){e.code((0, Qe._)`${p}++`),o===void 0?e.if((0, Qe._)`${p} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, Qe._)`${p} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, Qe._)`${p} >= ${s}`,()=>e.assign(h,true)));}}};Rl.default=Cb;});var vs=C(mt=>{Object.defineProperty(mt,"__esModule",{value:true});mt.validateSchemaDeps=mt.validatePropertyDeps=mt.error=void 0;var Vl=T(),vb=j(),Qr=Ze();mt.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, Vl.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, Vl._)`{property: ${n},
6
6
  missingProperty: ${r},
7
7
  depsCount: ${e},
8
- deps: ${t}}`};var Cb={keyword:"dependencies",type:"object",schemaType:"object",error:mt.error,code(n){let[e,t]=vb(n);cm(n,e),hm(n,t);}};function vb({schema:n}){let e={},t={};for(let r in n){if(r==="__proto__")continue;let i=Array.isArray(n[r])?e:t;i[r]=n[r];}return [e,t]}function cm(n,e=n.schema){let{gen:t,data:r,it:i}=n;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let u=(0, Qr.propertyInData)(t,r,s,i.opts.ownProperties);n.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(u,()=>{for(let l of o)(0, Qr.checkReportMissingProp)(n,l);}):(t.if((0, $l._)`${u} && (${(0, Qr.checkMissingProp)(n,o,a)})`),(0, Qr.reportMissingProp)(n,a),t.else());}}mt.validatePropertyDeps=cm;function hm(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, yb.alwaysValidSchema)(a,e[o])||(t.if((0, Qr.propertyInData)(t,r,o,a.opts.ownProperties),()=>{let u=n.subschema({keyword:i,schemaProp:o},s);n.mergeValidEvaluated(u,s);},()=>t.var(s,true)),n.ok(s));}mt.validateSchemaDeps=hm;mt.default=Cb;});var fm=y(Rl=>{Object.defineProperty(Rl,"__esModule",{value:true});var dm=I(),_b=L(),Eb={message:"property name must be valid",params:({params:n})=>(0, dm._)`{propertyName: ${n.propertyName}}`},bb={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Eb,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, _b.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",r,s=>{n.setParams({propertyName:s}),n.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:true},a),e.if((0, dm.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};Rl.default=bb;});var ql=y(Vl=>{Object.defineProperty(Vl,"__esModule",{value:true});var _s=Ze(),ct=I(),Sb=Je(),Es=L(),Db={message:"must NOT have additional properties",params:({params:n})=>(0, ct._)`{additionalProperty: ${n.additionalProperty}}`},wb={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:Db,code(n){let{gen:e,schema:t,parentSchema:r,data:i,errsCount:a,it:s}=n;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:u}=s;if(s.props=true,u.removeAdditional!=="all"&&(0, Es.alwaysValidSchema)(s,t))return;let l=(0, _s.allSchemaProperties)(r.properties),c=(0, _s.allSchemaProperties)(r.patternProperties);h(),n.ok((0, ct._)`${a} === ${Sb.default.errors}`);function h(){e.forIn("key",i,v=>{!l.length&&!c.length?m(v):e.if(d(v),()=>m(v));});}function d(v){let _;if(l.length>8){let b=(0, Es.schemaRefOrVal)(s,r.properties,"properties");_=(0, _s.isOwnProperty)(e,b,v);}else l.length?_=(0, ct.or)(...l.map(b=>(0, ct._)`${v} === ${b}`)):_=ct.nil;return c.length&&(_=(0, ct.or)(_,...c.map(b=>(0, ct._)`${(0, _s.usePattern)(n,b)}.test(${v})`))),(0, ct.not)(_)}function p(v){e.code((0, ct._)`delete ${i}[${v}]`);}function m(v){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){p(v);return}if(t===false){n.setParams({additionalProperty:v}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, Es.alwaysValidSchema)(s,t)){let _=e.name("valid");u.removeAdditional==="failing"?(f(v,_,false),e.if((0, ct.not)(_),()=>{n.reset(),p(v);})):(f(v,_),o||e.if((0, ct.not)(_),()=>e.break()));}}function f(v,_,b){let E={keyword:"additionalProperties",dataProp:v,dataPropType:Es.Type.Str};b===false&&Object.assign(E,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(E,_);}}};Vl.default=wb;});var gm=y(Ll=>{Object.defineProperty(Ll,"__esModule",{value:true});var Ab=jn(),pm=Ze(),jl=L(),mm=ql(),Pb={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n;a.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&mm.default.code(new Ab.KeywordCxt(a,mm.default,"additionalProperties"));let s=(0, pm.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=jl.mergeEvaluated.props(e,(0, jl.toHash)(s),a.props));let o=s.filter(h=>!(0, jl.alwaysValidSchema)(a,t[h]));if(o.length===0)return;let u=e.name("valid");for(let h of o)l(h)?c(h):(e.if((0, pm.propertyInData)(e,i,h,a.opts.ownProperties)),c(h),a.allErrors||e.else().var(u,true),e.endIf()),n.it.definedProperties.add(h),n.ok(u);function l(h){return a.opts.useDefaults&&!a.compositeRule&&t[h].default!==void 0}function c(h){n.subschema({keyword:"properties",schemaProp:h,dataProp:h},u);}}};Ll.default=Pb;});var _m=y(Bl=>{Object.defineProperty(Bl,"__esModule",{value:true});var ym=Ze(),bs=I(),Cm=L(),vm=L(),Fb={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,data:r,parentSchema:i,it:a}=n,{opts:s}=a,o=(0, ym.allSchemaProperties)(t),u=o.filter(f=>(0, Cm.alwaysValidSchema)(a,t[f]));if(o.length===0||u.length===o.length&&(!a.opts.unevaluated||a.props===true))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==true&&!(a.props instanceof bs.Name)&&(a.props=(0, vm.evaluatedPropsToName)(e,a.props));let{props:h}=a;d();function d(){for(let f of o)l&&p(f),a.allErrors?m(f):(e.var(c,true),m(f),e.if(c));}function p(f){for(let v in l)new RegExp(f).test(v)&&(0, Cm.checkStrictMode)(a,`property ${v} matches pattern ${f} (use allowMatchingProperties)`);}function m(f){e.forIn("key",r,v=>{e.if((0, bs._)`${(0, ym.usePattern)(n,f)}.test(${v})`,()=>{let _=u.includes(f);_||n.subschema({keyword:"patternProperties",schemaProp:f,dataProp:v,dataPropType:vm.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, bs._)`${h}[${v}]`,true):!_&&!a.allErrors&&e.if((0, bs.not)(c),()=>e.break());});});}}};Bl.default=Fb;});var Em=y(Wl=>{Object.defineProperty(Wl,"__esModule",{value:true});var Ob=L(),xb={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, Ob.alwaysValidSchema)(r,t)){n.fail();return}let i=e.name("valid");n.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},i),n.failResult(i,()=>n.reset(),()=>n.error());},error:{message:"must NOT be valid"}};Wl.default=xb;});var bm=y(Ml=>{Object.defineProperty(Ml,"__esModule",{value:true});var Nb=Ze(),Tb={keyword:"anyOf",schemaType:"array",trackErrors:true,code:Nb.validateUnion,error:{message:"must match a schema in anyOf"}};Ml.default=Tb;});var Sm=y(Gl=>{Object.defineProperty(Gl,"__esModule",{value:true});var Ss=I(),Ib=L(),kb={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, Ss._)`{passingSchemas: ${n.passing}}`},$b={keyword:"oneOf",schemaType:"array",trackErrors:true,error:kb,code(n){let{gen:e,schema:t,parentSchema:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&r.discriminator)return;let a=t,s=e.let("valid",false),o=e.let("passing",null),u=e.name("_valid");n.setParams({passing:o}),e.block(l),n.result(s,()=>n.reset(),()=>n.error(true));function l(){a.forEach((c,h)=>{let d;(0, Ib.alwaysValidSchema)(i,c)?e.var(u,true):d=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, Ss._)`${u} && ${s}`).assign(s,false).assign(o,(0, Ss._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),d&&n.mergeEvaluated(d,Ss.Name);});});}}};Gl.default=$b;});var Dm=y(Ul=>{Object.defineProperty(Ul,"__esModule",{value:true});var Rb=L(),Vb={keyword:"allOf",schemaType:"array",code(n){let{gen:e,schema:t,it:r}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0, Rb.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};Ul.default=Vb;});var Pm=y(Hl=>{Object.defineProperty(Hl,"__esModule",{value:true});var Ds=I(),Am=L(),qb={message:({params:n})=>(0, Ds.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, Ds._)`{failingKeyword: ${n.ifClause}}`},jb={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:qb,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, Am.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=wm(r,"then"),a=wm(r,"else");if(!i&&!a)return;let s=e.let("valid",true),o=e.name("_valid");if(u(),n.reset(),i&&a){let c=e.let("ifClause");n.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c));}else i?e.if(o,l("then")):e.if((0, Ds.not)(o),l("else"));n.pass(s,()=>n.error(true));function u(){let c=n.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},o);n.mergeEvaluated(c);}function l(c,h){return ()=>{let d=n.subschema({keyword:c},o);e.assign(s,o),n.mergeValidEvaluated(d,s),h?e.assign(h,(0, Ds._)`${c}`):n.setParams({ifClause:c});}}}};function wm(n,e){let t=n.schema[e];return t!==void 0&&!(0, Am.alwaysValidSchema)(n,t)}Hl.default=jb;});var Fm=y(Kl=>{Object.defineProperty(Kl,"__esModule",{value:true});var Lb=L(),Bb={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, Lb.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Kl.default=Bb;});var Jl=y(zl=>{Object.defineProperty(zl,"__esModule",{value:true});var Wb=xl(),Mb=am(),Gb=Nl(),Ub=um(),Hb=lm(),Kb=vs(),zb=fm(),Jb=ql(),Zb=gm(),Xb=_m(),Qb=Em(),Yb=bm(),eS=Sm(),tS=Dm(),nS=Pm(),rS=Fm();function iS(n=false){let e=[Qb.default,Yb.default,eS.default,tS.default,nS.default,rS.default,zb.default,Jb.default,Kb.default,Zb.default,Xb.default];return n?e.push(Mb.default,Ub.default):e.push(Wb.default,Gb.default),e.push(Hb.default),e}zl.default=iS;});var Om=y(Zl=>{Object.defineProperty(Zl,"__esModule",{value:true});var le=I(),sS={message:({schemaCode:n})=>(0, le.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, le._)`{format: ${n}}`},aS={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:sS,code(n,e){let{gen:t,data:r,$data:i,schema:a,schemaCode:s,it:o}=n,{opts:u,errSchemaPath:l,schemaEnv:c,self:h}=o;if(!u.validateFormats)return;i?d():p();function d(){let m=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),f=t.const("fDef",(0, le._)`${m}[${s}]`),v=t.let("fType"),_=t.let("format");t.if((0, le._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>t.assign(v,(0, le._)`${f}.type || "string"`).assign(_,(0, le._)`${f}.validate`),()=>t.assign(v,(0, le._)`"string"`).assign(_,f)),n.fail$data((0, le.or)(b(),E()));function b(){return u.strictSchema===false?le.nil:(0, le._)`${s} && !${_}`}function E(){let g=c.$async?(0, le._)`(${f}.async ? await ${_}(${r}) : ${_}(${r}))`:(0, le._)`${_}(${r})`,C=(0, le._)`(typeof ${_} == "function" ? ${g} : ${_}.test(${r}))`;return (0, le._)`${_} && ${_} !== true && ${v} === ${e} && !${C}`}}function p(){let m=h.formats[a];if(!m){b();return}if(m===true)return;let[f,v,_]=E(m);f===e&&n.pass(g());function b(){if(u.strictSchema===false){h.logger.warn(C());return}throw new Error(C());function C(){return `unknown format "${a}" ignored in schema at path "${l}"`}}function E(C){let S=C instanceof RegExp?(0, le.regexpCode)(C):u.code.formats?(0, le._)`${u.code.formats}${(0, le.getProperty)(a)}`:void 0,w=t.scopeValue("formats",{key:a,ref:C,code:S});return typeof C=="object"&&!(C instanceof RegExp)?[C.type||"string",C.validate,(0, le._)`${w}.validate`]:["string",C,w]}function g(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!c.$async)throw new Error("async format in sync schema");return (0, le._)`await ${_}(${r})`}return typeof v=="function"?(0, le._)`${_}(${r})`:(0, le._)`${_}.test(${r})`}}}};Zl.default=aS;});var Ql=y(Xl=>{Object.defineProperty(Xl,"__esModule",{value:true});var oS=Om(),uS=[oS.default];Xl.default=uS;});var Yl=y(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.contentVocabulary=Un.metadataVocabulary=void 0;Un.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Un.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var Nm=y(ec=>{Object.defineProperty(ec,"__esModule",{value:true});var lS=dl(),cS=Fl(),hS=Jl(),dS=Ql(),xm=Yl(),fS=[lS.default,cS.default,(0, hS.default)(),dS.default,xm.metadataVocabulary,xm.contentVocabulary];ec.default=fS;});var Im=y(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.DiscrError=void 0;var Tm;(function(n){n.Tag="tag",n.Mapping="mapping";})(Tm||(ws.DiscrError=Tm={}));});var rc=y(nc=>{Object.defineProperty(nc,"__esModule",{value:true});var Hn=I(),tc=Im(),km=qr(),pS=Ln(),mS=L(),gS={message:({params:{discrError:n,tagName:e}})=>n===tc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Hn._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},yS={keyword:"discriminator",type:"object",schemaType:"object",error:gS,code(n){let{gen:e,data:t,schema:r,parentSchema:i,it:a}=n,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=r.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",false),l=e.const("tag",(0, Hn._)`${t}${(0, Hn.getProperty)(o)}`);e.if((0, Hn._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:tc.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let p=d();e.if(false);for(let m in p)e.elseIf((0, Hn._)`${l} === ${m}`),e.assign(u,h(p[m]));e.else(),n.error(false,{discrError:tc.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(p){let m=e.name("valid"),f=n.subschema({keyword:"oneOf",schemaProp:p},m);return n.mergeEvaluated(f,Hn.Name),m}function d(){var p;let m={},f=_(i),v=true;for(let g=0;g<s.length;g++){let C=s[g];if(C?.$ref&&!(0, mS.schemaHasRulesButRef)(C,a.self.RULES)){let w=C.$ref;if(C=km.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,w),C instanceof km.SchemaEnv&&(C=C.schema),C===void 0)throw new pS.default(a.opts.uriResolver,a.baseId,w)}let S=(p=C?.properties)===null||p===void 0?void 0:p[o];if(typeof S!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);v=v&&(f||_(C)),b(S,g);}if(!v)throw new Error(`discriminator: "${o}" must be required`);return m;function _({required:g}){return Array.isArray(g)&&g.includes(o)}function b(g,C){if(g.const)E(g.const,C);else if(g.enum)for(let S of g.enum)E(S,C);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function E(g,C){if(typeof g!="string"||g in m)throw new Error(`discriminator: "${o}" values must be unique strings`);m[g]=C;}}}};nc.default=yS;});var $m=y((fx,CS)=>{CS.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:true,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:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},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:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},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:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},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:true};});var Vm=y((ne,ic)=>{Object.defineProperty(ne,"__esModule",{value:true});ne.MissingRefError=ne.ValidationError=ne.CodeGen=ne.Name=ne.nil=ne.stringify=ne.str=ne._=ne.KeywordCxt=ne.Ajv=void 0;var vS=ll(),_S=Nm(),ES=rc(),Rm=$m(),bS=["/properties"],As="http://json-schema.org/draft-07/schema",Kn=class extends vS.default{_addVocabularies(){super._addVocabularies(),_S.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ES.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Rm,bS):Rm;this.addMetaSchema(e,As,false),this.refs["http://json-schema.org/schema"]=As;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(As)?As:void 0)}};ne.Ajv=Kn;ic.exports=ne=Kn;ic.exports.Ajv=Kn;Object.defineProperty(ne,"__esModule",{value:true});ne.default=Kn;var SS=jn();Object.defineProperty(ne,"KeywordCxt",{enumerable:true,get:function(){return SS.KeywordCxt}});var zn=I();Object.defineProperty(ne,"_",{enumerable:true,get:function(){return zn._}});Object.defineProperty(ne,"str",{enumerable:true,get:function(){return zn.str}});Object.defineProperty(ne,"stringify",{enumerable:true,get:function(){return zn.stringify}});Object.defineProperty(ne,"nil",{enumerable:true,get:function(){return zn.nil}});Object.defineProperty(ne,"Name",{enumerable:true,get:function(){return zn.Name}});Object.defineProperty(ne,"CodeGen",{enumerable:true,get:function(){return zn.CodeGen}});var DS=Vr();Object.defineProperty(ne,"ValidationError",{enumerable:true,get:function(){return DS.default}});var wS=Ln();Object.defineProperty(ne,"MissingRefError",{enumerable:true,get:function(){return wS.default}});});var ac=y(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.dynamicAnchor=void 0;var sc=I(),AS=Je(),qm=qr(),PS=fs(),FS={keyword:"$dynamicAnchor",schemaType:"string",code:n=>jm(n,n.schema)};function jm(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, sc._)`${AS.default.dynamicAnchors}${(0, sc.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:OS(n);t.if((0, sc._)`!${i}`,()=>t.assign(i,a));}Yr.dynamicAnchor=jm;function OS(n){let{schemaEnv:e,schema:t,self:r}=n.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:u}=r.opts,l=new qm.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return qm.compileSchema.call(r,l),(0, PS.getValidate)(n,l)}Yr.default=FS;});var oc=y(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.dynamicRef=void 0;var Lm=I(),xS=Je(),Bm=fs(),NS={keyword:"$dynamicRef",schemaType:"string",code:n=>Wm(n,n.schema)};function Wm(n,e){let{gen:t,keyword:r,it:i}=n;if(e[0]!=="#")throw new Error(`"${r}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else {let u=t.let("valid",false);s(u),n.ok(u);}function s(u){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0, Lm._)`${xS.default.dynamicAnchors}${(0, Lm.getProperty)(a)}`);t.if(l,o(l,u),o(i.validateName,u));}else o(i.validateName,u)();}function o(u,l){return l?()=>t.block(()=>{(0, Bm.callRef)(n,u),t.let(l,true);}):()=>(0, Bm.callRef)(n,u)}}ei.dynamicRef=Wm;ei.default=NS;});var Mm=y(uc=>{Object.defineProperty(uc,"__esModule",{value:true});var TS=ac(),IS=L(),kS={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, TS.dynamicAnchor)(n,""):(0, IS.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};uc.default=kS;});var Gm=y(lc=>{Object.defineProperty(lc,"__esModule",{value:true});var $S=oc(),RS={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, $S.dynamicRef)(n,n.schema)};lc.default=RS;});var Um=y(cc=>{Object.defineProperty(cc,"__esModule",{value:true});var VS=ac(),qS=oc(),jS=Mm(),LS=Gm(),BS=[VS.default,qS.default,jS.default,LS.default];cc.default=BS;});var Km=y(hc=>{Object.defineProperty(hc,"__esModule",{value:true});var Hm=vs(),WS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Hm.error,code:n=>(0, Hm.validatePropertyDeps)(n)};hc.default=WS;});var zm=y(dc=>{Object.defineProperty(dc,"__esModule",{value:true});var MS=vs(),GS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, MS.validateSchemaDeps)(n)};dc.default=GS;});var Jm=y(fc=>{Object.defineProperty(fc,"__esModule",{value:true});var US=L(),HS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, US.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};fc.default=HS;});var Zm=y(pc=>{Object.defineProperty(pc,"__esModule",{value:true});var KS=Km(),zS=zm(),JS=Jm(),ZS=[KS.default,zS.default,JS.default];pc.default=ZS;});var Qm=y(mc=>{Object.defineProperty(mc,"__esModule",{value:true});var Ut=I(),Xm=L(),XS=Je(),QS={message:"must NOT have unevaluated properties",params:({params:n})=>(0, Ut._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},YS={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:QS,code(n){let{gen:e,schema:t,data:r,errsCount:i,it:a}=n;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof Ut.Name?e.if((0, Ut._)`${o} !== true`,()=>e.forIn("key",r,h=>e.if(l(o,h),()=>u(h)))):o!==true&&e.forIn("key",r,h=>o===void 0?u(h):e.if(c(o,h),()=>u(h))),a.props=true,n.ok((0, Ut._)`${i} === ${XS.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, Xm.alwaysValidSchema)(a,t)){let d=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:Xm.Type.Str},d),s||e.if((0, Ut.not)(d),()=>e.break());}}function l(h,d){return (0, Ut._)`!${h} || !${h}[${d}]`}function c(h,d){let p=[];for(let m in h)h[m]===true&&p.push((0, Ut._)`${d} !== ${m}`);return (0, Ut.and)(...p)}}};mc.default=YS;});var eg=y(gc=>{Object.defineProperty(gc,"__esModule",{value:true});var yn=I(),Ym=L(),eD={message:({params:{len:n}})=>(0, yn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, yn._)`{limit: ${n}}`},tD={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:eD,code(n){let{gen:e,schema:t,data:r,it:i}=n,a=i.items||0;if(a===true)return;let s=e.const("len",(0, yn._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, yn._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, Ym.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, yn._)`${s} <= ${a}`);e.if((0, yn.not)(u),()=>o(u,a)),n.ok(u);}i.items=true;function o(u,l){e.forRange("i",l,s,c=>{n.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:Ym.Type.Num},u),i.allErrors||e.if((0, yn.not)(u),()=>e.break());});}}};gc.default=tD;});var tg=y(yc=>{Object.defineProperty(yc,"__esModule",{value:true});var nD=Qm(),rD=eg(),iD=[nD.default,rD.default];yc.default=iD;});var rg=y(Cc=>{Object.defineProperty(Cc,"__esModule",{value:true});var sD=dl(),aD=Fl(),oD=Jl(),uD=Um(),lD=Zm(),cD=tg(),hD=Ql(),ng=Yl(),dD=[uD.default,sD.default,aD.default,(0, oD.default)(true),hD.default,ng.metadataVocabulary,ng.contentVocabulary,lD.default,cD.default];Cc.default=dD;});var ig=y((Px,fD)=>{fD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}};});var sg=y((Fx,pD)=>{pD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}};});var ag=y((Ox,mD)=>{mD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}};});var og=y((xx,gD)=>{gD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}};});var ug=y((Nx,yD)=>{yD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}};});var lg=y((Tx,CD)=>{CD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}};});var cg=y((Ix,vD)=>{vD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}};});var hg=y((kx,_D)=>{_D.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}};});var dg=y(vc=>{Object.defineProperty(vc,"__esModule",{value:true});var ED=ig(),bD=sg(),SD=ag(),DD=og(),wD=ug(),AD=lg(),PD=cg(),FD=hg(),OD=["/properties"];function xD(n){return [ED,bD,SD,DD,wD,e(this,AD),PD,e(this,FD)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,OD):r}}vc.default=xD;});var fg=y((re,Ec)=>{Object.defineProperty(re,"__esModule",{value:true});re.MissingRefError=re.ValidationError=re.CodeGen=re.Name=re.nil=re.stringify=re.str=re._=re.KeywordCxt=re.Ajv2020=void 0;var ND=ll(),TD=rg(),ID=rc(),kD=dg(),_c="https://json-schema.org/draft/2020-12/schema",Jn=class extends ND.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),TD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ID.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(kD.default.call(this,e),this.refs["http://json-schema.org/schema"]=_c);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_c)?_c:void 0)}};re.Ajv2020=Jn;Ec.exports=re=Jn;Ec.exports.Ajv2020=Jn;Object.defineProperty(re,"__esModule",{value:true});re.default=Jn;var $D=jn();Object.defineProperty(re,"KeywordCxt",{enumerable:true,get:function(){return $D.KeywordCxt}});var Zn=I();Object.defineProperty(re,"_",{enumerable:true,get:function(){return Zn._}});Object.defineProperty(re,"str",{enumerable:true,get:function(){return Zn.str}});Object.defineProperty(re,"stringify",{enumerable:true,get:function(){return Zn.stringify}});Object.defineProperty(re,"nil",{enumerable:true,get:function(){return Zn.nil}});Object.defineProperty(re,"Name",{enumerable:true,get:function(){return Zn.Name}});Object.defineProperty(re,"CodeGen",{enumerable:true,get:function(){return Zn.CodeGen}});var RD=Vr();Object.defineProperty(re,"ValidationError",{enumerable:true,get:function(){return RD.default}});var VD=Ln();Object.defineProperty(re,"MissingRefError",{enumerable:true,get:function(){return VD.default}});});var Sc=y(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.CompilerOptions=void 0;var bc=class{constructor(e=null,t=[],r=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=r,this.errorHandler=i,this.fileHandler=a;}};Ps.CompilerOptions=bc;});var pg=y(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.DebugSourceRange=void 0;var Dc=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};Fs.DebugSourceRange=Dc;});var ti=y(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.ErrorType=void 0;var mg;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(mg||(Os.ErrorType=mg={}));});var gg=y(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.Argument=void 0;var wc=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};xs.Argument=wc;});var Z=y(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.filterUndef=pe.isEquatable=pe.nullIfUndefined=pe.asINamedContentOrNull=pe.asBooleanOrThrows=pe.asNumberOrThrows=pe.asOrThrows=pe.asOrNull=void 0;function qD(n,e){return n instanceof e?yg(n):null}pe.asOrNull=qD;function jD(n,e){if(n instanceof e)return yg(n);throw new Error(`${n} is not of type ${e}`)}pe.asOrThrows=jD;function LD(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}pe.asNumberOrThrows=LD;function BD(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}pe.asBooleanOrThrows=BD;function WD(n){return n.hasValidName&&n.name?n:null}pe.asINamedContentOrNull=WD;function MD(n){return typeof n>"u"?null:n}pe.nullIfUndefined=MD;function GD(n){return typeof n=="object"&&typeof n.Equals=="function"}pe.isEquatable=GD;function yg(n,e){return n}function UD(n){return n!=null}pe.filterUndef=UD;});var se=y(Ns=>{Object.defineProperty(Ns,"__esModule",{value:true});Ns.ParsedObject=void 0;var Cg=Z(),Ac=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let r of t)r.hasOwnProperty("parent")&&(r.parent=this),this.content.push(r);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let r=(0, Cg.asOrNull)(this,e);if(r!==null&&(t===null||t(r)===true))return r;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,r)=>{let i=Array.isArray(r)?r:[],a=(0, Cg.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,r=false){if(t===null&&(t=this),!(t._alreadyHadError&&!r||t._alreadyHadWarning&&r)){if(this.parent)this.parent.Error(e,t,r);else throw new Error(`No parent object to send error to: ${e}`);r?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};Ns.ParsedObject=Ac;});var Is=y(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.AuthorWarning=void 0;var HD=se(),Pc=class extends HD.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Ts.AuthorWarning=Pc;});var Be=y(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.Path=void 0;var Xn=class n{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof n.Component&&arguments[1]instanceof n){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new n(e)}else return n.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new n;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new n,r=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)r++;for(let i=0;i<this._components.length-r;++i)t._components.push(this._components[i]);for(let i=r;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let r of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(r)?this._components.push(new n.Component(parseInt(r))):this._components.push(new n.Component(r));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,r=e._components.length;t<r;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new n;return t._components.push(...this._components),t._components.push(e),t}};ni.Path=Xn;Xn.parentId="^";(function(n){class e{constructor(r){this.index=-1,this.name=null,typeof r=="string"?this.name=r:this.index=r;}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new e(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(r){return r!=null&&r.isIndex==this.isIndex?this.isIndex?this.index==r.index:this.name==r.name:false}}n.Component=e;})(Xn||(ni.Path=Xn={}));});var ri=y(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.Debug=void 0;var vg;(function(n){function e(r,i,a){t(r instanceof i,a);}n.AssertType=e;function t(r,i){if(!r)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}n.Assert=t;})(vg||(ks.Debug=vg={}));});var Ae=y(Qn=>{Object.defineProperty(Qn,"__esModule",{value:true});Qn.throwNullException=Qn.NullException=void 0;var $s=class extends Error{};Qn.NullException=$s;function KD(n){throw new $s(`${n} is null or undefined`)}Qn.throwNullException=KD;});var We=y(Vs=>{Object.defineProperty(Vs,"__esModule",{value:true});Vs.InkObject=void 0;var Yn=Be(),ii=ce(),Fc=ri(),er=Z(),Rs=Ae(),Oc=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let r=t.ContentAtPath(e).obj;if(r){let i=r.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Yn.Path;else {let e=[],t=this,r=(0, er.asOrNull)(t.parent,ii.Container);for(;r!==null;){let i=(0, er.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Rs.throwNullException)("namedChild.name");e.unshift(new Yn.Path.Component(i.name));}else e.unshift(new Yn.Path.Component(r.content.indexOf(t)));t=r,r=(0, er.asOrNull)(r.parent,ii.Container);}this._path=new Yn.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Rs.throwNullException)("path");if(e.isRelative){let t=(0, er.asOrNull)(this,ii.Container);return t===null&&(Fc.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, er.asOrNull)(this.parent,ii.Container),Fc.Debug.Assert(t!==null,"Expected parent to be a container"),Fc.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Rs.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Rs.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,r=Math.min(e.length,t.length),i=-1;for(let u=0;u<r;++u){let l=t.GetComponent(u),c=e.GetComponent(u);if(l.Equals(c))i=u;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let u=0;u<a;++u)s.push(Yn.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new Yn.Path(s,true)}CompactPathString(e){let t=null,r=null;return e.isRelative?(r=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(r=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),r.length<t.length?r:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, er.asOrNull)(e,ii.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,r){e[t]&&(e[t]=null),e[t]=r,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};Vs.InkObject=Oc;});var Cn=y(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.StringBuilder=void 0;var xc=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
9
- `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(r,i)=>typeof t[i]<"u"?t[i]:r);}toString(){return this.string}Clear(){this.string="";}};qs.StringBuilder=xc;});var Ge=y(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.InkList=tr.InkListItem=void 0;var gt=Ae(),zD=Cn(),Me=class n{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new n(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof n){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new n(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!n.isLikeInkListItem(t))return n.Null;let r=t;return new n(r.originName,r.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};tr.InkListItem=Me;var Nc=class n extends Map{constructor(){if(super(arguments[0]instanceof n?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof n){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, gt.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, gt.throwNullException)("def.result");this.origins=[r.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var r;if(e==null||e=="")return new n;let i=(r=t.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(e);if(i)return i.value===null?(0, gt.throwNullException)("listValue.value"):new n(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof Me){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, gt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==r.originName){let a=i.TryGetValueForItem(r,0);if(a.exists){this.Add(r,a.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let r=e,i=null;if(this.origins===null)return (0, gt.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, gt.throwNullException)("itemName");if(a.ContainsItemWithName(r)){if(i!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=n.FromString(r,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new Me(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(Me.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let r=e.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${e}`);this.set(r,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(r=>r.name==e?(t=r,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=Me.fromSerializedKey(e);if(t.originName===null)return (0, gt.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:Me.Null,Value:0};for(let[t,r]of this){let i=Me.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:Me.Null,Value:0};for(let[t,r]of this){let i=Me.fromSerializedKey(t);(e.Key.isNull||r<e.Value)&&(e={Key:i,Value:r});}return e}get inverse(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Me.fromSerializedKey(r);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Me.fromSerializedKey(r);e.set(a.serialized(),i);}return e}Union(e){let t=new n(this);for(let[r,i]of e)t.set(r,i);return t}Intersect(e){let t=new n;for(let[r,i]of this)e.has(r)&&t.set(r,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new n(this);for(let[r]of e)t.delete(r);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[r]of t)if(!this.has(r))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new n(this.maxItem):new n}MinAsList(){return this.Count>0?new n(this.minItem):new n}ListWithSubRange(e,t){if(this.Count==0)return new n;let r=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof n&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof n&&t.Count>0&&(a=t.maxItem.Value);let s=new n;s.SetInitialOriginNames(this.originNames);for(let o of r)o.Value>=i&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof n)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,r]of this){let i=Me.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, gt.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, gt.throwNullException)("y.Key.originName"):t.Value==r.Value?t.Key.originName.localeCompare(r.Key.originName):t.Value<r.Value?-1:t.Value>r.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new zD.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, gt.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};tr.InkList=Nc;});var si=y(js=>{Object.defineProperty(js,"__esModule",{value:true});js.StoryException=void 0;var Tc=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};js.StoryException=Tc;});var nr=y(Ht=>{Object.defineProperty(Ht,"__esModule",{value:true});Ht.tryParseFloat=Ht.tryParseInt=Ht.tryGetValueFromMap=void 0;function JD(n,e,t){if(n===null)return {result:t,exists:false};let r=n.get(e);return typeof r>"u"?{result:t,exists:false}:{result:r,exists:true}}Ht.tryGetValueFromMap=JD;function ZD(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ht.tryParseInt=ZD;function XD(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ht.tryParseFloat=XD;});var ae=y(oe=>{Object.defineProperty(oe,"__esModule",{value:true});oe.ValueType=oe.ListValue=oe.VariablePointerValue=oe.DivertTargetValue=oe.StringValue=oe.FloatValue=oe.IntValue=oe.BoolValue=oe.Value=oe.AbstractValue=void 0;var _g=We(),Eg=Be(),vn=Ge(),QD=si(),ai=Z(),bg=nr(),Ye=Ae(),Ls=class n extends _g.InkObject{static Create(e,t){if(t){if(t===ie.Int&&Number.isInteger(Number(e)))return new Ct(Number(e));if(t===ie.Float&&!isNaN(e))return new vt(Number(e))}if(typeof e=="boolean")return new rr(!!e);if(typeof e=="string")return new Tt(String(e));if(Number.isInteger(Number(e)))return new Ct(Number(e));if(isNaN(e)){if(e instanceof Eg.Path)return new Bs((0, ai.asOrThrows)(e,Eg.Path));if(e instanceof vn.InkList)return new Ws((0, ai.asOrThrows)(e,vn.InkList))}else return new vt(Number(e));return null}Copy(){return (0, ai.asOrThrows)(n.Create(this.valueObject),_g.InkObject)}BadCastException(e){return new QD.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};oe.AbstractValue=Ls;var yt=class extends Ls{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value.toString()}};oe.Value=yt;var rr=class extends yt{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return ie.Bool}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Int)return new Ct(this.value?1:0);if(e==ie.Float)return new vt(this.value?1:0);if(e==ie.String)return new Tt(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};oe.BoolValue=rr;var Ct=class extends yt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ie.Int}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Bool)return new rr(this.value!==0);if(e==ie.Float)return new vt(this.value);if(e==ie.String)return new Tt(""+this.value);throw this.BadCastException(e)}};oe.IntValue=Ct;var vt=class extends yt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ie.Float}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Bool)return new rr(this.value!==0);if(e==ie.Int)return new Ct(this.value);if(e==ie.String)return new Tt(""+this.value);throw this.BadCastException(e)}};oe.FloatValue=vt;var Tt=class extends yt{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
- `,this._isInlineWhitespace=true,this.value===null)return (0, Ye.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return ie.String}get isTruthy(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==ie.Int){let t=(0, bg.tryParseInt)(this.value);if(t.exists)return new Ct(t.result);throw this.BadCastException(e)}if(e==ie.Float){let t=(0, bg.tryParseFloat)(this.value);if(t.exists)return new vt(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};oe.StringValue=Tt;var Bs=class extends yt{constructor(e=null){super(e);}get valueType(){return ie.DivertTarget}get targetPath(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};oe.DivertTargetValue=Bs;var Ic=class n extends yt{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return ie.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new n(this.variableName,this.contextIndex)}};oe.VariablePointerValue=Ic;var Ws=class n extends yt{get isTruthy(){return this.value===null?(0, Ye.throwNullException)("this.value"):this.value.Count>0}get valueType(){return ie.List}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==ie.Int){let t=this.value.maxItem;return t.Key.isNull?new Ct(0):new Ct(t.Value)}else if(e==ie.Float){let t=this.value.maxItem;return t.Key.isNull?new vt(0):new vt(t.Value)}else if(e==ie.String){let t=this.value.maxItem;return t.Key.isNull?new Tt(""):new Tt(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new vn.InkList:e instanceof vn.InkList?this.value=new vn.InkList(e):e instanceof vn.InkListItem&&typeof t=="number"&&(this.value=new vn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, ai.asOrNull)(e,n),i=(0, ai.asOrNull)(t,n);if(i&&i.value===null)return (0, Ye.throwNullException)("newList.value");if(r&&r.value===null)return (0, Ye.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};oe.ListValue=Ws;var ie;(function(n){n[n.Bool=-1]="Bool",n[n.Int=0]="Int",n[n.Float=1]="Float",n[n.List=2]="List",n[n.String=3]="String",n[n.DivertTarget=4]="DivertTarget",n[n.VariablePointer=5]="VariablePointer";})(ie||(oe.ValueType=ie={}));});var Sg=y(Ms=>{Object.defineProperty(Ms,"__esModule",{value:true});Ms.SearchResult=void 0;var YD=ce(),kc=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof YD.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};Ms.SearchResult=kc;});var ce=y(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.Container=void 0;var ew=ae(),Dg=Ae(),tw=Cn(),ir=We(),nw=Sg(),wg=Be(),Ag=ri(),rw=nr(),Kt=Z(),oi=class n extends ir.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,r]of this.namedContent){let i=(0, Kt.asOrThrows)(r,ir.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, Kt.asINamedContentOrNull)(t);r!=null&&r.hasValidName&&e.delete(r.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[r]of t)this.namedContent.delete(r);if(e!=null)for(let[,r]of e){let i=(0, Kt.asINamedContentOrNull)(r);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=n.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=n.CountFlags.Turns),this.countingAtStartOnly&&(e|=n.CountFlags.CountStartOnly),e==n.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&n.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&n.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&n.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof n;)t.content.length>0&&(e.push(new wg.Path.Component(0)),t=t.content[0]);return new wg.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let r of t)this.AddContent(r);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, Kt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Ag.Debug.AssertType(e,ir.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Kt.asOrThrows)(e,ir.InkObject);if(t.parent=this,e.name===null)return (0, Dg.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new nw.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<r;++o){let u=e.GetComponent(o);if(a==null){i.approximate=true;break}let l=a.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let c=(0, Kt.asOrNull)(l,n);if(o<r-1&&c==null){i.approximate=true;break}s=l,a=c;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, Dg.throwNullException)("component.name");let t=(0, rw.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Kt.asOrThrows)(t.result,ir.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new tw.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],r=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==r&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof n?o.BuildStringOfHierarchy(e,t,r):(i(),o instanceof ew.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
11
- `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof n)&&o==r&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Kt.asOrThrows)(o,ir.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Ag.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};ui.Container=oi;(function(n){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(n.CountFlags||(n.CountFlags={}));})(oi||(ui.Container=oi={}));});var Pe=y(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.ControlCommand=void 0;var iw=We(),li=class n extends iw.InkObject{get commandType(){return this._commandType}constructor(e=n.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new n(this.commandType)}static EvalStart(){return new n(n.CommandType.EvalStart)}static EvalOutput(){return new n(n.CommandType.EvalOutput)}static EvalEnd(){return new n(n.CommandType.EvalEnd)}static Duplicate(){return new n(n.CommandType.Duplicate)}static PopEvaluatedValue(){return new n(n.CommandType.PopEvaluatedValue)}static PopFunction(){return new n(n.CommandType.PopFunction)}static PopTunnel(){return new n(n.CommandType.PopTunnel)}static BeginString(){return new n(n.CommandType.BeginString)}static EndString(){return new n(n.CommandType.EndString)}static NoOp(){return new n(n.CommandType.NoOp)}static ChoiceCount(){return new n(n.CommandType.ChoiceCount)}static Turns(){return new n(n.CommandType.Turns)}static TurnsSince(){return new n(n.CommandType.TurnsSince)}static ReadCount(){return new n(n.CommandType.ReadCount)}static Random(){return new n(n.CommandType.Random)}static SeedRandom(){return new n(n.CommandType.SeedRandom)}static VisitIndex(){return new n(n.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new n(n.CommandType.SequenceShuffleIndex)}static StartThread(){return new n(n.CommandType.StartThread)}static Done(){return new n(n.CommandType.Done)}static End(){return new n(n.CommandType.End)}static ListFromInt(){return new n(n.CommandType.ListFromInt)}static ListRange(){return new n(n.CommandType.ListRange)}static ListRandom(){return new n(n.CommandType.ListRandom)}static BeginTag(){return new n(n.CommandType.BeginTag)}static EndTag(){return new n(n.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};ci.ControlCommand=li;(function(n){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(n.CommandType||(n.CommandType={}));})(li||(ci.ControlCommand=li={}));});var et=y(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.Expression=void 0;var Pg=ce(),$c=Pe(),sw=se(),Rc=class extends sw.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Pg.Container;return e.AddContent($c.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent($c.ControlCommand.EvalOutput()),e.AddContent($c.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Pg.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let r=t.Copy();r&&e.AddContent(r);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Gs.Expression=Rc;});var _n=y(Us=>{Object.defineProperty(Us,"__esModule",{value:true});Us.Void=void 0;var aw=We(),Vc=class extends aw.InkObject{toString(){return "Void"}};Us.Void=Vc;});var _t=y(Ks=>{Object.defineProperty(Ks,"__esModule",{value:true});Ks.NativeFunctionCall=void 0;var F=ae(),hi=si(),ow=_n(),Hs=Ge(),uw=We(),tt=Z(),Ue=Ae(),G=class n extends uw.InkObject{static CallWithName(e){return new n(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, Ue.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, Ue.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=n._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof ow.Void)throw new hi.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof F.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==F.ValueType.Int?this.CallType(r):i==F.ValueType.Float?this.CallType(r):i==F.ValueType.String?this.CallType(r):i==F.ValueType.DivertTarget?this.CallType(r):i==F.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, tt.asOrThrows)(e[0],F.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=F.ValueType[r];throw new hi.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, tt.asOrThrows)(e[1],F.Value),l=s;if(i.value===null||u.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return F.Value.Create(c)}else {let o=s;if(i.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?F.Value.Create(u,F.ValueType.Int):this.name===n.Float?F.Value.Create(u,F.ValueType.Float):F.Value.Create(u,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof F.ListValue&&e[1]instanceof F.IntValue)return this.CallListIncrementOperation(e);let t=(0, tt.asOrThrows)(e[0],F.Value),r=(0, tt.asOrThrows)(e[1],F.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=F.ValueType.List||r.valueType!=F.ValueType.List)){if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(F.ValueType.Int);if(i===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, tt.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new F.BoolValue(a)}if(t.valueType==F.ValueType.List&&r.valueType==F.ValueType.List)return this.CallType([t,r]);throw new hi.StoryException("Can not call use "+this.name+" operation on "+F.ValueType[t.valueType]+" and "+F.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, tt.asOrThrows)(e[0],F.ListValue),r=(0, tt.asOrThrows)(e[1],F.IntValue),i=new Hs.InkList;if(t.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Hs.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(F.ValueType.Int);if(r.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let h of t.value.origins)if(h.name==o.originName){c=h;break}if(c!=null){let h=c.TryGetItemWithValue(l,Hs.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new F.ListValue(i)}CoerceValuesToSingleType(e){let t=F.ValueType.Int,r=null;for(let a of e){let s=(0, tt.asOrThrows)(a,F.Value);s.valueType>t&&(t=s.valueType),s.valueType==F.ValueType.List&&(r=(0, tt.asOrNull)(s,F.ListValue));}let i=[];if(F.ValueType[t]==F.ValueType[F.ValueType.List])for(let a of e){let s=(0, tt.asOrThrows)(a,F.Value);if(s.valueType==F.ValueType.List)i.push(s);else if(s.valueType==F.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, tt.asOrThrows)(r,F.ListValue),r.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, Ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,Hs.InkListItem.Null);if(l.exists){let c=new F.ListValue(l.result,o);i.push(c);}else throw new hi.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=F.ValueType[s.valueType];throw new hi.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, tt.asOrThrows)(a,F.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)n.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];n.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(r,i)=>r+i),this.AddIntBinaryOp(this.Subtract,(r,i)=>r-i),this.AddIntBinaryOp(this.Multiply,(r,i)=>r*i),this.AddIntBinaryOp(this.Divide,(r,i)=>Math.floor(r/i)),this.AddIntBinaryOp(this.Mod,(r,i)=>r%i),this.AddIntUnaryOp(this.Negate,r=>-r),this.AddIntBinaryOp(this.Equal,(r,i)=>r==i),this.AddIntBinaryOp(this.Greater,(r,i)=>r>i),this.AddIntBinaryOp(this.Less,(r,i)=>r<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddIntBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddIntUnaryOp(this.Not,r=>r==0),this.AddIntBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddIntBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddIntBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddIntBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddIntBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddIntUnaryOp(this.Floor,n.Identity),this.AddIntUnaryOp(this.Ceiling,n.Identity),this.AddIntUnaryOp(this.Int,n.Identity),this.AddIntUnaryOp(this.Float,r=>r),this.AddFloatBinaryOp(this.Add,(r,i)=>r+i),this.AddFloatBinaryOp(this.Subtract,(r,i)=>r-i),this.AddFloatBinaryOp(this.Multiply,(r,i)=>r*i),this.AddFloatBinaryOp(this.Divide,(r,i)=>r/i),this.AddFloatBinaryOp(this.Mod,(r,i)=>r%i),this.AddFloatUnaryOp(this.Negate,r=>-r),this.AddFloatBinaryOp(this.Equal,(r,i)=>r==i),this.AddFloatBinaryOp(this.Greater,(r,i)=>r>i),this.AddFloatBinaryOp(this.Less,(r,i)=>r<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddFloatBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddFloatUnaryOp(this.Not,r=>r==0),this.AddFloatBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddFloatBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddFloatBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddFloatBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddFloatUnaryOp(this.Floor,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Ceiling,r=>Math.ceil(r)),this.AddFloatUnaryOp(this.Int,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Float,n.Identity),this.AddStringBinaryOp(this.Add,(r,i)=>r+i),this.AddStringBinaryOp(this.Equal,(r,i)=>r===i),this.AddStringBinaryOp(this.NotEquals,(r,i)=>r!==i),this.AddStringBinaryOp(this.Has,(r,i)=>r.includes(i)),this.AddStringBinaryOp(this.Hasnt,(r,i)=>!r.includes(i)),this.AddListBinaryOp(this.Add,(r,i)=>r.Union(i)),this.AddListBinaryOp(this.Subtract,(r,i)=>r.Without(i)),this.AddListBinaryOp(this.Has,(r,i)=>r.Contains(i)),this.AddListBinaryOp(this.Hasnt,(r,i)=>!r.Contains(i)),this.AddListBinaryOp(this.Intersect,(r,i)=>r.Intersect(i)),this.AddListBinaryOp(this.Equal,(r,i)=>r.Equals(i)),this.AddListBinaryOp(this.Greater,(r,i)=>r.GreaterThan(i)),this.AddListBinaryOp(this.Less,(r,i)=>r.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(r,i)=>r.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(r,i)=>r.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(r,i)=>!r.Equals(i)),this.AddListBinaryOp(this.And,(r,i)=>r.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(r,i)=>r.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,r=>r.Count==0?1:0),this.AddListUnaryOp(this.Invert,r=>r.inverse),this.AddListUnaryOp(this.All,r=>r.all),this.AddListUnaryOp(this.ListMin,r=>r.MinAsList()),this.AddListUnaryOp(this.ListMax,r=>r.MaxAsList()),this.AddListUnaryOp(this.Count,r=>r.Count),this.AddListUnaryOp(this.ValueOfList,r=>r.maxItem.Value);let e=(r,i)=>r.Equals(i),t=(r,i)=>!r.Equals(i);this.AddOpToNativeFunc(this.Equal,2,F.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,F.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,r,i){if(this._nativeFunctions===null)return (0, Ue.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new n(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(r,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,F.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,F.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Ks.NativeFunctionCall=G;G.Add="+";G.Subtract="-";G.Divide="/";G.Multiply="*";G.Mod="%";G.Negate="_";G.Equal="==";G.Greater=">";G.Less="<";G.GreaterThanOrEquals=">=";G.LessThanOrEquals="<=";G.NotEquals="!=";G.Not="!";G.And="&&";G.Or="||";G.Min="MIN";G.Max="MAX";G.Pow="POW";G.Floor="FLOOR";G.Ceiling="CEILING";G.Int="INT";G.Float="FLOAT";G.Has="?";G.Hasnt="!?";G.Intersect="^";G.ListMin="LIST_MIN";G.ListMax="LIST_MAX";G.All="LIST_ALL";G.Count="LIST_COUNT";G.ValueOfList="LIST_VALUE";G.Invert="LIST_INVERT";G._nativeFunctions=null;});var Js=y(zs=>{Object.defineProperty(zs,"__esModule",{value:true});zs.NumberExpression=void 0;var lw=et(),qc=ae(),cw=Z(),jc=class n extends lw.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new qc.IntValue(this.value)):this.isFloat()?r.AddContent(new qc.FloatValue(this.value)):this.isBool()&&r.AddContent(new qc.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, cw.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};zs.NumberExpression=jc;});var Lc=y(Zs=>{Object.defineProperty(Zs,"__esModule",{value:true});Zs.UnaryExpression=void 0;var hw=et(),dw=_t(),sr=Js(),fw=Z(),di=class extends hw.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=r=>{this.innerExpression.GenerateIntoContainer(r),r.AddContent(dw.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Zs.UnaryExpression=di;di.WithInner=(n,e)=>{let t=(0, fw.asOrNull)(n,sr.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new sr.NumberExpression(-t.value,"int");if(t.isFloat())return new sr.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new sr.NumberExpression(t.value==0,"bool");if(t.isFloat())return new sr.NumberExpression(t.value==0,"bool");if(t.isBool())return new sr.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new di(n,e)};});var Wc=y(Xs=>{Object.defineProperty(Xs,"__esModule",{value:true});Xs.BinaryExpression=void 0;var pw=et(),mw=_t(),gw=Lc(),yw=Z(),Bc=class extends pw.Expression{constructor(e,t,r){super(),this.opName=r,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(mw.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=r;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, yw.asOrNull)(this.leftExpression,gw.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Xs.BinaryExpression=Bc;});var pi=y(Qs=>{Object.defineProperty(Qs,"__esModule",{value:true});Qs.CharacterSet=void 0;var fi=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,r)=>{for(let i=t.charCodeAt(0);i<=r.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let r of t)this.Add(r);else for(let r of t.set)this.Add(r);return this},e&&this.AddCharacters(e);}};Qs.CharacterSet=fi;fi.FromRange=(n,e)=>new fi().AddRange(n,e);});var Og=y(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.CharacterRange=void 0;var Fg=pi(),mi=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Fg.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},r instanceof Fg.CharacterSet)this._excludes=r.set;else for(let i of r)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};Ys.CharacterRange=mi;mi.Define=(n,e,t=[])=>new mi(n,e,t);});var ta=y(ea=>{Object.defineProperty(ea,"__esModule",{value:true});ea.ChoicePoint=void 0;var Cw=We(),vw=Be(),Mc=Ae(),Gc=class extends Cw.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Mc.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Mc.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new vw.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Mc.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};ea.ChoicePoint=Gc;});var En=y(na=>{Object.defineProperty(na,"__esModule",{value:true});na.PushPopType=void 0;var xg;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(xg||(na.PushPopType=xg={}));});var gi=y(ra=>{Object.defineProperty(ra,"__esModule",{value:true});ra.Pointer=void 0;var _w=Be(),Uc=class n{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new _w.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new n(this.container,this.index)}static StartOf(e){return new n(e,0)}static get Null(){return new n(null,-1)}};ra.Pointer=Uc;});var Et=y(sa=>{Object.defineProperty(sa,"__esModule",{value:true});sa.Divert=void 0;var Ew=Be(),bw=En(),Sw=Cn(),Dw=We(),Hc=gi(),Ng=ce(),ia=Ae(),Kc=class n extends Dw.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=Hc.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, ia.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, ia.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, ia.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Ng.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Hc.Pointer.StartOf(e instanceof Ng.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Ew.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Hc.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof n&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, ia.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new Sw.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==bw.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};sa.Divert=Kc;});var It=y(aa=>{Object.defineProperty(aa,"__esModule",{value:true});aa.SymbolType=void 0;var Tg;(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp";})(Tg||(aa.SymbolType=Tg={}));});var zt=y(oa=>{Object.defineProperty(oa,"__esModule",{value:true});oa.VariableAssignment=void 0;var ww=We(),zc=class extends ww.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};oa.VariableAssignment=zc;});var ar=y(la=>{Object.defineProperty(la,"__esModule",{value:true});la.Choice=void 0;var Aw=ta(),ua=ce(),Jt=Pe(),Jc=Et(),Ig=ae(),Pw=se(),Fw=It(),kg=zt(),Zc=class extends Pw.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,r){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new ua.Container,this._runtimeChoice=new Aw.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Jt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Ig.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new kg.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Jt.ControlCommand.BeginString()),this._divertToStartContentOuter=new Jc.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Jc.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new ua.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Jt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Jt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Jt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Jt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new ua.Container,this.startContent){this._returnToR2=new Ig.DivertTargetValue,this._innerContentContainer.AddContent(Jt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Jt.ControlCommand.EvalEnd());let i=new kg.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Jc.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new ua.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=r,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),r&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Fw.SymbolType.SubFlowAndWeave);}};la.Choice=Zc;});var $g=y(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.StringParserElement=void 0;var ca=class n{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{n._uniqueIdCounter++,this.uniqueId=n._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};ha.StringParserElement=ca;ca._uniqueIdCounter=1e3;});var Vg=y(da=>{Object.defineProperty(da,"__esModule",{value:true});da.StringParserState=void 0;var Rg=$g(),Xc=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let r=0;r<200;++r)this._stack[r]=new Rg.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],r=this._stack[this._numElements];return this._numElements++,r.CopyFrom(t),r.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],r=this._stack[this._numElements-1];t.SquashFrom(r),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Rg.StringParserElement;this._numElements=1;}};da.StringParserState=Xc;});var Yc=y(bn=>{Object.defineProperty(bn,"__esModule",{value:true});bn.StringParser=bn.ParseSuccess=void 0;var Qc=pi(),Ow=Vg();bn.ParseSuccess=Symbol("ParseSuccessStruct");var yi=class n{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r);},this.SucceedRule=(r,i=null)=>{let a=this.state.Peek(r),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,s,a),this.state.Squash();let o=i;return o===null&&(o=n.ParseSuccess),o},this.Expect=(r,i=null,a=null)=>{let s=this.ParseObject(r);if(s===null){i===null&&(i=r.name);let o,u=this.LineRemainder();u===null||u.length===0?o="end of line":o=`'${u}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(r,i=false)=>{this.ErrorOnLine(r,this.lineIndex+1,i);},this.ErrorWithParsedObject=(r,i,a=false)=>{this.ErrorOnLine(r,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(r,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,i-1,a);else throw new Error(`${s} on line ${i}: ${r}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=r=>this.Error(r,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
8
+ deps: ${t}}`};var _b={keyword:"dependencies",type:"object",schemaType:"object",error:mt.error,code(n){let[e,t]=Eb(n);hm(n,e),dm(n,t);}};function Eb({schema:n}){let e={},t={};for(let r in n){if(r==="__proto__")continue;let i=Array.isArray(n[r])?e:t;i[r]=n[r];}return [e,t]}function hm(n,e=n.schema){let{gen:t,data:r,it:i}=n;if(Object.keys(e).length===0)return;let a=t.let("missing");for(let s in e){let o=e[s];if(o.length===0)continue;let u=(0, Qr.propertyInData)(t,r,s,i.opts.ownProperties);n.setParams({property:s,depsCount:o.length,deps:o.join(", ")}),i.allErrors?t.if(u,()=>{for(let l of o)(0, Qr.checkReportMissingProp)(n,l);}):(t.if((0, Vl._)`${u} && (${(0, Qr.checkMissingProp)(n,o,a)})`),(0, Qr.reportMissingProp)(n,a),t.else());}}mt.validatePropertyDeps=hm;function dm(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, vb.alwaysValidSchema)(a,e[o])||(t.if((0, Qr.propertyInData)(t,r,o,a.opts.ownProperties),()=>{let u=n.subschema({keyword:i,schemaProp:o},s);n.mergeValidEvaluated(u,s);},()=>t.var(s,true)),n.ok(s));}mt.validateSchemaDeps=dm;mt.default=_b;});var pm=C(ql=>{Object.defineProperty(ql,"__esModule",{value:true});var fm=T(),bb=j(),Sb={message:"property name must be valid",params:({params:n})=>(0, fm._)`{propertyName: ${n.propertyName}}`},Db={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Sb,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, bb.alwaysValidSchema)(i,t))return;let a=e.name("valid");e.forIn("key",r,s=>{n.setParams({propertyName:s}),n.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:true},a),e.if((0, fm.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};ql.default=Db;});var Ll=C(jl=>{Object.defineProperty(jl,"__esModule",{value:true});var _s=Ze(),ct=T(),wb=Je(),Es=j(),Ab={message:"must NOT have additional properties",params:({params:n})=>(0, ct._)`{additionalProperty: ${n.additionalProperty}}`},Pb={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:Ab,code(n){let{gen:e,schema:t,parentSchema:r,data:i,errsCount:a,it:s}=n;if(!a)throw new Error("ajv implementation error");let{allErrors:o,opts:u}=s;if(s.props=true,u.removeAdditional!=="all"&&(0, Es.alwaysValidSchema)(s,t))return;let l=(0, _s.allSchemaProperties)(r.properties),c=(0, _s.allSchemaProperties)(r.patternProperties);h(),n.ok((0, ct._)`${a} === ${wb.default.errors}`);function h(){e.forIn("key",i,v=>{!l.length&&!c.length?g(v):e.if(f(v),()=>g(v));});}function f(v){let _;if(l.length>8){let b=(0, Es.schemaRefOrVal)(s,r.properties,"properties");_=(0, _s.isOwnProperty)(e,b,v);}else l.length?_=(0, ct.or)(...l.map(b=>(0, ct._)`${v} === ${b}`)):_=ct.nil;return c.length&&(_=(0, ct.or)(_,...c.map(b=>(0, ct._)`${(0, _s.usePattern)(n,b)}.test(${v})`))),(0, ct.not)(_)}function m(v){e.code((0, ct._)`delete ${i}[${v}]`);}function g(v){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){m(v);return}if(t===false){n.setParams({additionalProperty:v}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, Es.alwaysValidSchema)(s,t)){let _=e.name("valid");u.removeAdditional==="failing"?(p(v,_,false),e.if((0, ct.not)(_),()=>{n.reset(),m(v);})):(p(v,_),o||e.if((0, ct.not)(_),()=>e.break()));}}function p(v,_,b){let d={keyword:"additionalProperties",dataProp:v,dataPropType:Es.Type.Str};b===false&&Object.assign(d,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(d,_);}}};jl.default=Pb;});var ym=C(Wl=>{Object.defineProperty(Wl,"__esModule",{value:true});var Fb=qn(),mm=Ze(),Bl=j(),gm=Ll(),Ob={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,parentSchema:r,data:i,it:a}=n;a.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&gm.default.code(new Fb.KeywordCxt(a,gm.default,"additionalProperties"));let s=(0, mm.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=Bl.mergeEvaluated.props(e,(0, Bl.toHash)(s),a.props));let o=s.filter(h=>!(0, Bl.alwaysValidSchema)(a,t[h]));if(o.length===0)return;let u=e.name("valid");for(let h of o)l(h)?c(h):(e.if((0, mm.propertyInData)(e,i,h,a.opts.ownProperties)),c(h),a.allErrors||e.else().var(u,true),e.endIf()),n.it.definedProperties.add(h),n.ok(u);function l(h){return a.opts.useDefaults&&!a.compositeRule&&t[h].default!==void 0}function c(h){n.subschema({keyword:"properties",schemaProp:h,dataProp:h},u);}}};Wl.default=Ob;});var Em=C(Ml=>{Object.defineProperty(Ml,"__esModule",{value:true});var Cm=Ze(),bs=T(),vm=j(),_m=j(),xb={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:e,schema:t,data:r,parentSchema:i,it:a}=n,{opts:s}=a,o=(0, Cm.allSchemaProperties)(t),u=o.filter(p=>(0, vm.alwaysValidSchema)(a,t[p]));if(o.length===0||u.length===o.length&&(!a.opts.unevaluated||a.props===true))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,c=e.name("valid");a.props!==true&&!(a.props instanceof bs.Name)&&(a.props=(0, _m.evaluatedPropsToName)(e,a.props));let{props:h}=a;f();function f(){for(let p of o)l&&m(p),a.allErrors?g(p):(e.var(c,true),g(p),e.if(c));}function m(p){for(let v in l)new RegExp(p).test(v)&&(0, vm.checkStrictMode)(a,`property ${v} matches pattern ${p} (use allowMatchingProperties)`);}function g(p){e.forIn("key",r,v=>{e.if((0, bs._)`${(0, Cm.usePattern)(n,p)}.test(${v})`,()=>{let _=u.includes(p);_||n.subschema({keyword:"patternProperties",schemaProp:p,dataProp:v,dataPropType:_m.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, bs._)`${h}[${v}]`,true):!_&&!a.allErrors&&e.if((0, bs.not)(c),()=>e.break());});});}}};Ml.default=xb;});var bm=C(Gl=>{Object.defineProperty(Gl,"__esModule",{value:true});var Nb=j(),Tb={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, Nb.alwaysValidSchema)(r,t)){n.fail();return}let i=e.name("valid");n.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},i),n.failResult(i,()=>n.reset(),()=>n.error());},error:{message:"must NOT be valid"}};Gl.default=Tb;});var Sm=C(Ul=>{Object.defineProperty(Ul,"__esModule",{value:true});var Ib=Ze(),kb={keyword:"anyOf",schemaType:"array",trackErrors:true,code:Ib.validateUnion,error:{message:"must match a schema in anyOf"}};Ul.default=kb;});var Dm=C(Hl=>{Object.defineProperty(Hl,"__esModule",{value:true});var Ss=T(),$b=j(),Rb={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, Ss._)`{passingSchemas: ${n.passing}}`},Vb={keyword:"oneOf",schemaType:"array",trackErrors:true,error:Rb,code(n){let{gen:e,schema:t,parentSchema:r,it:i}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&r.discriminator)return;let a=t,s=e.let("valid",false),o=e.let("passing",null),u=e.name("_valid");n.setParams({passing:o}),e.block(l),n.result(s,()=>n.reset(),()=>n.error(true));function l(){a.forEach((c,h)=>{let f;(0, $b.alwaysValidSchema)(i,c)?e.var(u,true):f=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, Ss._)`${u} && ${s}`).assign(s,false).assign(o,(0, Ss._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),f&&n.mergeEvaluated(f,Ss.Name);});});}}};Hl.default=Vb;});var wm=C(Kl=>{Object.defineProperty(Kl,"__esModule",{value:true});var qb=j(),jb={keyword:"allOf",schemaType:"array",code(n){let{gen:e,schema:t,it:r}=n;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((a,s)=>{if((0, qb.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};Kl.default=jb;});var Fm=C(zl=>{Object.defineProperty(zl,"__esModule",{value:true});var Ds=T(),Pm=j(),Lb={message:({params:n})=>(0, Ds.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, Ds._)`{failingKeyword: ${n.ifClause}}`},Bb={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:Lb,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, Pm.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=Am(r,"then"),a=Am(r,"else");if(!i&&!a)return;let s=e.let("valid",true),o=e.name("_valid");if(u(),n.reset(),i&&a){let c=e.let("ifClause");n.setParams({ifClause:c}),e.if(o,l("then",c),l("else",c));}else i?e.if(o,l("then")):e.if((0, Ds.not)(o),l("else"));n.pass(s,()=>n.error(true));function u(){let c=n.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},o);n.mergeEvaluated(c);}function l(c,h){return ()=>{let f=n.subschema({keyword:c},o);e.assign(s,o),n.mergeValidEvaluated(f,s),h?e.assign(h,(0, Ds._)`${c}`):n.setParams({ifClause:c});}}}};function Am(n,e){let t=n.schema[e];return t!==void 0&&!(0, Pm.alwaysValidSchema)(n,t)}zl.default=Bb;});var Om=C(Jl=>{Object.defineProperty(Jl,"__esModule",{value:true});var Wb=j(),Mb={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, Wb.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Jl.default=Mb;});var Xl=C(Zl=>{Object.defineProperty(Zl,"__esModule",{value:true});var Gb=Tl(),Ub=om(),Hb=Il(),Kb=lm(),zb=cm(),Jb=vs(),Zb=pm(),Xb=Ll(),Qb=ym(),Yb=Em(),eS=bm(),tS=Sm(),nS=Dm(),rS=wm(),iS=Fm(),sS=Om();function aS(n=false){let e=[eS.default,tS.default,nS.default,rS.default,iS.default,sS.default,Zb.default,Xb.default,Jb.default,Qb.default,Yb.default];return n?e.push(Ub.default,Kb.default):e.push(Gb.default,Hb.default),e.push(zb.default),e}Zl.default=aS;});var xm=C(Ql=>{Object.defineProperty(Ql,"__esModule",{value:true});var le=T(),oS={message:({schemaCode:n})=>(0, le.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, le._)`{format: ${n}}`},uS={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:oS,code(n,e){let{gen:t,data:r,$data:i,schema:a,schemaCode:s,it:o}=n,{opts:u,errSchemaPath:l,schemaEnv:c,self:h}=o;if(!u.validateFormats)return;i?f():m();function f(){let g=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),p=t.const("fDef",(0, le._)`${g}[${s}]`),v=t.let("fType"),_=t.let("format");t.if((0, le._)`typeof ${p} == "object" && !(${p} instanceof RegExp)`,()=>t.assign(v,(0, le._)`${p}.type || "string"`).assign(_,(0, le._)`${p}.validate`),()=>t.assign(v,(0, le._)`"string"`).assign(_,p)),n.fail$data((0, le.or)(b(),d()));function b(){return u.strictSchema===false?le.nil:(0, le._)`${s} && !${_}`}function d(){let E=c.$async?(0, le._)`(${p}.async ? await ${_}(${r}) : ${_}(${r}))`:(0, le._)`${_}(${r})`,y=(0, le._)`(typeof ${_} == "function" ? ${E} : ${_}.test(${r}))`;return (0, le._)`${_} && ${_} !== true && ${v} === ${e} && !${y}`}}function m(){let g=h.formats[a];if(!g){b();return}if(g===true)return;let[p,v,_]=d(g);p===e&&n.pass(E());function b(){if(u.strictSchema===false){h.logger.warn(y());return}throw new Error(y());function y(){return `unknown format "${a}" ignored in schema at path "${l}"`}}function d(y){let D=y instanceof RegExp?(0, le.regexpCode)(y):u.code.formats?(0, le._)`${u.code.formats}${(0, le.getProperty)(a)}`:void 0,w=t.scopeValue("formats",{key:a,ref:y,code:D});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0, le._)`${w}.validate`]:["string",y,w]}function E(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!c.$async)throw new Error("async format in sync schema");return (0, le._)`await ${_}(${r})`}return typeof v=="function"?(0, le._)`${_}(${r})`:(0, le._)`${_}.test(${r})`}}}};Ql.default=uS;});var ec=C(Yl=>{Object.defineProperty(Yl,"__esModule",{value:true});var lS=xm(),cS=[lS.default];Yl.default=cS;});var tc=C(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.contentVocabulary=Gn.metadataVocabulary=void 0;Gn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Gn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var Tm=C(nc=>{Object.defineProperty(nc,"__esModule",{value:true});var hS=pl(),dS=xl(),fS=Xl(),pS=ec(),Nm=tc(),mS=[hS.default,dS.default,(0, fS.default)(),pS.default,Nm.metadataVocabulary,Nm.contentVocabulary];nc.default=mS;});var km=C(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.DiscrError=void 0;var Im;(function(n){n.Tag="tag",n.Mapping="mapping";})(Im||(ws.DiscrError=Im={}));});var sc=C(ic=>{Object.defineProperty(ic,"__esModule",{value:true});var Un=T(),rc=km(),$m=qr(),gS=jn(),yS=j(),CS={message:({params:{discrError:n,tagName:e}})=>n===rc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Un._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},vS={keyword:"discriminator",type:"object",schemaType:"object",error:CS,code(n){let{gen:e,data:t,schema:r,parentSchema:i,it:a}=n,{oneOf:s}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let o=r.propertyName;if(typeof o!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=e.let("valid",false),l=e.const("tag",(0, Un._)`${t}${(0, Un.getProperty)(o)}`);e.if((0, Un._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:rc.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let m=f();e.if(false);for(let g in m)e.elseIf((0, Un._)`${l} === ${g}`),e.assign(u,h(m[g]));e.else(),n.error(false,{discrError:rc.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(m){let g=e.name("valid"),p=n.subschema({keyword:"oneOf",schemaProp:m},g);return n.mergeEvaluated(p,Un.Name),g}function f(){var m;let g={},p=_(i),v=true;for(let E=0;E<s.length;E++){let y=s[E];if(y?.$ref&&!(0, yS.schemaHasRulesButRef)(y,a.self.RULES)){let w=y.$ref;if(y=$m.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,w),y instanceof $m.SchemaEnv&&(y=y.schema),y===void 0)throw new gS.default(a.opts.uriResolver,a.baseId,w)}let D=(m=y?.properties)===null||m===void 0?void 0:m[o];if(typeof D!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);v=v&&(p||_(y)),b(D,E);}if(!v)throw new Error(`discriminator: "${o}" must be required`);return g;function _({required:E}){return Array.isArray(E)&&E.includes(o)}function b(E,y){if(E.const)d(E.const,y);else if(E.enum)for(let D of E.enum)d(D,y);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function d(E,y){if(typeof E!="string"||E in g)throw new Error(`discriminator: "${o}" values must be unique strings`);g[E]=y;}}}};ic.default=vS;});var Rm=C((mx,_S)=>{_S.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:true,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:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},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:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},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:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},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:true};});var qm=C((ne,ac)=>{Object.defineProperty(ne,"__esModule",{value:true});ne.MissingRefError=ne.ValidationError=ne.CodeGen=ne.Name=ne.nil=ne.stringify=ne.str=ne._=ne.KeywordCxt=ne.Ajv=void 0;var ES=hl(),bS=Tm(),SS=sc(),Vm=Rm(),DS=["/properties"],As="http://json-schema.org/draft-07/schema",Hn=class extends ES.default{_addVocabularies(){super._addVocabularies(),bS.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(SS.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Vm,DS):Vm;this.addMetaSchema(e,As,false),this.refs["http://json-schema.org/schema"]=As;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(As)?As:void 0)}};ne.Ajv=Hn;ac.exports=ne=Hn;ac.exports.Ajv=Hn;Object.defineProperty(ne,"__esModule",{value:true});ne.default=Hn;var wS=qn();Object.defineProperty(ne,"KeywordCxt",{enumerable:true,get:function(){return wS.KeywordCxt}});var Kn=T();Object.defineProperty(ne,"_",{enumerable:true,get:function(){return Kn._}});Object.defineProperty(ne,"str",{enumerable:true,get:function(){return Kn.str}});Object.defineProperty(ne,"stringify",{enumerable:true,get:function(){return Kn.stringify}});Object.defineProperty(ne,"nil",{enumerable:true,get:function(){return Kn.nil}});Object.defineProperty(ne,"Name",{enumerable:true,get:function(){return Kn.Name}});Object.defineProperty(ne,"CodeGen",{enumerable:true,get:function(){return Kn.CodeGen}});var AS=Vr();Object.defineProperty(ne,"ValidationError",{enumerable:true,get:function(){return AS.default}});var PS=jn();Object.defineProperty(ne,"MissingRefError",{enumerable:true,get:function(){return PS.default}});});var uc=C(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.dynamicAnchor=void 0;var oc=T(),FS=Je(),jm=qr(),OS=fs(),xS={keyword:"$dynamicAnchor",schemaType:"string",code:n=>Lm(n,n.schema)};function Lm(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, oc._)`${FS.default.dynamicAnchors}${(0, oc.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:NS(n);t.if((0, oc._)`!${i}`,()=>t.assign(i,a));}Yr.dynamicAnchor=Lm;function NS(n){let{schemaEnv:e,schema:t,self:r}=n.it,{root:i,baseId:a,localRefs:s,meta:o}=e.root,{schemaId:u}=r.opts,l=new jm.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return jm.compileSchema.call(r,l),(0, OS.getValidate)(n,l)}Yr.default=xS;});var lc=C(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.dynamicRef=void 0;var Bm=T(),TS=Je(),Wm=fs(),IS={keyword:"$dynamicRef",schemaType:"string",code:n=>Mm(n,n.schema)};function Mm(n,e){let{gen:t,keyword:r,it:i}=n;if(e[0]!=="#")throw new Error(`"${r}" only supports hash fragment reference`);let a=e.slice(1);if(i.allErrors)s();else {let u=t.let("valid",false);s(u),n.ok(u);}function s(u){if(i.schemaEnv.root.dynamicAnchors[a]){let l=t.let("_v",(0, Bm._)`${TS.default.dynamicAnchors}${(0, Bm.getProperty)(a)}`);t.if(l,o(l,u),o(i.validateName,u));}else o(i.validateName,u)();}function o(u,l){return l?()=>t.block(()=>{(0, Wm.callRef)(n,u),t.let(l,true);}):()=>(0, Wm.callRef)(n,u)}}ei.dynamicRef=Mm;ei.default=IS;});var Gm=C(cc=>{Object.defineProperty(cc,"__esModule",{value:true});var kS=uc(),$S=j(),RS={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, kS.dynamicAnchor)(n,""):(0, $S.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};cc.default=RS;});var Um=C(hc=>{Object.defineProperty(hc,"__esModule",{value:true});var VS=lc(),qS={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, VS.dynamicRef)(n,n.schema)};hc.default=qS;});var Hm=C(dc=>{Object.defineProperty(dc,"__esModule",{value:true});var jS=uc(),LS=lc(),BS=Gm(),WS=Um(),MS=[jS.default,LS.default,BS.default,WS.default];dc.default=MS;});var zm=C(fc=>{Object.defineProperty(fc,"__esModule",{value:true});var Km=vs(),GS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Km.error,code:n=>(0, Km.validatePropertyDeps)(n)};fc.default=GS;});var Jm=C(pc=>{Object.defineProperty(pc,"__esModule",{value:true});var US=vs(),HS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, US.validateSchemaDeps)(n)};pc.default=HS;});var Zm=C(mc=>{Object.defineProperty(mc,"__esModule",{value:true});var KS=j(),zS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, KS.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};mc.default=zS;});var Xm=C(gc=>{Object.defineProperty(gc,"__esModule",{value:true});var JS=zm(),ZS=Jm(),XS=Zm(),QS=[JS.default,ZS.default,XS.default];gc.default=QS;});var Ym=C(yc=>{Object.defineProperty(yc,"__esModule",{value:true});var Gt=T(),Qm=j(),YS=Je(),eD={message:"must NOT have unevaluated properties",params:({params:n})=>(0, Gt._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},tD={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:eD,code(n){let{gen:e,schema:t,data:r,errsCount:i,it:a}=n;if(!i)throw new Error("ajv implementation error");let{allErrors:s,props:o}=a;o instanceof Gt.Name?e.if((0, Gt._)`${o} !== true`,()=>e.forIn("key",r,h=>e.if(l(o,h),()=>u(h)))):o!==true&&e.forIn("key",r,h=>o===void 0?u(h):e.if(c(o,h),()=>u(h))),a.props=true,n.ok((0, Gt._)`${i} === ${YS.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, Qm.alwaysValidSchema)(a,t)){let f=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:Qm.Type.Str},f),s||e.if((0, Gt.not)(f),()=>e.break());}}function l(h,f){return (0, Gt._)`!${h} || !${h}[${f}]`}function c(h,f){let m=[];for(let g in h)h[g]===true&&m.push((0, Gt._)`${f} !== ${g}`);return (0, Gt.and)(...m)}}};yc.default=tD;});var tg=C(Cc=>{Object.defineProperty(Cc,"__esModule",{value:true});var gn=T(),eg=j(),nD={message:({params:{len:n}})=>(0, gn.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, gn._)`{limit: ${n}}`},rD={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:nD,code(n){let{gen:e,schema:t,data:r,it:i}=n,a=i.items||0;if(a===true)return;let s=e.const("len",(0, gn._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, gn._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, eg.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, gn._)`${s} <= ${a}`);e.if((0, gn.not)(u),()=>o(u,a)),n.ok(u);}i.items=true;function o(u,l){e.forRange("i",l,s,c=>{n.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:eg.Type.Num},u),i.allErrors||e.if((0, gn.not)(u),()=>e.break());});}}};Cc.default=rD;});var ng=C(vc=>{Object.defineProperty(vc,"__esModule",{value:true});var iD=Ym(),sD=tg(),aD=[iD.default,sD.default];vc.default=aD;});var ig=C(_c=>{Object.defineProperty(_c,"__esModule",{value:true});var oD=pl(),uD=xl(),lD=Xl(),cD=Hm(),hD=Xm(),dD=ng(),fD=ec(),rg=tc(),pD=[cD.default,oD.default,uD.default,(0, lD.default)(true),fD.default,rg.metadataVocabulary,rg.contentVocabulary,hD.default,dD.default];_c.default=pD;});var sg=C((Ox,mD)=>{mD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:true,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:true,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:true},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:true}}};});var ag=C((xx,gD)=>{gD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":true},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}};});var og=C((Nx,yD)=>{yD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}};});var ug=C((Tx,CD)=>{CD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":true},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}};});var lg=C((Ix,vD)=>{vD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":true},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}};});var cg=C((kx,_D)=>{_D.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}};});var hg=C(($x,ED)=>{ED.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:true,deprecated:{type:"boolean",default:false},readOnly:{type:"boolean",default:false},writeOnly:{type:"boolean",default:false},examples:{type:"array",items:true}}};});var dg=C((Rx,bD)=>{bD.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":true},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:true}]},const:true,enum:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}}};});var fg=C(Ec=>{Object.defineProperty(Ec,"__esModule",{value:true});var SD=sg(),DD=ag(),wD=og(),AD=ug(),PD=lg(),FD=cg(),OD=hg(),xD=dg(),ND=["/properties"];function TD(n){return [SD,DD,wD,AD,PD,e(this,FD),OD,e(this,xD)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,ND):r}}Ec.default=TD;});var pg=C((re,Sc)=>{Object.defineProperty(re,"__esModule",{value:true});re.MissingRefError=re.ValidationError=re.CodeGen=re.Name=re.nil=re.stringify=re.str=re._=re.KeywordCxt=re.Ajv2020=void 0;var ID=hl(),kD=ig(),$D=sc(),RD=fg(),bc="https://json-schema.org/draft/2020-12/schema",zn=class extends ID.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),kD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($D.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(RD.default.call(this,e),this.refs["http://json-schema.org/schema"]=bc);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bc)?bc:void 0)}};re.Ajv2020=zn;Sc.exports=re=zn;Sc.exports.Ajv2020=zn;Object.defineProperty(re,"__esModule",{value:true});re.default=zn;var VD=qn();Object.defineProperty(re,"KeywordCxt",{enumerable:true,get:function(){return VD.KeywordCxt}});var Jn=T();Object.defineProperty(re,"_",{enumerable:true,get:function(){return Jn._}});Object.defineProperty(re,"str",{enumerable:true,get:function(){return Jn.str}});Object.defineProperty(re,"stringify",{enumerable:true,get:function(){return Jn.stringify}});Object.defineProperty(re,"nil",{enumerable:true,get:function(){return Jn.nil}});Object.defineProperty(re,"Name",{enumerable:true,get:function(){return Jn.Name}});Object.defineProperty(re,"CodeGen",{enumerable:true,get:function(){return Jn.CodeGen}});var qD=Vr();Object.defineProperty(re,"ValidationError",{enumerable:true,get:function(){return qD.default}});var jD=jn();Object.defineProperty(re,"MissingRefError",{enumerable:true,get:function(){return jD.default}});});var wc=C(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.CompilerOptions=void 0;var Dc=class{constructor(e=null,t=[],r=false,i=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=r,this.errorHandler=i,this.fileHandler=a;}};Ps.CompilerOptions=Dc;});var mg=C(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.DebugSourceRange=void 0;var Ac=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};Fs.DebugSourceRange=Ac;});var ti=C(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.ErrorType=void 0;var gg;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(gg||(Os.ErrorType=gg={}));});var yg=C(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.Argument=void 0;var Pc=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};xs.Argument=Pc;});var J=C(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.filterUndef=pe.isEquatable=pe.nullIfUndefined=pe.asINamedContentOrNull=pe.asBooleanOrThrows=pe.asNumberOrThrows=pe.asOrThrows=pe.asOrNull=void 0;function LD(n,e){return n instanceof e?Cg(n):null}pe.asOrNull=LD;function BD(n,e){if(n instanceof e)return Cg(n);throw new Error(`${n} is not of type ${e}`)}pe.asOrThrows=BD;function WD(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}pe.asNumberOrThrows=WD;function MD(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}pe.asBooleanOrThrows=MD;function GD(n){return n.hasValidName&&n.name?n:null}pe.asINamedContentOrNull=GD;function UD(n){return typeof n>"u"?null:n}pe.nullIfUndefined=UD;function HD(n){return typeof n=="object"&&typeof n.Equals=="function"}pe.isEquatable=HD;function Cg(n,e){return n}function KD(n){return n!=null}pe.filterUndef=KD;});var se=C(Ns=>{Object.defineProperty(Ns,"__esModule",{value:true});Ns.ParsedObject=void 0;var vg=J(),Fc=class{constructor(){this._alreadyHadError=false,this._alreadyHadWarning=false,this._debugMetadata=null,this._runtimeObject=null,this.content=[],this.parent=null,this.GetType=()=>this.typeName,this.AddContent=e=>{this.content===null&&(this.content=[]);let t=Array.isArray(e)?e:[e];for(let r of t)r.hasOwnProperty("parent")&&(r.parent=this),this.content.push(r);if(!Array.isArray(e))return e},this.InsertContent=(e,t)=>(this.content===null&&(this.content=[]),t.parent=this,this.content.splice(e,0,t),t),this.Find=e=>(t=null)=>{let r=(0, vg.asOrNull)(this,e);if(r!==null&&(t===null||t(r)===true))return r;if(this.content===null)return null;for(let i of this.content){let a=i.Find&&i.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,r)=>{let i=Array.isArray(r)?r:[],a=(0, vg.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&i.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,i);return i},this.Warning=(e,t=null)=>{this.Error(e,t,true);};}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get hasOwnDebugMetadata(){return !!this.debugMetadata}get typeName(){return "ParsedObject"}get story(){let e=this;for(;e.parent;)e=e.parent;return e}get runtimeObject(){return this._runtimeObject||(this._runtimeObject=this.GenerateRuntimeObject(),this._runtimeObject&&(this._runtimeObject.debugMetadata=this.debugMetadata)),this._runtimeObject}set runtimeObject(e){this._runtimeObject=e;}get runtimePath(){if(!this.runtimeObject.path)throw new Error;return this.runtimeObject.path}get containerForCounting(){return this.runtimeObject}get ancestry(){let e=[],t=this.parent;for(;t;)e.push(t),t=t.parent;return e=e.reverse(),e}ResolveReferences(e){if(this.content!==null)for(let t of this.content)t.ResolveReferences(e);}Error(e,t=null,r=false){if(t===null&&(t=this),!(t._alreadyHadError&&!r||t._alreadyHadWarning&&r)){if(this.parent)this.parent.Error(e,t,r);else throw new Error(`No parent object to send error to: ${e}`);r?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};Ns.ParsedObject=Fc;});var Is=C(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.AuthorWarning=void 0;var zD=se(),Oc=class extends zD.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Ts.AuthorWarning=Oc;});var Be=C(ni=>{Object.defineProperty(ni,"__esModule",{value:true});ni.Path=void 0;var Zn=class n{constructor(){if(this._components=[],this._componentsString=null,this._isRelative=false,typeof arguments[0]=="string"){let e=arguments[0];this.componentsString=e;}else if(arguments[0]instanceof n.Component&&arguments[1]instanceof n){let e=arguments[0],t=arguments[1];this._components.push(e),this._components=this._components.concat(t._components);}else if(arguments[0]instanceof Array){let e=arguments[0],t=!!arguments[1];this._components=this._components.concat(e),this._isRelative=t;}}get isRelative(){return this._isRelative}get componentCount(){return this._components.length}get head(){return this._components.length>0?this._components[0]:null}get tail(){if(this._components.length>=2){let e=this._components.slice(1,this._components.length);return new n(e)}else return n.self}get length(){return this._components.length}get lastComponent(){let e=this._components.length-1;return e>=0?this._components[e]:null}get containsNamedComponent(){for(let e=0,t=this._components.length;e<t;e++)if(!this._components[e].isIndex)return true;return false}static get self(){let e=new n;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new n,r=0;for(let i=0;i<e._components.length&&e._components[i].isParent;++i)r++;for(let i=0;i<this._components.length-r;++i)t._components.push(this._components[i]);for(let i=r;i<e._components.length;++i)t._components.push(e._components[i]);return t}get componentsString(){return this._componentsString==null&&(this._componentsString=this._components.join("."),this.isRelative&&(this._componentsString="."+this._componentsString)),this._componentsString}set componentsString(e){if(this._components.length=0,this._componentsString=e,this._componentsString==null||this._componentsString=="")return;this._componentsString[0]=="."&&(this._isRelative=true,this._componentsString=this._componentsString.substring(1));let t=this._componentsString.split(".");for(let r of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(r)?this._components.push(new n.Component(parseInt(r))):this._components.push(new n.Component(r));}toString(){return this.componentsString}Equals(e){if(e==null||e._components.length!=this._components.length||e.isRelative!=this.isRelative)return false;for(let t=0,r=e._components.length;t<r;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new n;return t._components.push(...this._components),t._components.push(e),t}};ni.Path=Zn;Zn.parentId="^";(function(n){class e{constructor(r){this.index=-1,this.name=null,typeof r=="string"?this.name=r:this.index=r;}get isIndex(){return this.index>=0}get isParent(){return this.name==n.parentId}static ToParent(){return new e(n.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(r){return r!=null&&r.isIndex==this.isIndex?this.isIndex?this.index==r.index:this.name==r.name:false}}n.Component=e;})(Zn||(ni.Path=Zn={}));});var ri=C(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.Debug=void 0;var _g;(function(n){function e(r,i,a){t(r instanceof i,a);}n.AssertType=e;function t(r,i){if(!r)throw typeof i<"u"&&console.warn(i),console.trace&&console.trace(),new Error("")}n.Assert=t;})(_g||(ks.Debug=_g={}));});var Ae=C(Xn=>{Object.defineProperty(Xn,"__esModule",{value:true});Xn.throwNullException=Xn.NullException=void 0;var $s=class extends Error{};Xn.NullException=$s;function JD(n){throw new $s(`${n} is null or undefined`)}Xn.throwNullException=JD;});var We=C(Vs=>{Object.defineProperty(Vs,"__esModule",{value:true});Vs.InkObject=void 0;var Qn=Be(),ii=ce(),xc=ri(),Yn=J(),Rs=Ae(),Nc=class{constructor(){this.parent=null,this._debugMetadata=null,this._path=null;}get debugMetadata(){return this._debugMetadata===null&&this.parent?this.parent.debugMetadata:this._debugMetadata}set debugMetadata(e){this._debugMetadata=e;}get ownDebugMetadata(){return this._debugMetadata}DebugLineNumberOfPath(e){if(e===null)return null;let t=this.rootContentContainer;if(t){let r=t.ContentAtPath(e).obj;if(r){let i=r.debugMetadata;if(i!==null)return i.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new Qn.Path;else {let e=[],t=this,r=(0, Yn.asOrNull)(t.parent,ii.Container);for(;r!==null;){let i=(0, Yn.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Rs.throwNullException)("namedChild.name");e.unshift(new Qn.Path.Component(i.name));}else e.unshift(new Qn.Path.Component(r.content.indexOf(t)));t=r,r=(0, Yn.asOrNull)(r.parent,ii.Container);}this._path=new Qn.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Rs.throwNullException)("path");if(e.isRelative){let t=(0, Yn.asOrNull)(this,ii.Container);return t===null&&(xc.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, Yn.asOrNull)(this.parent,ii.Container),xc.Debug.Assert(t!==null,"Expected parent to be a container"),xc.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Rs.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Rs.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,r=Math.min(e.length,t.length),i=-1;for(let u=0;u<r;++u){let l=t.GetComponent(u),c=e.GetComponent(u);if(l.Equals(c))i=u;else break}if(i==-1)return e;let a=t.componentCount-1-i,s=[];for(let u=0;u<a;++u)s.push(Qn.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new Qn.Path(s,true)}CompactPathString(e){let t=null,r=null;return e.isRelative?(r=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(r=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),r.length<t.length?r:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, Yn.asOrNull)(e,ii.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,r){e[t]&&(e[t]=null),e[t]=r,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};Vs.InkObject=Nc;});var yn=C(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.StringBuilder=void 0;var Tc=class{constructor(e){e=typeof e<"u"?e.toString():"",this.string=e;}get Length(){return this.string.length}Append(e){e!==null&&(this.string+=e);}AppendLine(e){typeof e<"u"&&this.Append(e),this.string+=`
9
+ `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(r,i)=>typeof t[i]<"u"?t[i]:r);}toString(){return this.string}Clear(){this.string="";}};qs.StringBuilder=Tc;});var Ge=C(er=>{Object.defineProperty(er,"__esModule",{value:true});er.InkList=er.InkListItem=void 0;var gt=Ae(),ZD=yn(),Me=class n{constructor(){if(this.originName=null,this.itemName=null,typeof arguments[1]<"u"){let e=arguments[0],t=arguments[1];this.originName=e,this.itemName=t;}else if(arguments[0]){let t=arguments[0].toString().split(".");this.originName=t[0],this.itemName=t[1];}}static get Null(){return new n(null,null)}get isNull(){return this.originName==null&&this.itemName==null}get fullName(){return (this.originName!==null?this.originName:"?")+"."+this.itemName}toString(){return this.fullName}Equals(e){if(e instanceof n){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new n(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!n.isLikeInkListItem(t))return n.Null;let r=t;return new n(r.originName,r.itemName)}static isLikeInkListItem(e){return !(typeof e!="object"||!e.hasOwnProperty("originName")||!e.hasOwnProperty("itemName")||typeof e.originName!="string"&&typeof e.originName!==null||typeof e.itemName!="string"&&typeof e.itemName!==null)}};er.InkListItem=Me;var Ic=class n extends Map{constructor(){if(super(arguments[0]instanceof n?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof n){let e=arguments[0],t=e.originNames;t!==null&&(this._originNames=t.slice()),e.origins!==null&&(this.origins=e.origins.slice());}else if(typeof arguments[0]=="string"){let e=arguments[0],t=arguments[1];if(this.SetInitialOriginName(e),t.listDefinitions===null)return (0, gt.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, gt.throwNullException)("def.result");this.origins=[r.result];}else throw new Error("InkList origin could not be found in story when constructing new list: "+e)}else if(typeof arguments[0]=="object"&&arguments[0].hasOwnProperty("Key")&&arguments[0].hasOwnProperty("Value")){let e=arguments[0];this.Add(e.Key,e.Value);}}static FromString(e,t){var r;if(e==null||e=="")return new n;let i=(r=t.listDefinitions)===null||r===void 0?void 0:r.FindSingleItemListWithName(e);if(i)return i.value===null?(0, gt.throwNullException)("listValue.value"):new n(i.value);throw new Error("Could not find the InkListItem from the string '"+e+"' to create an InkList because it doesn't exist in the original list definition in ink.")}AddItem(e,t=null){if(e instanceof Me){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, gt.throwNullException)("this.origins");for(let i of this.origins)if(i.name==r.originName){let a=i.TryGetValueForItem(r,0);if(a.exists){this.Add(r,a.result);return}else throw new Error("Could not add the item "+r+" to this list because it doesn't exist in the original list definition in ink.")}throw new Error("Failed to add item to list because the item was from a new list definition that wasn't previously known to this list. Only items from previously known lists can be used, so that the int value can be found.")}else if(e!==null){let r=e,i=null;if(this.origins===null)return (0, gt.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, gt.throwNullException)("itemName");if(a.ContainsItemWithName(r)){if(i!=null)throw new Error("Could not add the item "+r+" to this list because it could come from either "+a.name+" or "+i.name);i=a;}}if(i==null){if(t==null)throw new Error("Could not add the item "+r+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=n.FromString(r,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new Me(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(Me.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let r=e.serialized();if(this.has(r))throw new Error(`The Map already contains an entry for ${e}`);this.set(r,t);}Remove(e){return this.delete(e.serialized())}get Count(){return this.size}get originOfMaxItem(){if(this.origins==null)return null;let e=this.maxItem.Key.originName,t=null;return this.origins.every(r=>r.name==e?(t=r,false):true),t}get originNames(){if(this.Count>0){this._originNames==null&&this.Count>0?this._originNames=[]:(this._originNames||(this._originNames=[]),this._originNames.length=0);for(let[e]of this){let t=Me.fromSerializedKey(e);if(t.originName===null)return (0, gt.throwNullException)("item.originName");this._originNames.push(t.originName);}}return this._originNames}SetInitialOriginName(e){this._originNames=[e];}SetInitialOriginNames(e){e==null?this._originNames=null:this._originNames=e.slice();}get maxItem(){let e={Key:Me.Null,Value:0};for(let[t,r]of this){let i=Me.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:Me.Null,Value:0};for(let[t,r]of this){let i=Me.fromSerializedKey(t);(e.Key.isNull||r<e.Value)&&(e={Key:i,Value:r});}return e}get inverse(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Me.fromSerializedKey(r);this.ContainsKey(a)||e.Add(a,i);}return e}get all(){let e=new n;if(this.origins!=null)for(let t of this.origins)for(let[r,i]of t.items){let a=Me.fromSerializedKey(r);e.set(a.serialized(),i);}return e}Union(e){let t=new n(this);for(let[r,i]of e)t.set(r,i);return t}Intersect(e){let t=new n;for(let[r,i]of this)e.has(r)&&t.set(r,i);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new n(this);for(let[r]of e)t.delete(r);return t}Contains(e){if(typeof e=="string")return this.ContainsItemNamed(e);let t=e;if(t.size==0||this.size==0)return false;for(let[r]of t)if(!this.has(r))return false;return true}GreaterThan(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>e.maxItem.Value}GreaterThanOrEquals(e){return this.Count==0?false:e.Count==0?true:this.minItem.Value>=e.minItem.Value&&this.maxItem.Value>=e.maxItem.Value}LessThan(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<e.minItem.Value}LessThanOrEquals(e){return e.Count==0?false:this.Count==0?true:this.maxItem.Value<=e.maxItem.Value&&this.minItem.Value<=e.minItem.Value}MaxAsList(){return this.Count>0?new n(this.maxItem):new n}MinAsList(){return this.Count>0?new n(this.minItem):new n}ListWithSubRange(e,t){if(this.Count==0)return new n;let r=this.orderedItems,i=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?i=e:e instanceof n&&e.Count>0&&(i=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof n&&t.Count>0&&(a=t.maxItem.Value);let s=new n;s.SetInitialOriginNames(this.originNames);for(let o of r)o.Value>=i&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof n)||e.Count!=this.Count)return false;for(let[t]of this)if(!e.has(t))return false;return true}get orderedItems(){let e=new Array;for(let[t,r]of this){let i=Me.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, gt.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, gt.throwNullException)("y.Key.originName"):t.Value==r.Value?t.Key.originName.localeCompare(r.Key.originName):t.Value<r.Value?-1:t.Value>r.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new ZD.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, gt.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};er.InkList=Ic;});var si=C(js=>{Object.defineProperty(js,"__esModule",{value:true});js.StoryException=void 0;var kc=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};js.StoryException=kc;});var tr=C(Ut=>{Object.defineProperty(Ut,"__esModule",{value:true});Ut.tryParseFloat=Ut.tryParseInt=Ut.tryGetValueFromMap=void 0;function XD(n,e,t){if(n===null)return {result:t,exists:false};let r=n.get(e);return typeof r>"u"?{result:t,exists:false}:{result:r,exists:true}}Ut.tryGetValueFromMap=XD;function QD(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ut.tryParseInt=QD;function YD(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Ut.tryParseFloat=YD;});var ae=C(oe=>{Object.defineProperty(oe,"__esModule",{value:true});oe.ValueType=oe.ListValue=oe.VariablePointerValue=oe.DivertTargetValue=oe.StringValue=oe.FloatValue=oe.IntValue=oe.BoolValue=oe.Value=oe.AbstractValue=void 0;var Eg=We(),bg=Be(),Cn=Ge(),ew=si(),ai=J(),Sg=tr(),Ye=Ae(),Ls=class n extends Eg.InkObject{static Create(e,t){if(t){if(t===ie.Int&&Number.isInteger(Number(e)))return new Ct(Number(e));if(t===ie.Float&&!isNaN(e))return new vt(Number(e))}if(typeof e=="boolean")return new nr(!!e);if(typeof e=="string")return new Tt(String(e));if(Number.isInteger(Number(e)))return new Ct(Number(e));if(isNaN(e)){if(e instanceof bg.Path)return new Bs((0, ai.asOrThrows)(e,bg.Path));if(e instanceof Cn.InkList)return new Ws((0, ai.asOrThrows)(e,Cn.InkList))}else return new vt(Number(e));return null}Copy(){return (0, ai.asOrThrows)(n.Create(this.valueObject),Eg.InkObject)}BadCastException(e){return new ew.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};oe.AbstractValue=Ls;var yt=class extends Ls{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value.toString()}};oe.Value=yt;var nr=class extends yt{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return ie.Bool}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Int)return new Ct(this.value?1:0);if(e==ie.Float)return new vt(this.value?1:0);if(e==ie.String)return new Tt(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};oe.BoolValue=nr;var Ct=class extends yt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ie.Int}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Bool)return new nr(this.value!==0);if(e==ie.Float)return new vt(this.value);if(e==ie.String)return new Tt(""+this.value);throw this.BadCastException(e)}};oe.IntValue=Ct;var vt=class extends yt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ie.Float}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ie.Bool)return new nr(this.value!==0);if(e==ie.Int)return new Ct(this.value);if(e==ie.String)return new Tt(""+this.value);throw this.BadCastException(e)}};oe.FloatValue=vt;var Tt=class extends yt{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Ye.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return ie.String}get isTruthy(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value.length>0}get isNewline(){return this._isNewline}get isInlineWhitespace(){return this._isInlineWhitespace}get isNonWhitespace(){return !this.isNewline&&!this.isInlineWhitespace}Cast(e){if(e==this.valueType)return this;if(e==ie.Int){let t=(0, Sg.tryParseInt)(this.value);if(t.exists)return new Ct(t.result);throw this.BadCastException(e)}if(e==ie.Float){let t=(0, Sg.tryParseFloat)(this.value);if(t.exists)return new vt(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};oe.StringValue=Tt;var Bs=class extends yt{constructor(e=null){super(e);}get valueType(){return ie.DivertTarget}get targetPath(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value}set targetPath(e){this.value=e;}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a divert target")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "DivertTargetValue("+this.targetPath+")"}};oe.DivertTargetValue=Bs;var $c=class n extends yt{constructor(e,t=-1){super(e),this._contextIndex=t;}get contextIndex(){return this._contextIndex}set contextIndex(e){this._contextIndex=e;}get variableName(){return this.value===null?(0, Ye.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return ie.VariablePointer}get isTruthy(){throw new Error("Shouldn't be checking the truthiness of a variable pointer")}Cast(e){if(e==this.valueType)return this;throw this.BadCastException(e)}toString(){return "VariablePointerValue("+this.variableName+")"}Copy(){return new n(this.variableName,this.contextIndex)}};oe.VariablePointerValue=$c;var Ws=class n extends yt{get isTruthy(){return this.value===null?(0, Ye.throwNullException)("this.value"):this.value.Count>0}get valueType(){return ie.List}Cast(e){if(this.value===null)return (0, Ye.throwNullException)("Value.value");if(e==ie.Int){let t=this.value.maxItem;return t.Key.isNull?new Ct(0):new Ct(t.Value)}else if(e==ie.Float){let t=this.value.maxItem;return t.Key.isNull?new vt(0):new vt(t.Value)}else if(e==ie.String){let t=this.value.maxItem;return t.Key.isNull?new Tt(""):new Tt(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new Cn.InkList:e instanceof Cn.InkList?this.value=new Cn.InkList(e):e instanceof Cn.InkListItem&&typeof t=="number"&&(this.value=new Cn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, ai.asOrNull)(e,n),i=(0, ai.asOrNull)(t,n);if(i&&i.value===null)return (0, Ye.throwNullException)("newList.value");if(r&&r.value===null)return (0, Ye.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};oe.ListValue=Ws;var ie;(function(n){n[n.Bool=-1]="Bool",n[n.Int=0]="Int",n[n.Float=1]="Float",n[n.List=2]="List",n[n.String=3]="String",n[n.DivertTarget=4]="DivertTarget",n[n.VariablePointer=5]="VariablePointer";})(ie||(oe.ValueType=ie={}));});var Dg=C(Ms=>{Object.defineProperty(Ms,"__esModule",{value:true});Ms.SearchResult=void 0;var tw=ce(),Rc=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof tw.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};Ms.SearchResult=Rc;});var ce=C(ui=>{Object.defineProperty(ui,"__esModule",{value:true});ui.Container=void 0;var nw=ae(),wg=Ae(),rw=yn(),rr=We(),iw=Dg(),Ag=Be(),Pg=ri(),sw=tr(),Ht=J(),oi=class n extends rr.InkObject{constructor(){super(...arguments),this.name=null,this._content=[],this.namedContent=new Map,this.visitsShouldBeCounted=false,this.turnIndexShouldBeCounted=false,this.countingAtStartOnly=false,this._pathToFirstLeafContent=null;}get hasValidName(){return this.name!=null&&this.name.length>0}get content(){return this._content}set content(e){this.AddContent(e);}get namedOnlyContent(){let e=new Map;for(let[t,r]of this.namedContent){let i=(0, Ht.asOrThrows)(r,rr.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, Ht.asINamedContentOrNull)(t);r!=null&&r.hasValidName&&e.delete(r.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[r]of t)this.namedContent.delete(r);if(e!=null)for(let[,r]of e){let i=(0, Ht.asINamedContentOrNull)(r);i!=null&&this.AddToNamedContentOnly(i);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=n.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=n.CountFlags.Turns),this.countingAtStartOnly&&(e|=n.CountFlags.CountStartOnly),e==n.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&n.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&n.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&n.CountFlags.CountStartOnly)>0&&(this.countingAtStartOnly=true);}get pathToFirstLeafContent(){return this._pathToFirstLeafContent==null&&(this._pathToFirstLeafContent=this.path.PathByAppendingPath(this.internalPathToFirstLeafContent)),this._pathToFirstLeafContent}get internalPathToFirstLeafContent(){let e=[],t=this;for(;t instanceof n;)t.content.length>0&&(e.push(new Ag.Path.Component(0)),t=t.content[0]);return new Ag.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let r of t)this.AddContent(r);}else {let t=e;if(this._content.push(t),t.parent)throw new Error("content is already in "+t.parent);t.parent=this,this.TryAddNamedContent(t);}}TryAddNamedContent(e){let t=(0, Ht.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Pg.Debug.AssertType(e,rr.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Ht.asOrThrows)(e,rr.InkObject);if(t.parent=this,e.name===null)return (0, wg.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new iw.SearchResult;i.approximate=false;let a=this,s=this;for(let o=t;o<r;++o){let u=e.GetComponent(o);if(a==null){i.approximate=true;break}let l=a.ContentWithPathComponent(u);if(l==null){i.approximate=true;break}let c=(0, Ht.asOrNull)(l,n);if(o<r-1&&c==null){i.approximate=true;break}s=l,a=c;}return i.obj=s,i}InsertContent(e,t){if(this.content.splice(t,0,e),e.parent)throw new Error("content is already in "+e.parent);e.parent=this,this.TryAddNamedContent(e);}AddContentsOfContainer(e){this.content.push(...e.content);for(let t of e.content)t.parent=this,this.TryAddNamedContent(t);}ContentWithPathComponent(e){if(e.isIndex)return e.index>=0&&e.index<this.content.length?this.content[e.index]:null;if(e.isParent)return this.parent;{if(e.name===null)return (0, wg.throwNullException)("component.name");let t=(0, sw.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Ht.asOrThrows)(t.result,rr.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new rw.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],r=arguments[2];function i(){for(let o=0;o<4*t;++o)e.Append(" ");}i(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==r&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof n?o.BuildStringOfHierarchy(e,t,r):(i(),o instanceof nw.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
11
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof n)&&o==r&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Ht.asOrThrows)(o,rr.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Pg.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};ui.Container=oi;(function(n){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(n.CountFlags||(n.CountFlags={}));})(oi||(ui.Container=oi={}));});var Pe=C(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.ControlCommand=void 0;var aw=We(),li=class n extends aw.InkObject{get commandType(){return this._commandType}constructor(e=n.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new n(this.commandType)}static EvalStart(){return new n(n.CommandType.EvalStart)}static EvalOutput(){return new n(n.CommandType.EvalOutput)}static EvalEnd(){return new n(n.CommandType.EvalEnd)}static Duplicate(){return new n(n.CommandType.Duplicate)}static PopEvaluatedValue(){return new n(n.CommandType.PopEvaluatedValue)}static PopFunction(){return new n(n.CommandType.PopFunction)}static PopTunnel(){return new n(n.CommandType.PopTunnel)}static BeginString(){return new n(n.CommandType.BeginString)}static EndString(){return new n(n.CommandType.EndString)}static NoOp(){return new n(n.CommandType.NoOp)}static ChoiceCount(){return new n(n.CommandType.ChoiceCount)}static Turns(){return new n(n.CommandType.Turns)}static TurnsSince(){return new n(n.CommandType.TurnsSince)}static ReadCount(){return new n(n.CommandType.ReadCount)}static Random(){return new n(n.CommandType.Random)}static SeedRandom(){return new n(n.CommandType.SeedRandom)}static VisitIndex(){return new n(n.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new n(n.CommandType.SequenceShuffleIndex)}static StartThread(){return new n(n.CommandType.StartThread)}static Done(){return new n(n.CommandType.Done)}static End(){return new n(n.CommandType.End)}static ListFromInt(){return new n(n.CommandType.ListFromInt)}static ListRange(){return new n(n.CommandType.ListRange)}static ListRandom(){return new n(n.CommandType.ListRandom)}static BeginTag(){return new n(n.CommandType.BeginTag)}static EndTag(){return new n(n.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};ci.ControlCommand=li;(function(n){(function(t){t[t.NotSet=-1]="NotSet",t[t.EvalStart=0]="EvalStart",t[t.EvalOutput=1]="EvalOutput",t[t.EvalEnd=2]="EvalEnd",t[t.Duplicate=3]="Duplicate",t[t.PopEvaluatedValue=4]="PopEvaluatedValue",t[t.PopFunction=5]="PopFunction",t[t.PopTunnel=6]="PopTunnel",t[t.BeginString=7]="BeginString",t[t.EndString=8]="EndString",t[t.NoOp=9]="NoOp",t[t.ChoiceCount=10]="ChoiceCount",t[t.Turns=11]="Turns",t[t.TurnsSince=12]="TurnsSince",t[t.ReadCount=13]="ReadCount",t[t.Random=14]="Random",t[t.SeedRandom=15]="SeedRandom",t[t.VisitIndex=16]="VisitIndex",t[t.SequenceShuffleIndex=17]="SequenceShuffleIndex",t[t.StartThread=18]="StartThread",t[t.Done=19]="Done",t[t.End=20]="End",t[t.ListFromInt=21]="ListFromInt",t[t.ListRange=22]="ListRange",t[t.ListRandom=23]="ListRandom",t[t.BeginTag=24]="BeginTag",t[t.EndTag=25]="EndTag",t[t.TOTAL_VALUES=26]="TOTAL_VALUES";})(n.CommandType||(n.CommandType={}));})(li||(ci.ControlCommand=li={}));});var et=C(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.Expression=void 0;var Fg=ce(),Vc=Pe(),ow=se(),qc=class extends ow.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Fg.Container;return e.AddContent(Vc.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(Vc.ControlCommand.EvalOutput()),e.AddContent(Vc.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Fg.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let r=t.Copy();r&&e.AddContent(r);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};Gs.Expression=qc;});var vn=C(Us=>{Object.defineProperty(Us,"__esModule",{value:true});Us.Void=void 0;var uw=We(),jc=class extends uw.InkObject{toString(){return "Void"}};Us.Void=jc;});var _t=C(Ks=>{Object.defineProperty(Ks,"__esModule",{value:true});Ks.NativeFunctionCall=void 0;var P=ae(),hi=si(),lw=vn(),Hs=Ge(),cw=We(),tt=J(),Ue=Ae(),M=class n extends cw.InkObject{static CallWithName(e){return new n(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, Ue.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, Ue.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=n._nativeFunctions.get(this._name)||null);}get numberOfParameters(){return this._prototype?this._prototype.numberOfParameters:this._numberOfParameters}set numberOfParameters(e){this._numberOfParameters=e;}Call(e){if(this._prototype)return this._prototype.Call(e);if(this.numberOfParameters!=e.length)throw new Error("Unexpected number of parameters");let t=false;for(let a of e){if(a instanceof lw.Void)throw new hi.StoryException("Attempting to perform "+this.name+' on a void value. Did you forget to "return" a value from a function you called here?');a instanceof P.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==P.ValueType.Int?this.CallType(r):i==P.ValueType.Float?this.CallType(r):i==P.ValueType.String?this.CallType(r):i==P.ValueType.DivertTarget?this.CallType(r):i==P.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, tt.asOrThrows)(e[0],P.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=P.ValueType[r];throw new hi.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, tt.asOrThrows)(e[1],P.Value),l=s;if(i.value===null||u.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return P.Value.Create(c)}else {let o=s;if(i.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?P.Value.Create(u,P.ValueType.Int):this.name===n.Float?P.Value.Create(u,P.ValueType.Float):P.Value.Create(u,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof P.ListValue&&e[1]instanceof P.IntValue)return this.CallListIncrementOperation(e);let t=(0, tt.asOrThrows)(e[0],P.Value),r=(0, tt.asOrThrows)(e[1],P.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=P.ValueType.List||r.valueType!=P.ValueType.List)){if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(P.ValueType.Int);if(i===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, tt.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new P.BoolValue(a)}if(t.valueType==P.ValueType.List&&r.valueType==P.ValueType.List)return this.CallType([t,r]);throw new hi.StoryException("Can not call use "+this.name+" operation on "+P.ValueType[t.valueType]+" and "+P.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, tt.asOrThrows)(e[0],P.ListValue),r=(0, tt.asOrThrows)(e[1],P.IntValue),i=new Hs.InkList;if(t.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Hs.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, Ue.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(P.ValueType.Int);if(r.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, Ue.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value.origins");for(let h of t.value.origins)if(h.name==o.originName){c=h;break}if(c!=null){let h=c.TryGetItemWithValue(l,Hs.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new P.ListValue(i)}CoerceValuesToSingleType(e){let t=P.ValueType.Int,r=null;for(let a of e){let s=(0, tt.asOrThrows)(a,P.Value);s.valueType>t&&(t=s.valueType),s.valueType==P.ValueType.List&&(r=(0, tt.asOrNull)(s,P.ListValue));}let i=[];if(P.ValueType[t]==P.ValueType[P.ValueType.List])for(let a of e){let s=(0, tt.asOrThrows)(a,P.Value);if(s.valueType==P.ValueType.List)i.push(s);else if(s.valueType==P.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, tt.asOrThrows)(r,P.ListValue),r.value===null)return (0, Ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, Ue.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,Hs.InkListItem.Null);if(l.exists){let c=new P.ListValue(l.result,o);i.push(c);}else throw new hi.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=P.ValueType[s.valueType];throw new hi.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, tt.asOrThrows)(a,P.Value).Cast(t);i.push(o);}return i}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)n.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];n.GenerateNativeFunctionsIfNecessary(),this.name=e;}else if(arguments.length===2){let e=arguments[0],t=arguments[1];this._isPrototype=true,this.name=e,this.numberOfParameters=t;}}static Identity(e){return e}static GenerateNativeFunctionsIfNecessary(){if(this._nativeFunctions==null){this._nativeFunctions=new Map,this.AddIntBinaryOp(this.Add,(r,i)=>r+i),this.AddIntBinaryOp(this.Subtract,(r,i)=>r-i),this.AddIntBinaryOp(this.Multiply,(r,i)=>r*i),this.AddIntBinaryOp(this.Divide,(r,i)=>Math.floor(r/i)),this.AddIntBinaryOp(this.Mod,(r,i)=>r%i),this.AddIntUnaryOp(this.Negate,r=>-r),this.AddIntBinaryOp(this.Equal,(r,i)=>r==i),this.AddIntBinaryOp(this.Greater,(r,i)=>r>i),this.AddIntBinaryOp(this.Less,(r,i)=>r<i),this.AddIntBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddIntBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddIntBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddIntUnaryOp(this.Not,r=>r==0),this.AddIntBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddIntBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddIntBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddIntBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddIntBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddIntUnaryOp(this.Floor,n.Identity),this.AddIntUnaryOp(this.Ceiling,n.Identity),this.AddIntUnaryOp(this.Int,n.Identity),this.AddIntUnaryOp(this.Float,r=>r),this.AddFloatBinaryOp(this.Add,(r,i)=>r+i),this.AddFloatBinaryOp(this.Subtract,(r,i)=>r-i),this.AddFloatBinaryOp(this.Multiply,(r,i)=>r*i),this.AddFloatBinaryOp(this.Divide,(r,i)=>r/i),this.AddFloatBinaryOp(this.Mod,(r,i)=>r%i),this.AddFloatUnaryOp(this.Negate,r=>-r),this.AddFloatBinaryOp(this.Equal,(r,i)=>r==i),this.AddFloatBinaryOp(this.Greater,(r,i)=>r>i),this.AddFloatBinaryOp(this.Less,(r,i)=>r<i),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(r,i)=>r>=i),this.AddFloatBinaryOp(this.LessThanOrEquals,(r,i)=>r<=i),this.AddFloatBinaryOp(this.NotEquals,(r,i)=>r!=i),this.AddFloatUnaryOp(this.Not,r=>r==0),this.AddFloatBinaryOp(this.And,(r,i)=>r!=0&&i!=0),this.AddFloatBinaryOp(this.Or,(r,i)=>r!=0||i!=0),this.AddFloatBinaryOp(this.Max,(r,i)=>Math.max(r,i)),this.AddFloatBinaryOp(this.Min,(r,i)=>Math.min(r,i)),this.AddFloatBinaryOp(this.Pow,(r,i)=>Math.pow(r,i)),this.AddFloatUnaryOp(this.Floor,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Ceiling,r=>Math.ceil(r)),this.AddFloatUnaryOp(this.Int,r=>Math.floor(r)),this.AddFloatUnaryOp(this.Float,n.Identity),this.AddStringBinaryOp(this.Add,(r,i)=>r+i),this.AddStringBinaryOp(this.Equal,(r,i)=>r===i),this.AddStringBinaryOp(this.NotEquals,(r,i)=>r!==i),this.AddStringBinaryOp(this.Has,(r,i)=>r.includes(i)),this.AddStringBinaryOp(this.Hasnt,(r,i)=>!r.includes(i)),this.AddListBinaryOp(this.Add,(r,i)=>r.Union(i)),this.AddListBinaryOp(this.Subtract,(r,i)=>r.Without(i)),this.AddListBinaryOp(this.Has,(r,i)=>r.Contains(i)),this.AddListBinaryOp(this.Hasnt,(r,i)=>!r.Contains(i)),this.AddListBinaryOp(this.Intersect,(r,i)=>r.Intersect(i)),this.AddListBinaryOp(this.Equal,(r,i)=>r.Equals(i)),this.AddListBinaryOp(this.Greater,(r,i)=>r.GreaterThan(i)),this.AddListBinaryOp(this.Less,(r,i)=>r.LessThan(i)),this.AddListBinaryOp(this.GreaterThanOrEquals,(r,i)=>r.GreaterThanOrEquals(i)),this.AddListBinaryOp(this.LessThanOrEquals,(r,i)=>r.LessThanOrEquals(i)),this.AddListBinaryOp(this.NotEquals,(r,i)=>!r.Equals(i)),this.AddListBinaryOp(this.And,(r,i)=>r.Count>0&&i.Count>0),this.AddListBinaryOp(this.Or,(r,i)=>r.Count>0||i.Count>0),this.AddListUnaryOp(this.Not,r=>r.Count==0?1:0),this.AddListUnaryOp(this.Invert,r=>r.inverse),this.AddListUnaryOp(this.All,r=>r.all),this.AddListUnaryOp(this.ListMin,r=>r.MinAsList()),this.AddListUnaryOp(this.ListMax,r=>r.MaxAsList()),this.AddListUnaryOp(this.Count,r=>r.Count),this.AddListUnaryOp(this.ValueOfList,r=>r.maxItem.Value);let e=(r,i)=>r.Equals(i),t=(r,i)=>!r.Equals(i);this.AddOpToNativeFunc(this.Equal,2,P.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,P.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,r,i){if(this._nativeFunctions===null)return (0, Ue.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new n(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(r,i);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,P.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,P.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Ks.NativeFunctionCall=M;M.Add="+";M.Subtract="-";M.Divide="/";M.Multiply="*";M.Mod="%";M.Negate="_";M.Equal="==";M.Greater=">";M.Less="<";M.GreaterThanOrEquals=">=";M.LessThanOrEquals="<=";M.NotEquals="!=";M.Not="!";M.And="&&";M.Or="||";M.Min="MIN";M.Max="MAX";M.Pow="POW";M.Floor="FLOOR";M.Ceiling="CEILING";M.Int="INT";M.Float="FLOAT";M.Has="?";M.Hasnt="!?";M.Intersect="^";M.ListMin="LIST_MIN";M.ListMax="LIST_MAX";M.All="LIST_ALL";M.Count="LIST_COUNT";M.ValueOfList="LIST_VALUE";M.Invert="LIST_INVERT";M._nativeFunctions=null;});var Js=C(zs=>{Object.defineProperty(zs,"__esModule",{value:true});zs.NumberExpression=void 0;var hw=et(),Lc=ae(),dw=J(),Bc=class n extends hw.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=r=>{this.isInt()?r.AddContent(new Lc.IntValue(this.value)):this.isFloat()?r.AddContent(new Lc.FloatValue(this.value)):this.isBool()&&r.AddContent(new Lc.BoolValue(this.value));},this.toString=()=>String(this.value),typeof e=="number"&&!Number.isNaN(e)||typeof e=="boolean")this.value=e,this.subtype=t;else throw new Error("Unexpected object type in NumberExpression.")}get typeName(){return "Number"}Equals(e){let t=(0, dw.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};zs.NumberExpression=Bc;});var Wc=C(Zs=>{Object.defineProperty(Zs,"__esModule",{value:true});Zs.UnaryExpression=void 0;var fw=et(),pw=_t(),ir=Js(),mw=J(),di=class extends fw.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=r=>{this.innerExpression.GenerateIntoContainer(r),r.AddContent(pw.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Zs.UnaryExpression=di;di.WithInner=(n,e)=>{let t=(0, mw.asOrNull)(n,ir.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new ir.NumberExpression(-t.value,"int");if(t.isFloat())return new ir.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new ir.NumberExpression(t.value==0,"bool");if(t.isFloat())return new ir.NumberExpression(t.value==0,"bool");if(t.isBool())return new ir.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new di(n,e)};});var Gc=C(Xs=>{Object.defineProperty(Xs,"__esModule",{value:true});Xs.BinaryExpression=void 0;var gw=et(),yw=_t(),Cw=Wc(),vw=J(),Mc=class extends gw.Expression{constructor(e,t,r){super(),this.opName=r,this.GenerateIntoContainer=i=>{this.leftExpression.GenerateIntoContainer(i),this.rightExpression.GenerateIntoContainer(i),this.opName=this.NativeNameForOp(this.opName),i.AddContent(yw.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=i=>i==="and"?"&&":i==="or"?"||":i==="mod"?"%":i==="has"?"?":i==="hasnt"?"!?":i,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=r;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, vw.asOrNull)(this.leftExpression,Cw.UnaryExpression);t!==null&&(t.op==="not"||t.op==="!")&&this.Error(`Using 'not' or '!' here negates '${t.innerExpression}' rather than the result of the '?' or 'has' operator. You need to add parentheses around the (A ? B) expression.`);}}};Xs.BinaryExpression=Mc;});var pi=C(Qs=>{Object.defineProperty(Qs,"__esModule",{value:true});Qs.CharacterSet=void 0;var fi=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,r)=>{for(let i=t.charCodeAt(0);i<=r.charCodeAt(0);++i)this.Add(String.fromCharCode(i));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let r of t)this.Add(r);else for(let r of t.set)this.Add(r);return this},e&&this.AddCharacters(e);}};Qs.CharacterSet=fi;fi.FromRange=(n,e)=>new fi().AddRange(n,e);});var xg=C(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.CharacterRange=void 0;var Og=pi(),mi=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Og.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let i=this.start.charCodeAt(0),a;i<=this.end.charCodeAt(0);i+=1)a=String.fromCharCode(i),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},r instanceof Og.CharacterSet)this._excludes=r.set;else for(let i of r)this._excludes.add(i);}get start(){return this._start}get end(){return this._end}};Ys.CharacterRange=mi;mi.Define=(n,e,t=[])=>new mi(n,e,t);});var ta=C(ea=>{Object.defineProperty(ea,"__esModule",{value:true});ea.ChoicePoint=void 0;var _w=We(),Ew=Be(),Uc=Ae(),Hc=class extends _w.InkObject{constructor(e=true){super(),this._pathOnChoice=null,this.hasCondition=false,this.hasStartContent=false,this.hasChoiceOnlyContent=false,this.isInvisibleDefault=false,this.onceOnly=true,this.onceOnly=e;}get pathOnChoice(){if(this._pathOnChoice!=null&&this._pathOnChoice.isRelative){let e=this.choiceTarget;e&&(this._pathOnChoice=e.path);}return this._pathOnChoice}set pathOnChoice(e){this._pathOnChoice=e;}get choiceTarget(){return this._pathOnChoice===null?(0, Uc.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Uc.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Ew.Path(e);}get flags(){let e=0;return this.hasCondition&&(e|=1),this.hasStartContent&&(e|=2),this.hasChoiceOnlyContent&&(e|=4),this.isInvisibleDefault&&(e|=8),this.onceOnly&&(e|=16),e}set flags(e){this.hasCondition=(e&1)>0,this.hasStartContent=(e&2)>0,this.hasChoiceOnlyContent=(e&4)>0,this.isInvisibleDefault=(e&8)>0,this.onceOnly=(e&16)>0;}toString(){if(this.pathOnChoice===null)return (0, Uc.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};ea.ChoicePoint=Hc;});var _n=C(na=>{Object.defineProperty(na,"__esModule",{value:true});na.PushPopType=void 0;var Ng;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Ng||(na.PushPopType=Ng={}));});var gi=C(ra=>{Object.defineProperty(ra,"__esModule",{value:true});ra.Pointer=void 0;var bw=Be(),Kc=class n{constructor(){this.container=null,this.index=-1,arguments.length===2&&(this.container=arguments[0],this.index=arguments[1]);}Resolve(){return this.index<0?this.container:this.container==null?null:this.container.content.length==0?this.container:this.index>=this.container.content.length?null:this.container.content[this.index]}get isNull(){return this.container==null}get path(){return this.isNull?null:this.index>=0?this.container.path.PathByAppendingComponent(new bw.Path.Component(this.index)):this.container.path}toString(){return this.container?"Ink Pointer -> "+this.container.path.toString()+" -- index "+this.index:"Ink Pointer (null)"}copy(){return new n(this.container,this.index)}static StartOf(e){return new n(e,0)}static get Null(){return new n(null,-1)}};ra.Pointer=Kc;});var Et=C(sa=>{Object.defineProperty(sa,"__esModule",{value:true});sa.Divert=void 0;var Sw=Be(),Dw=_n(),ww=yn(),Aw=We(),zc=gi(),Tg=ce(),ia=Ae(),Jc=class n extends Aw.InkObject{get targetPath(){if(this._targetPath!=null&&this._targetPath.isRelative){let e=this.targetPointer.Resolve();e&&(this._targetPath=e.path);}return this._targetPath}set targetPath(e){this._targetPath=e,this._targetPointer=zc.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, ia.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, ia.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, ia.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Tg.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=zc.Pointer.StartOf(e instanceof Tg.Container?e:null);}return this._targetPointer.copy()}get targetPathString(){return this.targetPath==null?null:this.CompactPathString(this.targetPath)}set targetPathString(e){e==null?this.targetPath=null:this.targetPath=new Sw.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=zc.Pointer.Null,this.variableDivertName=null,this.pushesToStack=false,this.stackPushType=0,this.isExternal=false,this.externalArgs=0,this.isConditional=false,this.pushesToStack=false,typeof e<"u"&&(this.pushesToStack=true,this.stackPushType=e);}Equals(e){let t=e;return t instanceof n&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, ia.throwNullException)("this.targetPath"):this.targetPath.Equals(t.targetPath):false}toString(){if(this.hasVariableTarget)return "Divert(variable: "+this.variableDivertName+")";if(this.targetPath==null)return "Divert(null)";{let e=new ww.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Dw.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};sa.Divert=Jc;});var It=C(aa=>{Object.defineProperty(aa,"__esModule",{value:true});aa.SymbolType=void 0;var Ig;(function(n){n[n.Knot=0]="Knot",n[n.List=1]="List",n[n.ListItem=2]="ListItem",n[n.Var=3]="Var",n[n.SubFlowAndWeave=4]="SubFlowAndWeave",n[n.Arg=5]="Arg",n[n.Temp=6]="Temp";})(Ig||(aa.SymbolType=Ig={}));});var Kt=C(oa=>{Object.defineProperty(oa,"__esModule",{value:true});oa.VariableAssignment=void 0;var Pw=We(),Zc=class extends Pw.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};oa.VariableAssignment=Zc;});var sr=C(la=>{Object.defineProperty(la,"__esModule",{value:true});la.Choice=void 0;var Fw=ta(),ua=ce(),zt=Pe(),Xc=Et(),kg=ae(),Ow=se(),xw=It(),$g=Kt(),Qc=class extends Ow.ParsedObject{get runtimeChoice(){if(!this._runtimeChoice)throw new Error;return this._runtimeChoice}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get condition(){return this._condition}set condition(e){this._condition=e,e&&this.AddContent(e);}get runtimeContainer(){return this._innerContentContainer}get innerContentContainer(){return this._innerContentContainer}get containerForCounting(){return this._innerContentContainer}get runtimePath(){if(!this.innerContentContainer||!this.innerContentContainer.path)throw new Error;return this.innerContentContainer.path}constructor(e,t,r){super(),this._condition=null,this._innerContentContainer=null,this._outerContainer=null,this._runtimeChoice=null,this._returnToR1=null,this._returnToR2=null,this._r1Label=null,this._r2Label=null,this._divertToStartContentOuter=null,this._divertToStartContentInner=null,this._startContentRuntimeContainer=null,this.isInvisibleDefault=false,this.hasWeaveStyleInlineBrackets=false,this.GenerateRuntimeObject=()=>{if(this._outerContainer=new ua.Container,this._runtimeChoice=new Fw.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(zt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new kg.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new $g.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(zt.ControlCommand.BeginString()),this._divertToStartContentOuter=new Xc.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Xc.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new ua.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(zt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(zt.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(zt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(zt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new ua.Container,this.startContent){this._returnToR2=new kg.DivertTargetValue,this._innerContentContainer.AddContent(zt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(zt.ControlCommand.EvalEnd());let i=new $g.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Xc.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new ua.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let i=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(i);}return this.story.countAllVisits&&(this._innerContentContainer.visitsShouldBeCounted=true),this._innerContentContainer.countingAtStartOnly=true,this._outerContainer},this.toString=()=>this.choiceOnlyContent!==null?`* ${this.startContent}[${this.choiceOnlyContent}]...`:`* ${this.startContent}...`,this.startContent=e,this.choiceOnlyContent=t,this.innerContent=r,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),r&&this.AddContent(this.innerContent),this.onceOnly=true;}get typeName(){return "Choice"}ResolveReferences(e){var t;if(this._innerContentContainer&&(this.runtimeChoice.pathOnChoice=this._innerContentContainer.path,this.onceOnly&&(this._innerContentContainer.visitsShouldBeCounted=true)),this._returnToR1){if(!this._r1Label)throw new Error;this._returnToR1.targetPath=this._r1Label.path;}if(this._returnToR2){if(!this._r2Label)throw new Error;this._returnToR2.targetPath=this._r2Label.path;}if(this._divertToStartContentOuter){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentOuter.targetPath=this._startContentRuntimeContainer.path;}if(this._divertToStartContentInner){if(!this._startContentRuntimeContainer)throw new Error;this._divertToStartContentInner.targetPath=this._startContentRuntimeContainer.path;}super.ResolveReferences(e),this.identifier&&(((t=this.identifier)===null||t===void 0?void 0:t.name)||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,xw.SymbolType.SubFlowAndWeave);}};la.Choice=Qc;});var Rg=C(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.StringParserElement=void 0;var ca=class n{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{n._uniqueIdCounter++,this.uniqueId=n._uniqueIdCounter,this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.customFlags=e.customFlags,this.reportedErrorInScope=false;},this.SquashFrom=e=>{this.characterIndex=e.characterIndex,this.characterInLineIndex=e.characterInLineIndex,this.lineIndex=e.lineIndex,this.reportedErrorInScope=e.reportedErrorInScope,this.customFlags=e.customFlags;};}};ha.StringParserElement=ca;ca._uniqueIdCounter=1e3;});var qg=C(da=>{Object.defineProperty(da,"__esModule",{value:true});da.StringParserState=void 0;var Vg=Rg(),Yc=class{get currentElement(){return this._stack[this._numElements-1]}get lineIndex(){return this.currentElement.lineIndex}set lineIndex(e){this.currentElement.lineIndex=e;}get characterIndex(){return this.currentElement.characterIndex}set characterIndex(e){this.currentElement.characterIndex=e;}get characterInLineIndex(){return this.currentElement.characterInLineIndex}set characterInLineIndex(e){this.currentElement.characterInLineIndex=e;}get customFlags(){return this.currentElement.customFlags}set customFlags(e){this.currentElement.customFlags=e;}get errorReportedAlreadyInScope(){return this.currentElement.reportedErrorInScope}get stackHeight(){return this._numElements}constructor(){this._stack=[],this._numElements=0,this.StringParserState=()=>{this._stack=new Array(200);for(let r=0;r<200;++r)this._stack[r]=new Vg.StringParserElement;this._numElements=1;},this.Push=()=>{if(this._numElements>=this._stack.length&&this._numElements>0)throw new Error("Stack overflow in parser state.");let t=this._stack[this._numElements-1],r=this._stack[this._numElements];return this._numElements++,r.CopyFrom(t),r.uniqueId},this.Pop=t=>{if(this._numElements==1)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Poping - do you have mismatched Begin/Succeed/Fail?");this._numElements-=1;},this.Peek=t=>{if(this.currentElement.uniqueId!=t)throw new Error("Mismatched rule IDs while Peeking - do you have mismatched Begin/Succeed/Fail?");return this._stack[this._numElements-1]},this.PeekPenultimate=()=>this._numElements>=2?this._stack[this._numElements-2]:null,this.Squash=()=>{if(this._numElements<2)throw new Error("Attempting to remove final stack element is illegal! Mismatched Begin/Succceed/Fail?");let t=this._stack[this._numElements-2],r=this._stack[this._numElements-1];t.SquashFrom(r),this._numElements-=1;},this.NoteErrorReported=()=>{for(let t of this._stack)t.reportedErrorInScope=true;};let e=200;for(let t=0;t<e;t++)this._stack[t]=new Vg.StringParserElement;this._numElements=1;}};da.StringParserState=Yc;});var th=C(En=>{Object.defineProperty(En,"__esModule",{value:true});En.StringParser=En.ParseSuccess=void 0;var eh=pi(),Nw=qg();En.ParseSuccess=Symbol("ParseSuccessStruct");var yi=class n{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=r=>(this.state.Pop(r),null),this.CancelRule=r=>{this.state.Pop(r);},this.SucceedRule=(r,i=null)=>{let a=this.state.Peek(r),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(i,s,a),this.state.Squash();let o=i;return o===null&&(o=n.ParseSuccess),o},this.Expect=(r,i=null,a=null)=>{let s=this.ParseObject(r);if(s===null){i===null&&(i=r.name);let o,u=this.LineRemainder();u===null||u.length===0?o="end of line":o=`'${u}'`,this.Error(`Expected ${i} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(r,i=false)=>{this.ErrorOnLine(r,this.lineIndex+1,i);},this.ErrorWithParsedObject=(r,i,a=false)=>{this.ErrorOnLine(r,i.debugMetadata?i.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(r,i,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(r,this.index,i-1,a);else throw new Error(`${s} on line ${i}: ${r}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=r=>this.Error(r,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
12
12
  \r`)),this.SetFlag=(r,i)=>{i?this.state.customFlags|=r:this.state.customFlags&=~r;},this.GetFlag=r=>!!(this.state.customFlags&r),this.ParseObject=r=>{let i=this.BeginRule(),a=this.state.stackHeight,s=r();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return s===null?this.FailRule(i):(this.SucceedRule(i,s),s)},this.Parse=r=>{let i=this.BeginRule(),a=r();return a===null?(this.FailRule(i),null):(this.SucceedRule(i,a),a)},this.OneOf=r=>{for(let i of r){let a=this.ParseObject(i);if(a!==null)return a}return null},this.OneOrMore=r=>{let i=[],a=null;do a=this.ParseObject(r),a!==null&&i.push(a);while(a!==null);return i.length>0?i:null},this.Optional=r=>()=>{let i=this.ParseObject(r);return i===null?n.ParseSuccess:i},this.Exclude=r=>()=>this.ParseObject(r)&&n.ParseSuccess,this.OptionalExclude=r=>()=>(this.ParseObject(r),n.ParseSuccess),this.String=r=>()=>this.ParseString(r),this.TryAddResultToList=(r,i,a=true)=>{if(r!==n.ParseSuccess){if(a&&Array.isArray(r)){let s=r;if(s!==null){for(let o of s)i.push(o);return}}i.push(r);}},this.Interleave=(r,i,a=null,s=true)=>{let o=this.BeginRule(),u=[],l=this.ParseObject(r);if(l===null)return this.FailRule(o);this.TryAddResultToList(l,u,s);let c=null,h=null;do{if(a!==null&&this.Peek(a)!==null||(c=this.ParseObject(i),c===null))break;if(this.TryAddResultToList(c,u,s),h=null,c!==null){if(h=this.ParseObject(r),h===null)break;this.TryAddResultToList(h,u,s);}}while((c!==null||h!==null)&&!(c===n.ParseSuccess&&h==n.ParseSuccess)&&this.remainingLength>0);return u.length===0?this.FailRule(o):this.SucceedRule(o,u)},this.ParseString=r=>{if(r.length>this.remainingLength)return null;let i=this.BeginRule(),a=this.index,s=this.characterInLineIndex,o=this.lineIndex,u=true;for(let l=0;l<r.length;l+=1){let c=r[l];if(this._chars[a]!==c){u=false;break}c===`
13
13
  `&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,u?this.SucceedRule(i,r):this.FailRule(i)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let r=this._chars[this.index];return r===`
14
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,r}return "0"},this.ParseUntilCharactersFromString=(r,i=-1)=>this.ParseCharactersFromString(r,false,i),this.ParseUntilCharactersFromCharSet=(r,i=-1)=>this.ParseCharactersFromCharSet(r,false,i),this.ParseCharactersFromString=(r,i=-1,a=-1)=>{let s=new Qc.CharacterSet(r);return typeof i=="number"?this.ParseCharactersFromCharSet(s,true,i):this.ParseCharactersFromCharSet(s,i,a)},this.ParseCharactersFromCharSet=(r,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,u=this.characterInLineIndex,l=this.lineIndex,c=0;for(;o<this._chars.length&&r.set.has(this._chars[o])===i&&c<a;)this._chars[o]===`
14
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,r}return "0"},this.ParseUntilCharactersFromString=(r,i=-1)=>this.ParseCharactersFromString(r,false,i),this.ParseUntilCharactersFromCharSet=(r,i=-1)=>this.ParseCharactersFromCharSet(r,false,i),this.ParseCharactersFromString=(r,i=-1,a=-1)=>{let s=new eh.CharacterSet(r);return typeof i=="number"?this.ParseCharactersFromCharSet(s,true,i):this.ParseCharactersFromCharSet(s,i,a)},this.ParseCharactersFromCharSet=(r,i=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,u=this.characterInLineIndex,l=this.lineIndex,c=0;for(;o<this._chars.length&&r.set.has(this._chars[o])===i&&c<a;)this._chars[o]===`
15
15
  `&&(l+=1,u=-1),o+=1,u+=1,c+=1;return this.index=o,this.characterInLineIndex=u,this.lineIndex=l,this.index>s?this._chars.slice(s,this.index).join(""):null},this.Peek=r=>{let i=this.BeginRule(),a=r();return this.CancelRule(i),a},this.ParseInt=()=>{let r=this.index,i=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let s=this.ParseCharactersFromCharSet(n.numbersCharacterSet);if(s===null)return this.index=r,this.characterInLineIndex=i,null;let o;return Number.isNaN(Number(s))?(this.Error("Failed to read integer value: "+s+". Perhaps it's out of the range of acceptable numbers ink supports? ("+Number.MIN_SAFE_INTEGER+" to "+Number.MAX_SAFE_INTEGER+")"),null):(o=Number(s),a?-o:o)},this.ParseFloat=()=>{let r=this.index,i=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let s=this.ParseCharactersFromCharSet(n.numbersCharacterSet);return +`${a}.${s}`}return this.index=r,this.characterInLineIndex=i,null},this.ParseNewline=()=>{let r=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
16
16
  `)===null?this.FailRule(r):this.SucceedRule(r,`
17
- `)};let t=this.PreProcessInputString(e);this.state=new Ow.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,r=null){let i=this.BeginRule(),a=new Qc.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),r!==null&&(a.set=new Set([...a.set.values(),...r.set.values()]));let s="",o=null;do{let u=this.ParseUntilCharactersFromCharSet(a);if(u&&(s+=u),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(t!==null&&t.set.has(l)){s+=l,l===`
18
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}};bn.StringParser=yi;yi.ParseSuccess=bn.ParseSuccess;yi.numbersCharacterSet=new Qc.CharacterSet("0123456789");});var qg=y(fa=>{Object.defineProperty(fa,"__esModule",{value:true});fa.CommentEliminator=void 0;var eh=pi(),xw=Yc(),th=class extends xw.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new eh.CharacterSet(`/\r
19
- `),this._commentBlockEndCharacter=new eh.CharacterSet("*"),this._newlineCharacters=new eh.CharacterSet(`
17
+ `)};let t=this.PreProcessInputString(e);this.state=new Nw.StringParserState,e?this._chars=t.split(""):this._chars=[],this.inputString=t;}get currentCharacter(){return this.index>=0&&this.remainingLength>0?this._chars[this.index]:"0"}PreProcessInputString(e){return e}get endOfInput(){return this.index>=this._chars.length}get remainingString(){return this._chars.slice(this.index,this.index+this.remainingLength).join("")}get remainingLength(){return this._chars.length-this.index}get lineIndex(){return this.state.lineIndex}set lineIndex(e){this.state.lineIndex=e;}set characterInLineIndex(e){this.state.characterInLineIndex=e;}get characterInLineIndex(){return this.state.characterInLineIndex}get index(){return this.state.characterIndex}set index(e){this.state.characterIndex=e;}ParseUntil(e,t=null,r=null){let i=this.BeginRule(),a=new eh.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),r!==null&&(a.set=new Set([...a.set.values(),...r.set.values()]));let s="",o=null;do{let u=this.ParseUntilCharactersFromCharSet(a);if(u&&(s+=u),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let l=this.currentCharacter;if(t!==null&&t.set.has(l)){s+=l,l===`
18
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(i,String(s)):this.FailRule(i)}};En.StringParser=yi;yi.ParseSuccess=En.ParseSuccess;yi.numbersCharacterSet=new eh.CharacterSet("0123456789");});var jg=C(fa=>{Object.defineProperty(fa,"__esModule",{value:true});fa.CommentEliminator=void 0;var nh=pi(),Tw=th(),rh=class extends Tw.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new nh.CharacterSet(`/\r
19
+ `),this._commentBlockEndCharacter=new nh.CharacterSet("*"),this._newlineCharacters=new nh.CharacterSet(`
20
20
  \r`),this.Process=()=>{let e=this.Interleave(this.Optional(this.CommentsAndNewlines),this.Optional(this.MainInk));return e!==null?e.join(""):""},this.MainInk=()=>this.ParseUntil(this.CommentsAndNewlines,this._commentOrNewlineStartCharacter,null),this.CommentsAndNewlines=()=>{let e=this.Interleave(this.Optional(this.ParseNewline),this.Optional(this.ParseSingleComment));return e!==null?e.join(""):null},this.ParseSingleComment=()=>this.OneOf([this.EndOfLineComment,this.BlockComment]),this.EndOfLineComment=()=>this.ParseString("//")===null?null:(this.ParseUntilCharactersFromCharSet(this._newlineCharacters),""),this.BlockComment=()=>{if(this.ParseString("/*")===null)return null;let e=this.lineIndex,t=this.ParseUntil(this.String("*/"),this._commentBlockEndCharacter,null);return this.endOfInput||this.ParseString("*/"),t!=null?`
21
- `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};fa.CommentEliminator=th;});var ma=y(pa=>{Object.defineProperty(pa,"__esModule",{value:true});pa.Conditional=void 0;var Nw=ce(),jg=Pe(),Tw=se(),nh=class extends Tw.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new Nw.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;r.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(jg.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=jg.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=t;}super.ResolveReferences(e);}};pa.Conditional=nh;});var Zt=y(ga=>{Object.defineProperty(ga,"__esModule",{value:true});ga.Text=void 0;var Iw=se(),kw=ae(),rh=class extends Iw.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new kw.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};ga.Text=rh;});var Ca=y(ya=>{Object.defineProperty(ya,"__esModule",{value:true});ya.ConstantDeclaration=void 0;var $w=se(),Rw=It(),ih=class extends $w.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,Rw.SymbolType.Var);}};ya.ConstantDeclaration=ih;});var or=y(va=>{Object.defineProperty(va,"__esModule",{value:true});va.FlowLevel=void 0;var Lg;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Lg||(va.FlowLevel=Lg={}));});var Ci=y(_a=>{Object.defineProperty(_a,"__esModule",{value:true});_a.Gather=void 0;var Vw=ce(),qw=se(),jw=It(),sh=class extends qw.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let r=new Vw.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=true),r.countingAtStartOnly=true,this.content)for(let i of this.content)r.AddContent(i.runtimeObject);return r},this.toString=()=>{var r,i;return `- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,jw.SymbolType.SubFlowAndWeave);}};_a.Gather=sh;});var Sn=y(ba=>{Object.defineProperty(ba,"__esModule",{value:true});ba.Path=void 0;var Ea=Z(),Bg=bt(),ur=or(),Lw=Dn(),ah=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?ur.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(Ea.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===ur.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=r=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(r);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=r=>{let i=this.firstComponent,a=r;for(;a;){let s=a===r,o=this.GetChildFromContext(a,i,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=r=>{let i=r;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,u=(0, Ea.asOrNull)(i,Bg.FlowBase);if(u!==null?o=u.flowLevel+1:o=ur.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(r,i,a,s=false)=>{let o=a===null,u=(0, Ea.asOrNull)(r,Lw.Weave);if(i&&u!==null&&(o||a===ur.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Ea.asOrNull)(r,Bg.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===ur.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values(ur.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};ba.Path=ah;});var lh=y(Sa=>{Object.defineProperty(Sa,"__esModule",{value:true});Sa.ReturnType=void 0;var Bw=se(),Ww=ce(),oh=Pe(),Mw=_n(),uh=class extends Bw.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new Ww.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(oh.ControlCommand.EvalStart()),t.AddContent(new Mw.Void),t.AddContent(oh.ControlCommand.EvalEnd())),t.AddContent(oh.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Sa.ReturnType=uh;});var vi=y(Da=>{Object.defineProperty(Da,"__esModule",{value:true});Da.ClosestFlowBase=void 0;function Gw(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Da.ClosestFlowBase=Gw;});var Aa=y(wa=>{Object.defineProperty(wa,"__esModule",{value:true});wa.Identifier=void 0;var ch=class n{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new n("DONE")}};wa.Identifier=ch;});var bt=y(Pa=>{Object.defineProperty(Pa,"__esModule",{value:true});Pa.FlowBase=void 0;var Uw=ar(),hh=cr(),Hw=lr(),St=or(),Kw=Ci(),zw=se(),Jw=Sn(),Zw=lh(),Xw=ce(),Qw=Et(),Yw=zt(),dh=It(),eA=Dn(),tA=vi(),nA=Aa(),Wg=Z(),fh=class n extends zw.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,r=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var u,l;let c=[],h=[];this._subFlowsByName=new Map;for(let p of s){let m=(0, Wg.asOrNull)(p,n);m?(this._firstChildFlow===null&&(this._firstChildFlow=m),h.push(p),!((u=m.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=m.identifier)===null||l===void 0?void 0:l.name,m)):c.push(p);}o&&c.push(new Kw.Gather(null,1),new hh.Divert(new Jw.Path(nA.Identifier.Done())));let d=[];return c.length>0&&(this._rootWeave=new eA.Weave(c,0),d.push(this._rootWeave)),h.length>0&&d.push(...h),d},this.ResolveVariableWithName=(s,o)=>{var u;let l={},c=o===null?this:(0, tA.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((u=h.identifier)===null||u===void 0?void 0:u.name)===s)return l.found=true,l.isArgument=true,l.ownerFlow=c,l}if(c!==this.story&&c.variableDeclarations.has(s))return l.found=true,l.ownerFlow=c,l.isTemporary=true,l}return this.story.variableDeclarations.has(s)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let u=this.variableDeclarations.get(o),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${l}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===St.FlowLevel.Knot||this.flowLevel===St.FlowLevel.Stitch)&&(o=this.Find(Zw.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let u=new Xw.Container;u.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let c=this.content[l];if(c instanceof n){let h=c,d=h.runtimeObject;l===0&&!h.hasParameters&&this.flowLevel===St.FlowLevel.Knot&&(this._startingSubFlowDivert=new Qw.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=d);let p=d,m=u.namedContent.get(p.name)||null;if(m){let f=`${this.GetType()} already contains flow named '${p.name}' (at ${m.debugMetadata})`;this.Error(f,h);}u.AddToNamedContentOnly(p);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==St.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((o=this.args[u].identifier)===null||o===void 0?void 0:o.name)||null,c=new Yw.VariableAssignment(l,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,u=false)=>{var l;if((o===this.flowLevel||o===null)&&s===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(o===St.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===St.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let c=this._subFlowsByName.get(s)||null;return c&&(o===null||o===c.flowLevel)?c:u?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,St.FlowLevel.WeavePoint,false);if(o)return o;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(s,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==St.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(hh.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof Hw.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(Uw.Choice)();for(let u of o)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, Wg.asOrNull)(s,hh.Divert);u&&u.isTunnel&&(o+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=r,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,r;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,dh.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.name)==((r=this.args[a].identifier)===null||r===void 0?void 0:r.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==St.FlowLevel.Story){let i=this.flowLevel===St.FlowLevel.Knot?dh.SymbolType.Knot:dh.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Pa.FlowBase=fh;});var Oa=y(Fa=>{Object.defineProperty(Fa,"__esModule",{value:true});Fa.ContentList=void 0;var rA=ce(),iA=se(),sA=Zt(),aA=Z(),ph=class extends iA.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let r=this.content.length-1;r>=0;--r){let i=(0, aA.asOrNull)(this.content[r],sA.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(r,1);else break}},this.GenerateRuntimeObject=()=>{let r=new rA.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&r.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(r),r},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Fa.ContentList=ph;});var hr=y(xa=>{Object.defineProperty(xa,"__esModule",{value:true});xa.VariableReference=void 0;var oA=We(),uA=Be(),mh=class extends oA.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new uA.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};xa.VariableReference=mh;});var dr=y(Na=>{Object.defineProperty(Na,"__esModule",{value:true});Na.VariableReference=void 0;var lA=Oa(),cA=et(),Mg=bt(),hA=Sn(),dA=hr(),fA=Dn(),pA=Aa(),Gg=Z(),gh=class extends cA.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Gg.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new pA.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let r=this.story.constants.get(this.name);if(r){r.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new dA.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new hA.Path(this.pathIdentifiers),r=t.ResolveFromContext(this);if(r){if(!r.containerForCounting)throw new Error;if(r.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=r.runtimePath,this._runtimeVarRef.name=null;let i=(0, Gg.asOrNull)(r,Mg.FlowBase);i&&i.isFunction&&(this.parent instanceof fA.Weave||this.parent instanceof lA.ContentList||this.parent instanceof Mg.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Na.VariableReference=gh;});var _i=y($a=>{Object.defineProperty($a,"__esModule",{value:true});$a.FunctionCall=void 0;var Dt=Pe(),mA=cr(),gA=lr(),yA=et(),CA=Ge(),vA=ae(),Ia=_t(),Ug=Js(),_A=Sn(),EA=ae(),bA=dr(),Ta=Z(),ka=class n extends yA.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=r=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),r.AddContent(Dt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(Dt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Ta.asOrNull)(this.args[0],gA.DivertTarget),o=(0, Ta.asOrNull)(this.args[0],bA.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(r)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(r)),this.isTurnsSince?r.AddContent(Dt.ControlCommand.TurnsSince()):r.AddContent(Dt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, Ta.asOrNull)(this.args[s],Ug.NumberExpression);if(o&&!o.isInt()){let u=s===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[s].GenerateIntoContainer(r);}r.AddContent(Dt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Ta.asOrNull)(this.args[0],Ug.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(r);r.AddContent(Dt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.ListRandom());else if(Ia.NativeFunctionCall.CallExistsWithName(this.name)){let s=Ia.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${n.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(r);r.AddContent(Ia.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)r.AddContent(new EA.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.ListFromInt());else {let s=new CA.InkList;s.SetInitialOriginName(this.name),r.AddContent(new vA.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(Dt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new mA.Divert(new _A.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,r=t.runtimeDivert.variableDivertName!=null;if(r){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)r||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${n.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};$a.FunctionCall=ka;ka.IsBuiltIn=n=>Ia.NativeFunctionCall.CallExistsWithName(n)?true:n==="CHOICE_COUNT"||n==="TURNS_SINCE"||n==="TURNS"||n==="RANDOM"||n==="SEED_RANDOM"||n==="LIST_VALUE"||n==="LIST_RANDOM"||n==="READ_COUNT";});var Ch=y(Ra=>{Object.defineProperty(Ra,"__esModule",{value:true});Ra.MultipleConditionExpression=void 0;var SA=et(),DA=_t(),yh=class extends SA.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let r=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),r||t.AddContent(DA.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Ra.MultipleConditionExpression=yh;});var lr=y(Va=>{Object.defineProperty(Va,"__esModule",{value:true});Va.DivertTarget=void 0;var wA=Wc(),AA=ar(),PA=ma(),FA=bh(),OA=ae(),vh=et(),xA=bt(),Hg=_i(),NA=Ch(),Kg=dr(),_h=Z(),Eh=class n extends vh.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new OA.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, _h.asOrNull)(t,n);if(!r||!this.divert.target||!r.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=r.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof vh.Expression;){let i=false,a=false,s=t.parent;if(s instanceof wA.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof Kg.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof Kg.VariableReference)||(i=true),a=true;}else if(s instanceof Hg.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof vh.Expression||s instanceof NA.MultipleConditionExpression||s instanceof AA.Choice&&s.condition===t||s instanceof PA.Conditional||s instanceof FA.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let r=this.divert.targetContent;if(r!==null){let i=r.containerForCounting;if(i!==null){let s=(0, _h.asOrNull)(this.parent,Hg.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, _h.asOrNull)(r,xA.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};Va.DivertTarget=Eh;});var cr=y(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.Divert=void 0;var TA=ce(),Ei=Pe(),IA=Et(),Sh=lr(),Dh=bt(),kA=_i(),$A=se(),zg=Sn(),RA=Be(),Jg=En(),VA=ae(),Zg=dr(),qA=vi(),bi=Z(),wh=class extends $A.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Ei.ControlCommand.End();if(this.isDone)return Ei.ControlCommand.Done();this.runtimeDivert=new IA.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let r=this.args!==null&&this.args.length>0;if(r||this.isFunctionCall||this.isTunnel||this.isThread){let i=new TA.Container;if(r){this.isFunctionCall||i.AddContent(Ei.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],u=null;if(a&&s<a.length&&(u=a[s]),u&&u.isByReference){let l=(0, bi.asOrNull)(o,Zg.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new zg.Path(l.pathIdentifiers);if(c.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${c.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let d=new VA.VariablePointerValue(l.name);i.AddContent(d);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Ei.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Ei.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Jg.PushPopType.Function:Jg.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let r=this.PathAsVariableName();if(r!==null){let i=(0, bi.asOrNull)((0, qA.ClosestFlowBase)(this),Dh.FlowBase);if(i){let a=i.ResolveVariableWithName(r,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var u;return ((u=o.identifier)===null||u===void 0?void 0:u.name)==r});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=r;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let r=0;if(this.args!==null&&this.args.length>0&&(r=this.args.length),this.targetContent===null)return;let i=(0, bi.asOrNull)(this.targetContent,Dh.FlowBase);if(r===0&&(i===null||!i.hasParameters))return;if(i===null&&r>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&r>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof Sh.DivertTarget){r>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==r){let s;r===0?s="but there weren't any passed to it":r<a?s=`but only got ${r}`:s=`but got ${r}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=i.args[s],u=this.args[s];if(o.isDivertTarget){let l=(0, bi.asOrNull)(u,Zg.VariableReference);if(!(u instanceof Sh.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${u}`,u);else if(l){let c=new zg.Path(l.pathIdentifiers);c.ResolveFromContext(l)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=r=>{let i=this.target?this.target.firstComponent:null,a=r.externals.get(i);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${s} but got ${o}`);},this.toString=()=>{let r="";if(this.target!==null)r+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(r+=" ->"),this.isFunctionCall&&(r+=" ()"),r},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, bi.asOrNull)(this.targetContent,Dh.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof Sh.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let r=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=kA.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new RA.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!r&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,r=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,r):super.Error(`Divert ${e}`,t,r);}};qa.Divert=wh;});var Xg=y(ja=>{Object.defineProperty(ja,"__esModule",{value:true});ja.GatherPointToResolve=void 0;var Ah=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};ja.GatherPointToResolve=Ah;});var Qg=y(La=>{Object.defineProperty(La,"__esModule",{value:true});La.SequenceDivertToResolve=void 0;var Ph=class{constructor(e,t){this.divert=e,this.targetContent=t;}};La.SequenceDivertToResolve=Ph;});var Fh=y(Ba=>{Object.defineProperty(Ba,"__esModule",{value:true});Ba.SequenceType=void 0;var Yg;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(Yg||(Ba.SequenceType=Yg={}));});var Nh=y(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.Sequence=void 0;var e0=ce(),ht=Pe(),Oh=Et(),Si=ae(),Wa=_t(),jA=se(),LA=Qg(),Ma=Fh(),BA=Dn(),xh=class extends jA.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new e0.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(ht.ControlCommand.EvalStart()),r.AddContent(ht.ControlCommand.VisitIndex());let i=(this.sequenceType&Ma.SequenceType.Once)>0,a=(this.sequenceType&Ma.SequenceType.Cycle)>0,s=(this.sequenceType&Ma.SequenceType.Stopping)>0,o=(this.sequenceType&Ma.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new Si.IntValue(u-1)),r.AddContent(Wa.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new Si.IntValue(this.sequenceElements.length)),r.AddContent(Wa.NativeFunctionCall.CallWithName("%"))),o){let c=ht.ControlCommand.NoOp();if(i||s){let d=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(ht.ControlCommand.Duplicate()),r.AddContent(new Si.IntValue(d)),r.AddContent(Wa.NativeFunctionCall.CallWithName("=="));let p=new Oh.Divert;p.isConditional=true,r.AddContent(p),this.AddDivertToResolve(p,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new Si.IntValue(h)),r.AddContent(ht.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(ht.ControlCommand.EvalEnd());let l=ht.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(ht.ControlCommand.EvalStart()),r.AddContent(ht.ControlCommand.Duplicate()),r.AddContent(new Si.IntValue(c)),r.AddContent(Wa.NativeFunctionCall.CallWithName("==")),r.AddContent(ht.ControlCommand.EvalEnd());let h=new Oh.Divert;h.isConditional=true,r.AddContent(h);let d;c<this.sequenceElements.length?d=this.sequenceElements[c].runtimeObject:d=new e0.Container,d.name=`s${c}`,d.InsertContent(ht.ControlCommand.PopEvaluatedValue(),0);let p=new Oh.Divert;d.AddContent(p),r.AddToNamedContentOnly(d),this.AddDivertToResolve(h,d),this.AddDivertToResolve(p,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new LA.SequenceDivertToResolve(r,i));},this.sequenceType=t,this.sequenceElements=[];for(let r of e){let i=r.content,a=null;i===null||i.length===0?a=r:a=new BA.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Ga.Sequence=xh;});var Ih=y(Ua=>{Object.defineProperty(Ua,"__esModule",{value:true});Ua.TunnelOnwards=void 0;var WA=ce(),Di=Pe(),MA=Et(),GA=ae(),UA=se(),HA=_n(),KA=Z(),zA=hr(),Th=class extends UA.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new WA.Container;if(e.AddContent(Di.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),r=t;if(r){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let u=0;u<r.content.length;u+=1){let l=r.content[u];l&&(s==-1&&l.commandType===Di.ControlCommand.CommandType.EvalStart?s=u:l.commandType===Di.ControlCommand.CommandType.EvalEnd&&(o=u));}for(let u=s+1;u<o;u+=1){let l=r.content[u];l.parent=null,e.AddContent(r.content[u]);}}}let i=(0, KA.asOrNull)(t,MA.Divert);if(i!=null&&i.hasVariableTarget){let a=new zA.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new GA.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new HA.Void);return e.AddContent(Di.ControlCommand.EvalEnd()),e.AddContent(Di.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Ua.TunnelOnwards=Th;});var Rh=y(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.ListDefinition=void 0;var kh=Ge(),$h=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let r=new kh.InkListItem(this.name,e);this._items.set(r.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[r,i]of this._itemNameToValues)if(i==e)return t=new kh.InkListItem(this.name,r),{result:t,exists:true};return t=kh.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let r=this._itemNameToValues.get(e.itemName);return r?{result:r,exists:true}:{result:0,exists:false}}};Ha.ListDefinition=$h;});var za=y(Ka=>{Object.defineProperty(Ka,"__esModule",{value:true});Ka.ListDefinition=void 0;var JA=Ge(),ZA=Ge(),XA=Rh(),QA=ae(),YA=se(),eP=It(),Vh=class extends YA.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let r of this.itemDefinitions)t.has(r.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${r.name}'`):t.set(r.name,r.seriesValue);return new XA.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=r=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(r)||null},this.GenerateRuntimeObject=()=>{var r,i;let a=new JA.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new ZA.InkListItem(((r=this.identifier)===null||r===void 0?void 0:r.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new QA.ListValue(a)};let t=1;for(let r of this.itemDefinitions)r.explicitValue!==null&&(t=r.explicitValue),r.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,eP.SymbolType.List);}};Ka.ListDefinition=Vh;});var jh=y(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.VariableAssignment=void 0;var tP=ce(),nP=vi(),rP=za(),iP=se(),t0=It(),sP=zt(),aP=dr(),oP=Z(),qh=class extends iP.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:r,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, nP.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new tP.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new sP.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!r,i instanceof rP.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?t0.SymbolType.Var:t0.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, oP.asOrNull)(this.expression,aP.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};Ja.VariableAssignment=qh;});var Dn=y(Qa=>{Object.defineProperty(Qa,"__esModule",{value:true});Qa.Weave=void 0;var n0=Is(),nt=ar(),Za=ma(),uP=Ca(),lP=ce(),Xa=cr(),cP=Et(),hP=lr(),dP=bt(),wt=Ci(),fP=Xg(),pP=se(),Lh=Nh(),mP=Zt(),gP=Ih(),yP=jh(),rt=Z(),Bh=class n extends pP.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let r=this.content.length-1;r>=0;--r){e=this.content[r];let i=(0, rt.asOrNull)(e,mP.Text);if(!(i&&i.text===`
22
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, rt.asOrNull)(e,n);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var r,i,a;let s=[...this.FindAll(wt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(nt.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let u=this.namedWeavePoints.get(((r=o.identifier)===null||r===void 0?void 0:r.name)||"");if(u){let l=u instanceof wt.Gather?"gather":"choice",c=u;this.Error(`A ${l} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let r=0;for(;r<this.content.length;){let i=this.content[r];if(i instanceof nt.Choice||i instanceof wt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=r;for(;r<this.content.length;){let h=(0, rt.asOrNull)(this.content[r],nt.Choice)||(0, rt.asOrNull)(this.content[r],wt.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;r+=1;}let u=r-o,l=this.content.slice(o,o+u);this.content.splice(o,u);let c=new n(l,s);this.InsertContent(o,c),r=o;}}r+=1;}},this.DetermineBaseIndentationFromContent=r=>{for(let i of r)if(i instanceof nt.Choice||i instanceof wt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new lP.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof nt.Choice||r instanceof wt.Gather)this.AddRuntimeForWeavePoint(r);else if(r instanceof n){let i=r;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(r.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=r=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=r.runtimeContainer;if(r.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof wt.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof Xa.Divert)u=o.runtimeObject;else {u=new cP.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new fP.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof wt.Gather)this.AddRuntimeForGather(r);else if(r instanceof nt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof wt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=r;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(r)&&(this.looseEnds.push(r),(0, rt.asOrNull)(r,nt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=r;},this.AddRuntimeForNestedWeave=r=>{this.AddGeneralRuntimeContent(r.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=r=>{if(r!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(r);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(r);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let r=null,i=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, rt.asOrNull)(s,n);o&&(!a&&r===null&&(r=o),a&&i===null&&(i=o)),(s instanceof Lh.Sequence||s instanceof Za.Conditional)&&(a=true);}if(!(r===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],u=false;if(a){if(o instanceof nt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof nt.Choice)){let l=r||i;l!==null&&(l.ReceiveLooseEnd(o),u=true);}}else r?.hasOwnProperty("ReceiveLooseEnd")&&r.ReceiveLooseEnd(o),u=true;u&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=r=>{this.looseEnds.push(r);},this.WeavePointNamed=r=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(r);return i||null},this.IsGlobalDeclaration=r=>{let i=(0, rt.asOrNull)(r,yP.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, rt.asOrNull)(r,uP.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=r=>{let i=[],a=r;if(a.content!==null)for(let u of a.content)this.IsGlobalDeclaration(u)||i.push(u);let s=(0, rt.asOrNull)(a.parent,n);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let u=o+1;u<s.content.length;u+=1){let l=s.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof nt.Choice||l instanceof wt.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof n0.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,r);}else {for(let a of this.content)if(a instanceof nt.Choice||a instanceof Xa.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,r);}},this.BadNestedTerminationHandler=r=>{let i=null;for(let s=r.parent;s!==null;s=s.parent)if(s instanceof Lh.Sequence||s instanceof Za.Conditional){i=(0, rt.asOrNull)(s,Za.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(nt.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,r);},this.ValidateFlowOfObjectsTerminates=(r,i,a)=>{let s=false,o=i;for(let u of r){if(u.Find(Xa.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof hP.DivertTarget))!==null&&(s=true),u.Find(gP.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof n0.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=r=>{if(r.content===null)return true;for(let i=r.content.length-1;i>=0;--i){let a=(0, rt.asOrNull)(r.content[i],Xa.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let r=[];for(let i of this.ancestry){let a=(0, rt.asOrNull)(i,dP.FlowBase);if(a)r.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let s of r){let o=s.ContentWithNameAtLevel(i);if(o&&o!==a){let u=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(u,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let r=this.parent;r!==null;r=r.parent)if(r instanceof Lh.Sequence||r instanceof Za.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Qa.Weave=Bh;});var bh=y(eo=>{Object.defineProperty(eo,"__esModule",{value:true});eo.ConditionalSingleBranch=void 0;var r0=ce(),Ya=Pe(),i0=Et(),CP=se(),vP=_t(),_P=ae(),EP=Zt(),bP=Dn(),SP=Z(),Wh=class extends CP.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, SP.asOrNull)(i,EP.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new r0.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(Ya.ControlCommand.Duplicate()),this._conditionalDivert=new i0.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Ya.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(vP.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Ya.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new _P.StringValue(`
23
- `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Ya.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new i0.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new r0.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new bP.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};eo.ConditionalSingleBranch=Wh;});var a0=y(to=>{Object.defineProperty(to,"__esModule",{value:true});to.CustomFlags=void 0;var s0;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(s0||(to.CustomFlags=s0={}));});var o0=y(no=>{Object.defineProperty(no,"__esModule",{value:true});no.DebugMetadata=void 0;var Mh=class n{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new n;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};no.DebugMetadata=Mh;});var u0=y(ro=>{Object.defineProperty(ro,"__esModule",{value:true});ro.ExternalDeclaration=void 0;var DP=se(),Gh=class extends DP.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};ro.ExternalDeclaration=Gh;});var l0=y(io=>{Object.defineProperty(io,"__esModule",{value:true});io.FlowDecl=void 0;var Uh=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};io.FlowDecl=Uh;});var Kh=y(so=>{Object.defineProperty(so,"__esModule",{value:true});so.Wrap=void 0;var wP=se(),Hh=class extends wP.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};so.Wrap=Hh;});var c0=y(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.Glue=void 0;var AP=Kh(),zh=class extends AP.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};ao.Glue=zh;});var uo=y(oo=>{Object.defineProperty(oo,"__esModule",{value:true});oo.Glue=void 0;var PP=We(),Jh=class extends PP.InkObject{toString(){return "Glue"}};oo.Glue=Jh;});var d0=y(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.IncDecExpression=void 0;var FP=Oa(),h0=et(),OP=bt(),xP=_t(),NP=ae(),TP=zt(),IP=hr(),kP=Dn(),Zh=class extends h0.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new IP.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new NP.IntValue(1)),i.AddContent(xP.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new TP.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof h0.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!r):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let r=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(r.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=r.isGlobal,!(this.parent instanceof kP.Weave)&&!(this.parent instanceof OP.FlowBase)&&!(this.parent instanceof FP.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};lo.IncDecExpression=Zh;});var Qh=y(co=>{Object.defineProperty(co,"__esModule",{value:true});co.IncludedFile=void 0;var $P=se(),Xh=class extends $P.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};co.IncludedFile=Xh;});var f0=y(ho=>{Object.defineProperty(ho,"__esModule",{value:true});ho.InfixOperator=void 0;var Yh=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};ho.InfixOperator=Yh;});var td=y(fo=>{Object.defineProperty(fo,"__esModule",{value:true});fo.Knot=void 0;var RP=bt(),p0=or(),ed=class extends RP.FlowBase{get flowLevel(){return p0.FlowLevel.Knot}constructor(e,t,r,i){super(e,t,r,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let r in this.subFlowsByName){let i=t.ContentWithNameAtLevel(r,p0.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(r),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(s,a);}}}};fo.Knot=ed;});var m0=y(po=>{Object.defineProperty(po,"__esModule",{value:true});po.List=void 0;var VP=et(),qP=Ge(),jP=Ge(),LP=ae(),nd=class extends VP.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new qP.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((r=s?.name)===null||r===void 0?void 0:r.split("."))||[],u=null,l="";o.length>1?(u=o[0],l=o[1]):l=o[0];let c=this.story.ResolveListItem(u,l,this);if(c===null)u===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(c.parent==null){this.Error(`Could not find list definition for item ${s}`);return}u||(u=((i=c.parent.identifier)===null||i===void 0?void 0:i.name)||null);let h=new jP.InkListItem(u,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new LP.ListValue(a));};}get typeName(){return "List"}};po.List=nd;});var id=y(mo=>{Object.defineProperty(mo,"__esModule",{value:true});mo.ListElementDefinition=void 0;var BP=se(),WP=It(),rd=class extends BP.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,r=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=r,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,WP.SymbolType.ListItem);}};mo.ListElementDefinition=rd;});var sd=y(go=>{Object.defineProperty(go,"__esModule",{value:true});go.StatementLevel=void 0;var g0;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(g0||(go.StatementLevel=g0={}));});var od=y(yo=>{Object.defineProperty(yo,"__esModule",{value:true});yo.Stitch=void 0;var MP=bt(),GP=or(),ad=class extends MP.FlowBase{get flowLevel(){return GP.FlowLevel.Stitch}constructor(e,t,r,i){super(e,t,r,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};yo.Stitch=ad;});var vo=y(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.Tag=void 0;var UP=We(),ud=class extends UP.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Co.Tag=ud;});var cd=y(_o=>{Object.defineProperty(_o,"__esModule",{value:true});_o.Choice=void 0;var HP=Be(),KP=Ae(),zP=We(),ld=class n extends zP.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, KP.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new HP.Path(e);}Clone(){let e=new n;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};_o.Choice=ld;});var dd=y(Eo=>{Object.defineProperty(Eo,"__esModule",{value:true});Eo.ListDefinitionsOrigin=void 0;var JP=Ge(),ZP=ae(),XP=Ae(),hd=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[r,i]of t.items){let a=JP.InkListItem.fromSerializedKey(r),s=new ZP.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let r=this._lists.get(e);return r?{result:r,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, XP.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Eo.ListDefinitionsOrigin=hd;});var pr=y(wo=>{Object.defineProperty(wo,"__esModule",{value:true});wo.JsonSerialisation=void 0;var bo=ce(),He=ae(),y0=uo(),K=Pe(),fr=En(),C0=Et(),v0=ta(),fd=hr(),_0=zt(),pd=_t(),E0=_n(),b0=vo(),QP=Be(),S0=cd(),YP=Rh(),e1=dd(),So=Ge(),he=Z(),wn=Ae(),Do=class n{static JArrayToRuntimeObjList(e,t=false){let r=e.length;t&&r--;let i=[];for(let a=0;a<r;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, wn.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WritePropertyStart(r),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let r of t)this.WriteRuntimeObject(e,r);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WriteIntProperty(r,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let r=(0, he.asOrNull)(t,bo.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, he.asOrNull)(t,C0.Divert);if(i){let C="->";i.isExternal?C="x()":i.pushesToStack&&(i.stackPushType==fr.PushPopType.Function?C="f()":i.stackPushType==fr.PushPopType.Tunnel&&(C="->t->"));let S;i.hasVariableTarget?S=i.variableDivertName:S=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(C,S),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, he.asOrNull)(t,v0.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, he.asOrNull)(t,He.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, he.asOrNull)(t,He.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, he.asOrNull)(t,He.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, he.asOrNull)(t,He.StringValue);if(l){l.isNewline?e.Write(`
24
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, he.asOrNull)(t,He.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, he.asOrNull)(t,He.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, wn.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let d=(0, he.asOrNull)(t,He.VariablePointerValue);if(d){e.WriteObjectStart(),e.WriteProperty("^var",d.value),e.WriteIntProperty("ci",d.contextIndex),e.WriteObjectEnd();return}if((0, he.asOrNull)(t,y0.Glue)){e.Write("<>");return}let m=(0, he.asOrNull)(t,K.ControlCommand);if(m){e.Write(n._controlCommandNames[m.commandType]);return}let f=(0, he.asOrNull)(t,pd.NativeFunctionCall);if(f){let C=f.name;C=="^"&&(C="L^"),e.Write(C);return}let v=(0, he.asOrNull)(t,fd.VariableReference);if(v){e.WriteObjectStart();let C=v.pathStringForCount;C!=null?e.WriteProperty("CNT?",C):e.WriteProperty("VAR?",v.name),e.WriteObjectEnd();return}let _=(0, he.asOrNull)(t,_0.VariableAssignment);if(_){e.WriteObjectStart();let C=_.isGlobal?"VAR=":"temp=";e.WriteProperty(C,_.variableName),_.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, he.asOrNull)(t,E0.Void)){e.Write("void");return}let E=(0, he.asOrNull)(t,b0.Tag);if(E){e.WriteObjectStart(),e.WriteProperty("#",E.text),e.WriteObjectEnd();return}let g=(0, he.asOrNull)(t,S0.Choice);if(g){this.WriteChoice(e,g);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let r in e)if(e.hasOwnProperty(r)){let i=this.JTokenToRuntimeObject(e[r]);if(i===null)return (0, wn.throwNullException)("inkObject");t.set(r,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let r in e)e.hasOwnProperty(r)&&t.set(r,parseInt(e[r]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return He.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new He.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new He.StringValue(t.substring(1));if(i==`
21
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};fa.CommentEliminator=rh;});var ma=C(pa=>{Object.defineProperty(pa,"__esModule",{value:true});pa.Conditional=void 0;var Iw=ce(),Lg=Pe(),kw=se(),ih=class extends kw.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new Iw.Container;this.initialCondition&&r.AddContent(this.initialCondition.runtimeObject);for(let i of this.branches){let a=i.runtimeObject;r.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&r.AddContent(Lg.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Lg.ControlCommand.NoOp(),r.AddContent(this._reJoinTarget),r},this.initialCondition&&this.AddContent(this.initialCondition),this.branches!==null&&this.AddContent(this.branches);}get typeName(){return "Conditional"}ResolveReferences(e){let t=this._reJoinTarget.path;for(let r of this.branches){if(!r.returnDivert)throw new Error;r.returnDivert.targetPath=t;}super.ResolveReferences(e);}};pa.Conditional=ih;});var Jt=C(ga=>{Object.defineProperty(ga,"__esModule",{value:true});ga.Text=void 0;var $w=se(),Rw=ae(),sh=class extends $w.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Rw.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};ga.Text=sh;});var Ca=C(ya=>{Object.defineProperty(ya,"__esModule",{value:true});ya.ConstantDeclaration=void 0;var Vw=se(),qw=It(),ah=class extends Vw.ParsedObject{get constantName(){var e;return (e=this.constantIdentifier)===null||e===void 0?void 0:e.name}get expression(){if(!this._expression)throw new Error;return this._expression}constructor(e,t){super(),this._expression=null,this.GenerateRuntimeObject=()=>null,this.constantIdentifier=e,t&&(this._expression=this.AddContent(t));}get typeName(){return "CONST"}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.constantIdentifier,qw.SymbolType.Var);}};ya.ConstantDeclaration=ah;});var ar=C(va=>{Object.defineProperty(va,"__esModule",{value:true});va.FlowLevel=void 0;var Bg;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Bg||(va.FlowLevel=Bg={}));});var Ci=C(_a=>{Object.defineProperty(_a,"__esModule",{value:true});_a.Gather=void 0;var jw=ce(),Lw=se(),Bw=It(),oh=class extends Lw.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}get runtimeContainer(){return this.runtimeObject}constructor(e,t){super(),this.indentationDepth=t,this.GenerateRuntimeObject=()=>{let r=new jw.Container;if(r.name=this.name,this.story.countAllVisits&&(r.visitsShouldBeCounted=true),r.countingAtStartOnly=true,this.content)for(let i of this.content)r.AddContent(i.runtimeObject);return r},this.toString=()=>{var r,i;return `- ${!((r=this.identifier)===null||r===void 0)&&r.name?"("+((i=this.identifier)===null||i===void 0?void 0:i.name)+")":"gather"}`},e&&(this.identifier=e);}get typeName(){return "Gather"}ResolveReferences(e){super.ResolveReferences(e),this.identifier&&(this.identifier.name||"").length>0&&e.CheckForNamingCollisions(this,this.identifier,Bw.SymbolType.SubFlowAndWeave);}};_a.Gather=oh;});var bn=C(ba=>{Object.defineProperty(ba,"__esModule",{value:true});ba.Path=void 0;var Ea=J(),Wg=bt(),or=ar(),Ww=Sn(),uh=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?or.FlowLevel.Story:this._baseTargetLevel}get baseLevelIsAmbiguous(){return !this._baseTargetLevel}get firstComponent(){return this.components==null||!this.components.length?null:this.components[0].name}get numberOfComponents(){return this.components?this.components.length:0}get dotSeparatedComponents(){return this._dotSeparatedComponents==null&&(this._dotSeparatedComponents=(this.components?this.components:[]).map(e=>e.name).filter(Ea.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===or.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=r=>{if(this.components==null||this.components.length==0)return null;let i=this.ResolveBaseTarget(r);return i===null?null:this.components.length>1?this.ResolveTailComponents(i):i},this.ResolveBaseTarget=r=>{let i=this.firstComponent,a=r;for(;a;){let s=a===r,o=this.GetChildFromContext(a,i,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=r=>{let i=r;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,u=(0, Ea.asOrNull)(i,Wg.FlowBase);if(u!==null?o=u.flowLevel+1:o=or.FlowLevel.WeavePoint,i=this.GetChildFromContext(i,s,o),i===null)break}return i},this.GetChildFromContext=(r,i,a,s=false)=>{let o=a===null,u=(0, Ea.asOrNull)(r,Ww.Weave);if(i&&u!==null&&(o||a===or.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Ea.asOrNull)(r,Wg.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===or.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values(or.FlowLevel).includes(e)?(this._baseTargetLevel=e,this.components=t||[]):Array.isArray(e)?(this._baseTargetLevel=null,this.components=e||[]):(this._baseTargetLevel=null,this.components=[e]);}get typeName(){return "Path"}};ba.Path=uh;});var hh=C(Sa=>{Object.defineProperty(Sa,"__esModule",{value:true});Sa.ReturnType=void 0;var Mw=se(),Gw=ce(),lh=Pe(),Uw=vn(),ch=class extends Mw.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new Gw.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(lh.ControlCommand.EvalStart()),t.AddContent(new Uw.Void),t.AddContent(lh.ControlCommand.EvalEnd())),t.AddContent(lh.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Sa.ReturnType=ch;});var vi=C(Da=>{Object.defineProperty(Da,"__esModule",{value:true});Da.ClosestFlowBase=void 0;function Hw(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Da.ClosestFlowBase=Hw;});var Aa=C(wa=>{Object.defineProperty(wa,"__esModule",{value:true});wa.Identifier=void 0;var dh=class n{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new n("DONE")}};wa.Identifier=dh;});var bt=C(Pa=>{Object.defineProperty(Pa,"__esModule",{value:true});Pa.FlowBase=void 0;var Kw=sr(),fh=lr(),zw=ur(),St=ar(),Jw=Ci(),Zw=se(),Xw=bn(),Qw=hh(),Yw=ce(),eA=Et(),tA=Kt(),ph=It(),nA=Sn(),rA=vi(),iA=Aa(),Mg=J(),mh=class n extends Zw.ParsedObject{get hasParameters(){return this.args!==null&&this.args.length>0}get subFlowsByName(){return this._subFlowsByName}get typeName(){return this.isFunction?"Function":String(this.flowLevel)}get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t=null,r=null,i=false,a=false){super(),this.isFunction=i,this._rootWeave=null,this._subFlowsByName=new Map,this._startingSubFlowDivert=null,this._startingSubFlowRuntime=null,this._firstChildFlow=null,this.variableDeclarations=new Map,this.identifier=null,this.args=null,this.iamFlowbase=()=>true,this.SplitWeaveAndSubFlowContent=(s,o)=>{var u,l;let c=[],h=[];this._subFlowsByName=new Map;for(let m of s){let g=(0, Mg.asOrNull)(m,n);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),h.push(m),!((u=g.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=g.identifier)===null||l===void 0?void 0:l.name,g)):c.push(m);}o&&c.push(new Jw.Gather(null,1),new fh.Divert(new Xw.Path(iA.Identifier.Done())));let f=[];return c.length>0&&(this._rootWeave=new nA.Weave(c,0),f.push(this._rootWeave)),h.length>0&&f.push(...h),f},this.ResolveVariableWithName=(s,o)=>{var u;let l={},c=o===null?this:(0, rA.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((u=h.identifier)===null||u===void 0?void 0:u.name)===s)return l.found=true,l.isArgument=true,l.ownerFlow=c,l}if(c!==this.story&&c.variableDeclarations.has(s))return l.found=true,l.ownerFlow=c,l.isTemporary=true,l}return this.story.variableDeclarations.has(s)?(l.found=true,l.ownerFlow=this.story,l.isGlobal=true,l):(l.found=false,l)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let u=this.variableDeclarations.get(o),l="";u.debugMetadata&&(l=` (${u.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${l}`,s,false);return}this.variableDeclarations.set(s.variableName,s);},this.ResolveWeavePointNaming=()=>{this._rootWeave&&this._rootWeave.ResolveWeavePointNaming();for(let[,s]of this._subFlowsByName)s.hasOwnProperty("ResolveWeavePointNaming")&&s.ResolveWeavePointNaming();},this.GenerateRuntimeObject=()=>{var s;let o=null;this.isFunction?this.CheckForDisallowedFunctionFlowControl():(this.flowLevel===St.FlowLevel.Knot||this.flowLevel===St.FlowLevel.Stitch)&&(o=this.Find(Qw.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let u=new Yw.Container;u.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(u.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(u);let l=0;for(;this.content!==null&&l<this.content.length;){let c=this.content[l];if(c instanceof n){let h=c,f=h.runtimeObject;l===0&&!h.hasParameters&&this.flowLevel===St.FlowLevel.Knot&&(this._startingSubFlowDivert=new eA.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let m=f,g=u.namedContent.get(m.name)||null;if(g){let p=`${this.GetType()} already contains flow named '${m.name}' (at ${g.debugMetadata})`;this.Error(p,h);}u.AddToNamedContentOnly(m);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==St.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),u},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let u=this.args.length-1;u>=0;--u){let l=((o=this.args[u].identifier)===null||o===void 0?void 0:o.name)||null,c=new tA.VariableAssignment(l,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,u=false)=>{var l;if((o===this.flowLevel||o===null)&&s===((l=this.identifier)===null||l===void 0?void 0:l.name))return this;if(o===St.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===St.FlowLevel.WeavePoint)return u?this.DeepSearchForAnyLevelContent(s):null}if(o!==null&&o<this.flowLevel)return null;let c=this._subFlowsByName.get(s)||null;return c&&(o===null||o===c.flowLevel)?c:u?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,St.FlowLevel.WeavePoint,false);if(o)return o;for(let[,u]of this._subFlowsByName){let l=u.ContentWithNameAtLevel(s,null,true);if(l)return l}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==St.FlowLevel.Knot&&this.Error("Functions cannot be stitches - i.e. they should be defined as '== function myFunc ==' rather than internal to another knot.");for(let[u,l]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${u}' within the function '${this.identifier}'`,l);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(fh.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof zw.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(Kw.Choice)();for(let u of o)this.Error(`Functions may not contain choices, but saw '${u}'`,u);},this.WarningInTermination=s=>{let o="Apparent loose end exists where the flow runs out. Do you need a '-> DONE' statement, choice or divert?";s.parent===this._rootWeave&&this._firstChildFlow&&(o=`${o} Note that if you intend to enter '${this._firstChildFlow.identifier}' next, you need to divert to it explicitly.`);let u=(0, Mg.asOrNull)(s,fh.Divert);u&&u.isTunnel&&(o+=` When final tunnel to '${u.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=r,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,r;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let i of this.args)e.CheckForNamingCollisions(this,i.identifier,ph.SymbolType.Arg,"argument");for(let i=0;i<this.args.length;i+=1)for(let a=i+1;a<this.args.length;a+=1)((t=this.args[i].identifier)===null||t===void 0?void 0:t.name)==((r=this.args[a].identifier)===null||r===void 0?void 0:r.name)&&this.Error(`Multiple arguments with the same name: '${this.args[i].identifier}'`);}if(this.flowLevel!==St.FlowLevel.Story){let i=this.flowLevel===St.FlowLevel.Knot?ph.SymbolType.Knot:ph.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Pa.FlowBase=mh;});var Oa=C(Fa=>{Object.defineProperty(Fa,"__esModule",{value:true});Fa.ContentList=void 0;var sA=ce(),aA=se(),oA=Jt(),uA=J(),gh=class extends aA.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let r=this.content.length-1;r>=0;--r){let i=(0, uA.asOrNull)(this.content[r],oA.Text);if(i===null)break;if(i.text=i.text.replace(new RegExp(/[ \t]/g),""),i.text.length===0)this.content.splice(r,1);else break}},this.GenerateRuntimeObject=()=>{let r=new sA.Container;if(this.content!==null)for(let i of this.content){let a=i.runtimeObject;a&&r.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(r),r},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Fa.ContentList=gh;});var cr=C(xa=>{Object.defineProperty(xa,"__esModule",{value:true});xa.VariableReference=void 0;var lA=We(),cA=Be(),yh=class extends lA.InkObject{get containerForCount(){return this.pathForCount===null?null:this.ResolvePath(this.pathForCount).container}get pathStringForCount(){return this.pathForCount===null?null:this.CompactPathString(this.pathForCount)}set pathStringForCount(e){e===null?this.pathForCount=null:this.pathForCount=new cA.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};xa.VariableReference=yh;});var hr=C(Na=>{Object.defineProperty(Na,"__esModule",{value:true});Na.VariableReference=void 0;var hA=Oa(),dA=et(),Gg=bt(),fA=bn(),pA=cr(),mA=Sn(),gA=Aa(),Ug=J(),Ch=class extends dA.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Ug.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new gA.Identifier(e)}get runtimeVarRef(){return this._runtimeVarRef}constructor(e){super(),this.pathIdentifiers=e,this._runtimeVarRef=null,this.isConstantReference=false,this.isListItemReference=false,this.GenerateIntoContainer=t=>{let r=this.story.constants.get(this.name);if(r){r.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new pA.VariableReference(this.name),this.path.length===1||this.path.length===2){let i="",a="";this.path.length===1?i=this.path[0]:(a=this.path[0],i=this.path[1]),this.story.ResolveListItem(a,i,this)&&(this.isListItemReference=true);}t.AddContent(this._runtimeVarRef);},this.toString=()=>`{${this.path.join(".")}}`;}get typeName(){return "ref"}ResolveReferences(e){if(super.ResolveReferences(e),this.isConstantReference||this.isListItemReference)return;let t=new fA.Path(this.pathIdentifiers),r=t.ResolveFromContext(this);if(r){if(!r.containerForCounting)throw new Error;if(r.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=r.runtimePath,this._runtimeVarRef.name=null;let i=(0, Ug.asOrNull)(r,Gg.FlowBase);i&&i.isFunction&&(this.parent instanceof mA.Weave||this.parent instanceof hA.ContentList||this.parent instanceof Gg.FlowBase)&&this.Warning(`'${i.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${i.identifier}()`);return}if(this.path.length>1){let i=`Could not find target for read count: ${t}`;this.path.length<=2&&(i+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(i);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};Na.VariableReference=Ch;});var _i=C($a=>{Object.defineProperty($a,"__esModule",{value:true});$a.FunctionCall=void 0;var Dt=Pe(),yA=lr(),CA=ur(),vA=et(),_A=Ge(),EA=ae(),Ia=_t(),Hg=Js(),bA=bn(),SA=ae(),DA=hr(),Ta=J(),ka=class n extends vA.Expression{get proxyDivert(){return this._proxyDivert}get name(){return this._proxyDivert.target.firstComponent||""}get args(){return this._proxyDivert.args}get runtimeDivert(){return this._proxyDivert.runtimeDivert}get isChoiceCount(){return this.name==="CHOICE_COUNT"}get isTurns(){return this.name==="TURNS"}get isTurnsSince(){return this.name==="TURNS_SINCE"}get isRandom(){return this.name==="RANDOM"}get isSeedRandom(){return this.name==="SEED_RANDOM"}get isListRange(){return this.name==="LIST_RANGE"}get isListRandom(){return this.name==="LIST_RANDOM"}get isReadCount(){return this.name==="READ_COUNT"}constructor(e,t){super(),this._divertTargetToCount=null,this._variableReferenceToCount=null,this.shouldPopReturnedValue=false,this.GenerateIntoContainer=r=>{let i=this.story.ResolveList(this.name),a=false;if(this.isChoiceCount)this.args.length>0&&this.Error("The CHOICE_COUNT() function shouldn't take any arguments"),r.AddContent(Dt.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(Dt.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Ta.asOrNull)(this.args[0],CA.DivertTarget),o=(0, Ta.asOrNull)(this.args[0],DA.VariableReference);if(this.args.length!==1||s===null&&o===null){this.Error(`The ${this.name}() function should take one argument: a divert target to the target knot, stitch, gather or choice you want to check. e.g. TURNS_SINCE(-> myKnot)`);return}s?(this._divertTargetToCount=s,this.AddContent(this._divertTargetToCount),this._divertTargetToCount.GenerateIntoContainer(r)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(r)),this.isTurnsSince?r.AddContent(Dt.ControlCommand.TurnsSince()):r.AddContent(Dt.ControlCommand.ReadCount());}else if(this.isRandom){this.args.length!==2&&this.Error("RANDOM should take 2 parameters: a minimum and a maximum integer");for(let s=0;s<this.args.length;s+=1){let o=(0, Ta.asOrNull)(this.args[s],Hg.NumberExpression);if(o&&!o.isInt()){let u=s===0?"minimum":"maximum";this.Error(`RANDOM's ${u} parameter should be an integer`);}this.args[s].GenerateIntoContainer(r);}r.AddContent(Dt.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Ta.asOrNull)(this.args[0],Hg.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.SeedRandom());}else if(this.isListRange){this.args.length!==3&&this.Error("LIST_RANGE should take 3 parameters - a list, a min and a max");for(let s=0;s<this.args.length;s+=1)this.args[s].GenerateIntoContainer(r);r.AddContent(Dt.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.ListRandom());else if(Ia.NativeFunctionCall.CallExistsWithName(this.name)){let s=Ia.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${n.name} should take ${s.numberOfParameters} parameter`;s.numberOfParameters>1&&(o+="s"),this.Error(o);}for(let o=0;o<this.args.length;o+=1)this.args[o].GenerateIntoContainer(r);r.AddContent(Ia.NativeFunctionCall.CallWithName(this.name));}else if(i!==null)if(this.args.length>1&&this.Error("Can currently only construct a list from one integer (or an empty list from a given list definition)"),this.args.length===1)r.AddContent(new SA.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(Dt.ControlCommand.ListFromInt());else {let s=new _A.InkList;s.SetInitialOriginName(this.name),r.AddContent(new EA.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(Dt.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new yA.Divert(new bA.Path(e),t),this._proxyDivert.isFunctionCall=true,this.AddContent(this._proxyDivert);}get typeName(){return "FunctionCall"}ResolveReferences(e){if(super.ResolveReferences(e),!this.content.includes(this._proxyDivert)&&this.args!==null)for(let t of this.args)t.ResolveReferences(e);if(this._divertTargetToCount){let t=this._divertTargetToCount.divert,r=t.runtimeDivert.variableDivertName!=null;if(r){this.Error(`When getting the TURNS_SINCE() of a variable target, remove the '->' - i.e. it should just be TURNS_SINCE(${t.runtimeDivert.variableDivertName})`);return}let i=t.targetContent;if(i===null)r||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!i.containerForCounting)throw new Error;i.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${n.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};$a.FunctionCall=ka;ka.IsBuiltIn=n=>Ia.NativeFunctionCall.CallExistsWithName(n)?true:n==="CHOICE_COUNT"||n==="TURNS_SINCE"||n==="TURNS"||n==="RANDOM"||n==="SEED_RANDOM"||n==="LIST_VALUE"||n==="LIST_RANDOM"||n==="READ_COUNT";});var _h=C(Ra=>{Object.defineProperty(Ra,"__esModule",{value:true});Ra.MultipleConditionExpression=void 0;var wA=et(),AA=_t(),vh=class extends wA.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let r=true;for(let i of this.subExpressions)i.GenerateIntoContainer(t),r||t.AddContent(AA.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Ra.MultipleConditionExpression=vh;});var ur=C(Va=>{Object.defineProperty(Va,"__esModule",{value:true});Va.DivertTarget=void 0;var PA=Gc(),FA=sr(),OA=ma(),xA=Dh(),NA=ae(),Eh=et(),TA=bt(),Kg=_i(),IA=_h(),zg=hr(),bh=J(),Sh=class n extends Eh.Expression{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}get runtimeDivertTargetValue(){if(!this._runtimeDivertTargetValue)throw new Error;return this._runtimeDivertTargetValue}constructor(e){super(),this._runtimeDivert=null,this._runtimeDivertTargetValue=null,this.GenerateIntoContainer=t=>{this.divert.GenerateRuntimeObject(),this._runtimeDivert=this.divert.runtimeDivert,this._runtimeDivertTargetValue=new NA.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, bh.asOrNull)(t,n);if(!r||!this.divert.target||!r.divert.target)return false;let i=this.divert.target.dotSeparatedComponents,a=r.divert.target.dotSeparatedComponents;return i===a},this.divert=this.AddContent(e);}get typeName(){return "DivertTarget"}ResolveReferences(e){if(super.ResolveReferences(e),this.divert.isDone||this.divert.isEnd){this.Error("Can't use -> DONE or -> END as variable divert targets",this);return}let t=this;for(;t&&t instanceof Eh.Expression;){let i=false,a=false,s=t.parent;if(s instanceof PA.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof zg.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof zg.VariableReference)||(i=true),a=true;}else if(s instanceof Kg.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof Eh.Expression||s instanceof IA.MultipleConditionExpression||s instanceof FA.Choice&&s.condition===t||s instanceof OA.Conditional||s instanceof xA.ConditionalSingleBranch)&&(i=true,a=true);if(i&&this.Error(`Can't use a divert target like that. Did you intend to call '${this.divert.target}' as a function: likeThis(), or check the read count: likeThis, with no arrows?`,this),a)break;t=s;}if(this.runtimeDivert.hasVariableTarget){if(!this.divert.target)throw new Error;this.Error(`Since '${this.divert.target.dotSeparatedComponents}' is a variable, it shouldn't be preceded by '->' here.`);}this.runtimeDivert.targetPath&&(this.runtimeDivertTargetValue.targetPath=this.runtimeDivert.targetPath);let r=this.divert.targetContent;if(r!==null){let i=r.containerForCounting;if(i!==null){let s=(0, bh.asOrNull)(this.parent,Kg.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, bh.asOrNull)(r,TA.FlowBase);if(a!=null&&a.args!==null)for(let s of a.args)s.isByReference&&this.Error(`Can't store a divert target to a knot or function that has by-reference arguments ('${a.identifier}' has 'ref ${s.identifier}').`);}}};Va.DivertTarget=Sh;});var lr=C(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.Divert=void 0;var kA=ce(),Ei=Pe(),$A=Et(),wh=ur(),Ah=bt(),RA=_i(),VA=se(),Jg=bn(),qA=Be(),Zg=_n(),jA=ae(),Xg=hr(),LA=vi(),bi=J(),Ph=class extends VA.ParsedObject{get runtimeDivert(){if(!this._runtimeDivert)throw new Error;return this._runtimeDivert}set runtimeDivert(e){this._runtimeDivert=e;}get isEnd(){return !!(this.target&&this.target.dotSeparatedComponents==="END")}get isDone(){return !!(this.target&&this.target.dotSeparatedComponents==="DONE")}constructor(e,t){super(),this.args=[],this.target=null,this.targetContent=null,this._runtimeDivert=null,this.isFunctionCall=false,this.isEmpty=false,this.isTunnel=false,this.isThread=false,this.GenerateRuntimeObject=()=>{if(this.isEnd)return Ei.ControlCommand.End();if(this.isDone)return Ei.ControlCommand.Done();this.runtimeDivert=new $A.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let r=this.args!==null&&this.args.length>0;if(r||this.isFunctionCall||this.isTunnel||this.isThread){let i=new kA.Container;if(r){this.isFunctionCall||i.AddContent(Ei.ControlCommand.EvalStart());let a=null;this.targetContent&&(a=this.targetContent.args);for(let s=0;s<this.args.length;++s){let o=this.args[s],u=null;if(a&&s<a.length&&(u=a[s]),u&&u.isByReference){let l=(0, bi.asOrNull)(o,Xg.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new Jg.Path(l.pathIdentifiers);if(c.ResolveFromContext(this)){this.Error(`can't pass a read count by reference. '${c.dotSeparatedComponents}' is a knot/stitch/label, but '${this.target.dotSeparatedComponents}' requires the name of a VAR to be passed.`);break}let f=new jA.VariablePointerValue(l.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Ei.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Ei.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Zg.PushPopType.Function:Zg.PushPopType.Tunnel),i.AddContent(this.runtimeDivert),i}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let r=this.PathAsVariableName();if(r!==null){let i=(0, bi.asOrNull)((0, LA.ClosestFlowBase)(this),Ah.FlowBase);if(i){let a=i.ResolveVariableWithName(r,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var u;return ((u=o.identifier)===null||u===void 0?void 0:u.name)==r});s&&!s.isDivertTarget&&this.Error(`Since '${s.identifier}' is used as a variable divert target (on ${this.debugMetadata}), it should be marked as: -> ${s.identifier}`,a.ownerFlow);}this.runtimeDivert.variableDivertName=r;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let r=0;if(this.args!==null&&this.args.length>0&&(r=this.args.length),this.targetContent===null)return;let i=(0, bi.asOrNull)(this.targetContent,Ah.FlowBase);if(r===0&&(i===null||!i.hasParameters))return;if(i===null&&r>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(i!==null&&(i.args===null||!i.args&&r>0)){this.Error(`target (${i.name}) doesn't take parameters`);return}else if(this.parent instanceof wh.DivertTarget){r>0&&this.Error("can't store arguments in a divert target variable");return}let a=i.args.length;if(a!==r){let s;r===0?s="but there weren't any passed to it":r<a?s=`but only got ${r}`:s=`but got ${r}`,this.Error(`to '${i.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=i.args[s],u=this.args[s];if(o.isDivertTarget){let l=(0, bi.asOrNull)(u,Xg.VariableReference);if(!(u instanceof wh.DivertTarget)&&l===null)this.Error(`Target '${i.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${u}`,u);else if(l){let c=new Jg.Path(l.pathIdentifiers);c.ResolveFromContext(l)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(i===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=r=>{let i=this.target?this.target.firstComponent:null,a=r.externals.get(i);if(!a)throw new Error("external not found");let s=a.argumentNames.length,o=0;this.args&&(o=this.args.length),o!==s&&this.Error(`incorrect number of arguments sent to external function '${i}'. Expected ${s} but got ${o}`);},this.toString=()=>{let r="";if(this.target!==null)r+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(r+=" ->"),this.isFunctionCall&&(r+=" ()"),r},e&&(this.target=e),t&&(this.args=t,this.AddContent(t));}get typeName(){return "Divert"}ResolveReferences(e){if(this.isEmpty||this.isEnd||this.isDone)return;if(!this.runtimeDivert)throw new Error;this.targetContent&&(this.runtimeDivert.targetPath=this.targetContent.runtimePath),super.ResolveReferences(e);let t=(0, bi.asOrNull)(this.targetContent,Ah.FlowBase);t&&(!t.isFunction&&this.isFunctionCall?super.Error(`${t.identifier} hasn't been marked as a function, but it's being called as one. Do you need to declare the knot as '== function ${t.identifier} =='?`):t.isFunction&&!this.isFunctionCall&&!(this.parent instanceof wh.DivertTarget)&&super.Error(t.identifier+" can't be diverted to. It can only be called as a function since it's been marked as such: '"+t.identifier+"(...)'"));let r=this.targetContent!==null,i=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(i=RA.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),i||a){this.isFunctionCall||super.Error(`${this.target.firstComponent} must be called as a function: ~ ${this.target.firstComponent}()`),a&&(this.runtimeDivert.isExternal=true,this.args!==null&&(this.runtimeDivert.externalArgs=this.args.length),this.runtimeDivert.pushesToStack=false,this.runtimeDivert.targetPath=new qA.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!r&&!i&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,r=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,r):super.Error(`Divert ${e}`,t,r);}};qa.Divert=Ph;});var Qg=C(ja=>{Object.defineProperty(ja,"__esModule",{value:true});ja.GatherPointToResolve=void 0;var Fh=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};ja.GatherPointToResolve=Fh;});var Yg=C(La=>{Object.defineProperty(La,"__esModule",{value:true});La.SequenceDivertToResolve=void 0;var Oh=class{constructor(e,t){this.divert=e,this.targetContent=t;}};La.SequenceDivertToResolve=Oh;});var xh=C(Ba=>{Object.defineProperty(Ba,"__esModule",{value:true});Ba.SequenceType=void 0;var e0;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(e0||(Ba.SequenceType=e0={}));});var Ih=C(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.Sequence=void 0;var t0=ce(),ht=Pe(),Nh=Et(),Si=ae(),Wa=_t(),BA=se(),WA=Yg(),Ma=xh(),MA=Sn(),Th=class extends BA.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new t0.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(ht.ControlCommand.EvalStart()),r.AddContent(ht.ControlCommand.VisitIndex());let i=(this.sequenceType&Ma.SequenceType.Once)>0,a=(this.sequenceType&Ma.SequenceType.Cycle)>0,s=(this.sequenceType&Ma.SequenceType.Stopping)>0,o=(this.sequenceType&Ma.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new Si.IntValue(u-1)),r.AddContent(Wa.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new Si.IntValue(this.sequenceElements.length)),r.AddContent(Wa.NativeFunctionCall.CallWithName("%"))),o){let c=ht.ControlCommand.NoOp();if(i||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(ht.ControlCommand.Duplicate()),r.AddContent(new Si.IntValue(f)),r.AddContent(Wa.NativeFunctionCall.CallWithName("=="));let m=new Nh.Divert;m.isConditional=true,r.AddContent(m),this.AddDivertToResolve(m,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new Si.IntValue(h)),r.AddContent(ht.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(ht.ControlCommand.EvalEnd());let l=ht.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(ht.ControlCommand.EvalStart()),r.AddContent(ht.ControlCommand.Duplicate()),r.AddContent(new Si.IntValue(c)),r.AddContent(Wa.NativeFunctionCall.CallWithName("==")),r.AddContent(ht.ControlCommand.EvalEnd());let h=new Nh.Divert;h.isConditional=true,r.AddContent(h);let f;c<this.sequenceElements.length?f=this.sequenceElements[c].runtimeObject:f=new t0.Container,f.name=`s${c}`,f.InsertContent(ht.ControlCommand.PopEvaluatedValue(),0);let m=new Nh.Divert;f.AddContent(m),r.AddToNamedContentOnly(f),this.AddDivertToResolve(h,f),this.AddDivertToResolve(m,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new WA.SequenceDivertToResolve(r,i));},this.sequenceType=t,this.sequenceElements=[];for(let r of e){let i=r.content,a=null;i===null||i.length===0?a=r:a=new MA.Weave(i),this.sequenceElements.push(a),this.AddContent(a);}}get typeName(){return "Sequence"}ResolveReferences(e){super.ResolveReferences(e);for(let t of this._sequenceDivertsToResolve)t.divert.targetPath=t.targetContent.path;}};Ga.Sequence=Th;});var $h=C(Ua=>{Object.defineProperty(Ua,"__esModule",{value:true});Ua.TunnelOnwards=void 0;var GA=ce(),Di=Pe(),UA=Et(),HA=ae(),KA=se(),zA=vn(),JA=J(),ZA=cr(),kh=class extends KA.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new GA.Container;if(e.AddContent(Di.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),r=t;if(r){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let u=0;u<r.content.length;u+=1){let l=r.content[u];l&&(s==-1&&l.commandType===Di.ControlCommand.CommandType.EvalStart?s=u:l.commandType===Di.ControlCommand.CommandType.EvalEnd&&(o=u));}for(let u=s+1;u<o;u+=1){let l=r.content[u];l.parent=null,e.AddContent(r.content[u]);}}}let i=(0, JA.asOrNull)(t,UA.Divert);if(i!=null&&i.hasVariableTarget){let a=new ZA.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new HA.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new zA.Void);return e.AddContent(Di.ControlCommand.EvalEnd()),e.AddContent(Di.ControlCommand.PopTunnel()),e},this.toString=()=>` -> ${this._divertAfter}`;}get divertAfter(){return this._divertAfter}set divertAfter(e){this._divertAfter=e,this._divertAfter&&this.AddContent(this._divertAfter);}get typeName(){return "TunnelOnwards"}ResolveReferences(e){super.ResolveReferences(e),this.divertAfter&&this.divertAfter.targetContent&&(this._overrideDivertTarget.targetPath=this.divertAfter.targetContent.runtimePath);}};Ua.TunnelOnwards=kh;});var qh=C(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.ListDefinition=void 0;var Rh=Ge(),Vh=class{constructor(e,t){this._name=e||"",this._items=null,this._itemNameToValues=t||new Map;}get name(){return this._name}get items(){if(this._items==null){this._items=new Map;for(let[e,t]of this._itemNameToValues){let r=new Rh.InkListItem(this.name,e);this._items.set(r.serialized(),t);}}return this._items}ValueForItem(e){if(!e.itemName)return 0;let t=this._itemNameToValues.get(e.itemName);return typeof t<"u"?t:0}ContainsItem(e){return !e.itemName||e.originName!=this.name?false:this._itemNameToValues.has(e.itemName)}ContainsItemWithName(e){return this._itemNameToValues.has(e)}TryGetItemWithValue(e,t){for(let[r,i]of this._itemNameToValues)if(i==e)return t=new Rh.InkListItem(this.name,r),{result:t,exists:true};return t=Rh.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let r=this._itemNameToValues.get(e.itemName);return r?{result:r,exists:true}:{result:0,exists:false}}};Ha.ListDefinition=Vh;});var za=C(Ka=>{Object.defineProperty(Ka,"__esModule",{value:true});Ka.ListDefinition=void 0;var XA=Ge(),QA=Ge(),YA=qh(),eP=ae(),tP=se(),nP=It(),jh=class extends tP.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let r of this.itemDefinitions)t.has(r.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${r.name}'`):t.set(r.name,r.seriesValue);return new YA.ListDefinition(((e=this.identifier)===null||e===void 0?void 0:e.name)||"",t)}constructor(e){super(),this.itemDefinitions=e,this.identifier=null,this.variableAssignment=null,this._elementsByName=null,this.ItemNamed=r=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(r)||null},this.GenerateRuntimeObject=()=>{var r,i;let a=new XA.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new QA.InkListItem(((r=this.identifier)===null||r===void 0?void 0:r.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((i=this.identifier)===null||i===void 0?void 0:i.name)||""),new eP.ListValue(a)};let t=1;for(let r of this.itemDefinitions)r.explicitValue!==null&&(t=r.explicitValue),r.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,nP.SymbolType.List);}};Ka.ListDefinition=jh;});var Bh=C(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.VariableAssignment=void 0;var rP=ce(),iP=vi(),sP=za(),aP=se(),n0=It(),oP=Kt(),uP=hr(),lP=J(),Lh=class extends aP.ParsedObject{get variableName(){return this.variableIdentifier.name}get typeName(){return this.isNewTemporaryDeclaration?"temp":this.isGlobalDeclaration?this.listDefinition!==null?"LIST":"VAR":"variable assignment"}get isDeclaration(){return this.isGlobalDeclaration||this.isNewTemporaryDeclaration}constructor({assignedExpression:e,isGlobalDeclaration:t,isTemporaryNewDeclaration:r,listDef:i,variableIdentifier:a}){super(),this._runtimeAssignment=null,this.expression=null,this.listDefinition=null,this.GenerateRuntimeObject=()=>{let s=null;if(this.isGlobalDeclaration?s=this.story:this.isNewTemporaryDeclaration&&(s=(0, iP.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new rP.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new oP.VariableAssignment(this.variableName,this.isNewTemporaryDeclaration),o.AddContent(this._runtimeAssignment),o},this.toString=()=>`${this.isGlobalDeclaration?"VAR":this.isNewTemporaryDeclaration?"~ temp":""} ${this.variableName}`,this.variableIdentifier=a,this.isGlobalDeclaration=!!t,this.isNewTemporaryDeclaration=!!r,i instanceof sP.ListDefinition?(this.listDefinition=this.AddContent(i),this.listDefinition.variableAssignment=this,this.isGlobalDeclaration=true):e&&(this.expression=this.AddContent(e));}ResolveReferences(e){if(super.ResolveReferences(e),this.isDeclaration&&this.listDefinition===null&&e.CheckForNamingCollisions(this,this.variableIdentifier,this.isGlobalDeclaration?n0.SymbolType.Var:n0.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, lP.asOrNull)(this.expression,uP.VariableReference);t&&!t.isConstantReference&&!t.isListItemReference&&this.Error("global variable assignments cannot refer to other variables, only literal values, constants and list items");}if(!this.isNewTemporaryDeclaration){let t=e.ResolveVariableWithName(this.variableName,this);t.found||(this.variableName in this.story.constants?this.Error(`Can't re-assign to a constant (do you need to use VAR when declaring '${this.variableName}'?)`,this):this.Error(`Variable could not be found to assign to: '${this.variableName}'`,this)),this._runtimeAssignment&&(this._runtimeAssignment.isGlobal=t.isGlobal);}}};Ja.VariableAssignment=Lh;});var Sn=C(Qa=>{Object.defineProperty(Qa,"__esModule",{value:true});Qa.Weave=void 0;var r0=Is(),nt=sr(),Za=ma(),cP=Ca(),hP=ce(),Xa=lr(),dP=Et(),fP=ur(),pP=bt(),wt=Ci(),mP=Qg(),gP=se(),Wh=Ih(),yP=Jt(),CP=$h(),vP=Bh(),rt=J(),Mh=class n extends gP.ParsedObject{get rootContainer(){return this._rootContainer||(this._rootContainer=this.GenerateRuntimeObject()),this._rootContainer}get namedWeavePoints(){return this._namedWeavePoints}get lastParsedSignificantObject(){if(this.content.length===0)return null;let e=null;for(let r=this.content.length-1;r>=0;--r){e=this.content[r];let i=(0, rt.asOrNull)(e,yP.Text);if(!(i&&i.text===`
22
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, rt.asOrNull)(e,n);return t&&(e=t.lastParsedSignificantObject),e}constructor(e,t=-1){super(),this.previousWeavePoint=null,this.addContentToPreviousWeavePoint=false,this.hasSeenChoiceInSection=false,this.currentContainer=null,this._unnamedGatherCount=0,this._choiceCount=0,this._rootContainer=null,this._namedWeavePoints=new Map,this.looseEnds=[],this.gatherPointsToResolve=[],this.ResolveWeavePointNaming=()=>{var r,i,a;let s=[...this.FindAll(wt.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(nt.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let u=this.namedWeavePoints.get(((r=o.identifier)===null||r===void 0?void 0:r.name)||"");if(u){let l=u instanceof wt.Gather?"gather":"choice",c=u;this.Error(`A ${l} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((i=o.identifier)===null||i===void 0)&&i.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let r=0;for(;r<this.content.length;){let i=this.content[r];if(i instanceof nt.Choice||i instanceof wt.Gather){let s=i.indentationDepth-1;if(s>this.baseIndentIndex){let o=r;for(;r<this.content.length;){let h=(0, rt.asOrNull)(this.content[r],nt.Choice)||(0, rt.asOrNull)(this.content[r],wt.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;r+=1;}let u=r-o,l=this.content.slice(o,o+u);this.content.splice(o,u);let c=new n(l,s);this.InsertContent(o,c),r=o;}}r+=1;}},this.DetermineBaseIndentationFromContent=r=>{for(let i of r)if(i instanceof nt.Choice||i instanceof wt.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new hP.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof nt.Choice||r instanceof wt.Gather)this.AddRuntimeForWeavePoint(r);else if(r instanceof n){let i=r;this.AddRuntimeForNestedWeave(i),this.gatherPointsToResolve.splice(0,0,...i.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(r.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=r=>{let i=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=r.runtimeContainer;if(r.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),i){if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(a);}else this.rootContainer.AddToNamedContentOnly(a);for(let s of this.looseEnds){let o=s;if(o instanceof wt.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof Xa.Divert)u=o.runtimeObject;else {u=new dP.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new mP.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof wt.Gather)this.AddRuntimeForGather(r);else if(r instanceof nt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof wt.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let i=r;if(this.currentContainer.AddContent(i.runtimeObject),!i.innerContentContainer)throw new Error;i.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(i.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(r)&&(this.looseEnds.push(r),(0, rt.asOrNull)(r,nt.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=r;},this.AddRuntimeForNestedWeave=r=>{this.AddGeneralRuntimeContent(r.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=r=>{if(r!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(r);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(r);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let r=null,i=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, rt.asOrNull)(s,n);o&&(!a&&r===null&&(r=o),a&&i===null&&(i=o)),(s instanceof Wh.Sequence||s instanceof Za.Conditional)&&(a=true);}if(!(r===null&&i===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],u=false;if(a){if(o instanceof nt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof nt.Choice)){let l=r||i;l!==null&&(l.ReceiveLooseEnd(o),u=true);}}else r?.hasOwnProperty("ReceiveLooseEnd")&&r.ReceiveLooseEnd(o),u=true;u&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=r=>{this.looseEnds.push(r);},this.WeavePointNamed=r=>{if(!this.namedWeavePoints)return null;let i=this.namedWeavePoints.get(r);return i||null},this.IsGlobalDeclaration=r=>{let i=(0, rt.asOrNull)(r,vP.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, rt.asOrNull)(r,cP.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=r=>{let i=[],a=r;if(a.content!==null)for(let u of a.content)this.IsGlobalDeclaration(u)||i.push(u);let s=(0, rt.asOrNull)(a.parent,n);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let u=o+1;u<s.content.length;u+=1){let l=s.content[u];if(!this.IsGlobalDeclaration(l)){if(l instanceof nt.Choice||l instanceof wt.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof r0.AuthorWarning)return;if(this.looseEnds!==null&&this.looseEnds.length>0)for(let a of this.looseEnds){let s=this.ContentThatFollowsWeavePoint(a);this.ValidateFlowOfObjectsTerminates(s,a,r);}else {for(let a of this.content)if(a instanceof nt.Choice||a instanceof Xa.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,r);}},this.BadNestedTerminationHandler=r=>{let i=null;for(let s=r.parent;s!==null;s=s.parent)if(s instanceof Wh.Sequence||s instanceof Za.Conditional){i=(0, rt.asOrNull)(s,Za.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(nt.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,r);},this.ValidateFlowOfObjectsTerminates=(r,i,a)=>{let s=false,o=i;for(let u of r){if(u.Find(Xa.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof fP.DivertTarget))!==null&&(s=true),u.Find(CP.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof r0.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=r=>{if(r.content===null)return true;for(let i=r.content.length-1;i>=0;--i){let a=(0, rt.asOrNull)(r.content[i],Xa.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let r=[];for(let i of this.ancestry){let a=(0, rt.asOrNull)(i,pP.FlowBase);if(a)r.push(a);else break}for(let[i,a]of this.namedWeavePoints)for(let s of r){let o=s.ContentWithNameAtLevel(i);if(o&&o!==a){let u=`${a.GetType()} '${i}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(u,a);}}},t==-1?this.baseIndentIndex=this.DetermineBaseIndentationFromContent(e):this.baseIndentIndex=t,this.AddContent(e),this.ConstructWeaveHierarchyFromIndentation();}get typeName(){return "Weave"}ResolveReferences(e){if(super.ResolveReferences(e),this.looseEnds!==null&&this.looseEnds.length>0){let t=false;for(let r=this.parent;r!==null;r=r.parent)if(r instanceof Wh.Sequence||r instanceof Za.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};Qa.Weave=Mh;});var Dh=C(eo=>{Object.defineProperty(eo,"__esModule",{value:true});eo.ConditionalSingleBranch=void 0;var i0=ce(),Ya=Pe(),s0=Et(),_P=se(),EP=_t(),bP=ae(),SP=Jt(),DP=Sn(),wP=J(),Gh=class extends _P.ParsedObject{get ownExpression(){return this._ownExpression}set ownExpression(e){this._ownExpression=e,this._ownExpression&&this.AddContent(this._ownExpression);}constructor(e){super(),this._contentContainer=null,this._conditionalDivert=null,this._ownExpression=null,this._innerWeave=null,this.isTrueBranch=false,this.matchingEquality=false,this.isElse=false,this.isInline=false,this.returnDivert=null,this.GenerateRuntimeObject=()=>{if(this._innerWeave)for(let i of this._innerWeave.content){let a=(0, wP.asOrNull)(i,SP.Text);a&&a.text.startsWith("else:")&&this.Warning("Saw the text 'else:' which is being treated as content. Did you mean '- else:'?",a);}let t=new i0.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(Ya.ControlCommand.Duplicate()),this._conditionalDivert=new s0.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(Ya.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(EP.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(Ya.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new bP.StringValue(`
23
+ `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Ya.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new s0.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new i0.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new DP.Weave(e),this.AddContent(this._innerWeave));}get typeName(){return "ConditionalSingleBranch"}ResolveReferences(e){if(!this._conditionalDivert||!this._contentContainer)throw new Error;this._conditionalDivert.targetPath=this._contentContainer.path,super.ResolveReferences(e);}};eo.ConditionalSingleBranch=Gh;});var o0=C(to=>{Object.defineProperty(to,"__esModule",{value:true});to.CustomFlags=void 0;var a0;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(a0||(to.CustomFlags=a0={}));});var u0=C(no=>{Object.defineProperty(no,"__esModule",{value:true});no.DebugMetadata=void 0;var Uh=class n{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new n;return t.fileName=this.fileName,t.sourceName=this.sourceName,this.startLineNumber<e.startLineNumber?(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=this.startCharacterNumber):this.startLineNumber>e.startLineNumber?(t.startLineNumber=e.startLineNumber,t.startCharacterNumber=e.startCharacterNumber):(t.startLineNumber=this.startLineNumber,t.startCharacterNumber=Math.min(this.startCharacterNumber,e.startCharacterNumber)),this.endLineNumber>e.endLineNumber?(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=this.endCharacterNumber):this.endLineNumber<e.endLineNumber?(t.endLineNumber=e.endLineNumber,t.endCharacterNumber=e.endCharacterNumber):(t.endLineNumber=this.endLineNumber,t.endCharacterNumber=Math.max(this.endCharacterNumber,e.endCharacterNumber)),t}toString(){return this.fileName!==null?`line ${this.startLineNumber} of ${this.fileName}"`:"line "+this.startLineNumber}};no.DebugMetadata=Uh;});var l0=C(ro=>{Object.defineProperty(ro,"__esModule",{value:true});ro.ExternalDeclaration=void 0;var AP=se(),Hh=class extends AP.ParsedObject{get name(){var e;return ((e=this.identifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t){super(),this.identifier=e,this.argumentNames=t,this.GenerateRuntimeObject=()=>(this.story.AddExternal(this),null);}get typeName(){return "EXTERNAL"}toString(){var e;return `EXTERNAL ${(e=this.identifier)===null||e===void 0?void 0:e.name}`}};ro.ExternalDeclaration=Hh;});var c0=C(io=>{Object.defineProperty(io,"__esModule",{value:true});io.FlowDecl=void 0;var Kh=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};io.FlowDecl=Kh;});var Jh=C(so=>{Object.defineProperty(so,"__esModule",{value:true});so.Wrap=void 0;var PP=se(),zh=class extends PP.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};so.Wrap=zh;});var h0=C(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.Glue=void 0;var FP=Jh(),Zh=class extends FP.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};ao.Glue=Zh;});var uo=C(oo=>{Object.defineProperty(oo,"__esModule",{value:true});oo.Glue=void 0;var OP=We(),Xh=class extends OP.InkObject{toString(){return "Glue"}};oo.Glue=Xh;});var f0=C(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.IncDecExpression=void 0;var xP=Oa(),d0=et(),NP=bt(),TP=_t(),IP=ae(),kP=Kt(),$P=cr(),RP=Sn(),Qh=class extends d0.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new $P.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new IP.IntValue(1)),i.AddContent(TP.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new kP.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),i.AddContent(this._runtimeAssignment);},this.toString=()=>{var i,a;return this.expression?`${(i=this.varIdentifier)===null||i===void 0?void 0:i.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof d0.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!r):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let r=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(r.found||this.Error(`variable for ${this.incrementDecrementWord} could not be found: '${this.varIdentifier}' after searching: {this.descriptionOfScope}`),!this._runtimeAssignment)throw new Error;this._runtimeAssignment.isGlobal=r.isGlobal,!(this.parent instanceof RP.Weave)&&!(this.parent instanceof NP.FlowBase)&&!(this.parent instanceof xP.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};lo.IncDecExpression=Qh;});var ed=C(co=>{Object.defineProperty(co,"__esModule",{value:true});co.IncludedFile=void 0;var VP=se(),Yh=class extends VP.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};co.IncludedFile=Yh;});var p0=C(ho=>{Object.defineProperty(ho,"__esModule",{value:true});ho.InfixOperator=void 0;var td=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};ho.InfixOperator=td;});var rd=C(fo=>{Object.defineProperty(fo,"__esModule",{value:true});fo.Knot=void 0;var qP=bt(),m0=ar(),nd=class extends qP.FlowBase{get flowLevel(){return m0.FlowLevel.Knot}constructor(e,t,r,i){super(e,t,r,i);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let r in this.subFlowsByName){let i=t.ContentWithNameAtLevel(r,m0.FlowLevel.Knot,false);if(i){let a=this.subFlowsByName.get(r),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${i.debugMetadata})`;this.Error(s,a);}}}};fo.Knot=nd;});var g0=C(po=>{Object.defineProperty(po,"__esModule",{value:true});po.List=void 0;var jP=et(),LP=Ge(),BP=Ge(),WP=ae(),id=class extends jP.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new LP.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((r=s?.name)===null||r===void 0?void 0:r.split("."))||[],u=null,l="";o.length>1?(u=o[0],l=o[1]):l=o[0];let c=this.story.ResolveListItem(u,l,this);if(c===null)u===null?this.Error(`Could not find list definition that contains item '${s}'`):this.Error(`Could not find list item ${s}`);else {if(c.parent==null){this.Error(`Could not find list definition for item ${s}`);return}u||(u=((i=c.parent.identifier)===null||i===void 0?void 0:i.name)||null);let h=new BP.InkListItem(u,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new WP.ListValue(a));};}get typeName(){return "List"}};po.List=id;});var ad=C(mo=>{Object.defineProperty(mo,"__esModule",{value:true});mo.ListElementDefinition=void 0;var MP=se(),GP=It(),sd=class extends MP.ParsedObject{get fullName(){var e;let t=this.parent;if(t===null)throw new Error("Can't get full name without a parent list.");return `${(e=t.identifier)===null||e===void 0?void 0:e.name}.${this.name}`}get typeName(){return "ListElement"}get name(){var e;return ((e=this.indentifier)===null||e===void 0?void 0:e.name)||null}constructor(e,t,r=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=r,this.seriesValue=0,this.parent=null,this.GenerateRuntimeObject=()=>{throw new Error("Not implemented.")},this.toString=()=>this.fullName,this.parent=this.parent;}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.indentifier,GP.SymbolType.ListItem);}};mo.ListElementDefinition=sd;});var od=C(go=>{Object.defineProperty(go,"__esModule",{value:true});go.StatementLevel=void 0;var y0;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(y0||(go.StatementLevel=y0={}));});var ld=C(yo=>{Object.defineProperty(yo,"__esModule",{value:true});yo.Stitch=void 0;var UP=bt(),HP=ar(),ud=class extends UP.FlowBase{get flowLevel(){return HP.FlowLevel.Stitch}constructor(e,t,r,i){super(e,t,r,i),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};yo.Stitch=ud;});var vo=C(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.Tag=void 0;var KP=We(),cd=class extends KP.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Co.Tag=cd;});var dd=C(_o=>{Object.defineProperty(_o,"__esModule",{value:true});_o.Choice=void 0;var zP=Be(),JP=Ae(),ZP=We(),hd=class n extends ZP.InkObject{constructor(){super(...arguments),this.text="",this.index=0,this.threadAtGeneration=null,this.sourcePath="",this.targetPath=null,this.isInvisibleDefault=false,this.tags=null,this.originalThreadIndex=0;}get pathStringOnChoice(){return this.targetPath===null?(0, JP.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new zP.Path(e);}Clone(){let e=new n;return e.text=this.text,e.sourcePath=this.sourcePath,e.index=this.index,e.targetPath=this.targetPath,e.originalThreadIndex=this.originalThreadIndex,e.isInvisibleDefault=this.isInvisibleDefault,this.threadAtGeneration!==null&&(e.threadAtGeneration=this.threadAtGeneration.Copy()),e}};_o.Choice=hd;});var pd=C(Eo=>{Object.defineProperty(Eo,"__esModule",{value:true});Eo.ListDefinitionsOrigin=void 0;var XP=Ge(),QP=ae(),YP=Ae(),fd=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[r,i]of t.items){let a=XP.InkListItem.fromSerializedKey(r),s=new QP.ListValue(a,i);if(!a.itemName)throw new Error("item.itemName is null or undefined.");this._allUnambiguousListValueCache.set(a.itemName,s),this._allUnambiguousListValueCache.set(a.fullName,s);}}}get lists(){let e=[];for(let[,t]of this._lists)e.push(t);return e}TryListGetDefinition(e,t){if(e===null)return {result:t,exists:false};let r=this._lists.get(e);return r?{result:r,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, YP.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Eo.ListDefinitionsOrigin=fd;});var fr=C(wo=>{Object.defineProperty(wo,"__esModule",{value:true});wo.JsonSerialisation=void 0;var bo=ce(),He=ae(),C0=uo(),H=Pe(),dr=_n(),v0=Et(),_0=ta(),md=cr(),E0=Kt(),gd=_t(),b0=vn(),S0=vo(),e1=Be(),D0=dd(),t1=qh(),n1=pd(),So=Ge(),he=J(),Dn=Ae(),Do=class n{static JArrayToRuntimeObjList(e,t=false){let r=e.length;t&&r--;let i=[];for(let a=0;a<r;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, Dn.throwNullException)("runtimeObj");i.push(o);}return i}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WritePropertyStart(r),this.WriteRuntimeObject(e,i),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let r of t)this.WriteRuntimeObject(e,r);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[r,i]of t)e.WriteIntProperty(r,i);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let r=(0, he.asOrNull)(t,bo.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, he.asOrNull)(t,v0.Divert);if(i){let y="->";i.isExternal?y="x()":i.pushesToStack&&(i.stackPushType==dr.PushPopType.Function?y="f()":i.stackPushType==dr.PushPopType.Tunnel&&(y="->t->"));let D;i.hasVariableTarget?D=i.variableDivertName:D=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(y,D),i.hasVariableTarget&&e.WriteProperty("var",true),i.isConditional&&e.WriteProperty("c",true),i.externalArgs>0&&e.WriteIntProperty("exArgs",i.externalArgs),e.WriteObjectEnd();return}let a=(0, he.asOrNull)(t,_0.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, he.asOrNull)(t,He.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, he.asOrNull)(t,He.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, he.asOrNull)(t,He.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, he.asOrNull)(t,He.StringValue);if(l){l.isNewline?e.Write(`
24
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, he.asOrNull)(t,He.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, he.asOrNull)(t,He.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, Dn.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let f=(0, he.asOrNull)(t,He.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, he.asOrNull)(t,C0.Glue)){e.Write("<>");return}let g=(0, he.asOrNull)(t,H.ControlCommand);if(g){e.Write(n._controlCommandNames[g.commandType]);return}let p=(0, he.asOrNull)(t,gd.NativeFunctionCall);if(p){let y=p.name;y=="^"&&(y="L^"),e.Write(y);return}let v=(0, he.asOrNull)(t,md.VariableReference);if(v){e.WriteObjectStart();let y=v.pathStringForCount;y!=null?e.WriteProperty("CNT?",y):e.WriteProperty("VAR?",v.name),e.WriteObjectEnd();return}let _=(0, he.asOrNull)(t,E0.VariableAssignment);if(_){e.WriteObjectStart();let y=_.isGlobal?"VAR=":"temp=";e.WriteProperty(y,_.variableName),_.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, he.asOrNull)(t,b0.Void)){e.Write("void");return}let d=(0, he.asOrNull)(t,S0.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let E=(0, he.asOrNull)(t,D0.Choice);if(E){this.WriteChoice(e,E);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let r in e)if(e.hasOwnProperty(r)){let i=this.JTokenToRuntimeObject(e[r]);if(i===null)return (0, Dn.throwNullException)("inkObject");t.set(r,i);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let r in e)e.hasOwnProperty(r)&&t.set(r,parseInt(e[r]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return He.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new He.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new He.StringValue(t.substring(1));if(i==`
25
25
  `&&t.length==1)return new He.StringValue(`
26
- `);if(t=="<>")return new y0.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new K.ControlCommand(a)}if(t=="L^"&&(t="^"),pd.NativeFunctionCall.CallExistsWithName(t))return pd.NativeFunctionCall.CallWithName(t);if(t=="->->")return K.ControlCommand.PopTunnel();if(t=="~ret")return K.ControlCommand.PopFunction();if(t=="void")return new E0.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new He.DivertTargetValue(new QP.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new He.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=fr.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=fr.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=fr.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=fr.PushPopType.Function),i){let c=new C0.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=r.toString();return (r=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(r=t.exArgs)&&(c.externalArgs=parseInt(r)),c}if(r=t["*"]){let c=new v0.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new fd.VariableReference(r.toString());if(r=t["CNT?"]){let c=new fd.VariableReference;return c.pathStringForCount=r.toString(),c}let u=false,l=false;if((r=t["VAR="])?(u=true,l=true):(r=t["temp="])&&(u=true,l=false),u){let c=r.toString(),h=!t.re,d=new _0.VariableAssignment(c,h);return d.isGlobal=l,d}if(t["#"]!==void 0)return r=t["#"],new b0.Tag(r.toString());if(r=t.list){let c=r,h=new So.InkList;if(r=t.origins){let d=r;h.SetInitialOriginNames(d);}for(let d in c)if(c.hasOwnProperty(d)){let p=c[d],m=new So.InkListItem(d),f=parseInt(p);h.Add(m,f);}return new He.ListValue(h)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,r){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,r)}static WriteRuntimeContainer(e,t,r=false){if(e.WriteArrayStart(),t===null)return (0, wn.throwNullException)("container");for(let u of t.content)this.WriteRuntimeObject(e,u);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!r,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[u,l]of i){let c=u,h=(0, he.asOrNull)(l,bo.Container);e.WritePropertyStart(c),this.WriteRuntimeContainer(e,h,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new bo.Container;t.content=this.JArrayToRuntimeObjList(e,true);let r=e[e.length-1];if(r!=null){let i=new Map;for(let a in r)if(a=="#f")t.countFlags=parseInt(r[a]);else if(a=="#n")t.name=r[a].toString();else {let s=this.JTokenToRuntimeObject(r[a]),o=(0, he.asOrNull)(s,bo.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new S0.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let r of t.tags)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let r=t.value;if(r===null)return (0, wn.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=So.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, wn.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),r.Count==0&&r.originNames!=null&&r.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of r.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let r of e.lists){let i={};for(let[a,s]of r.items){let o=So.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, wn.throwNullException)("item.itemName");i[o.itemName]=s;}t[r.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,r=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let l in s)if(t.hasOwnProperty(i)){let c=s[l];o.set(l,parseInt(c));}let u=new YP.ListDefinition(a,o);r.push(u);}return new e1.ListDefinitionsOrigin(r)}};wo.JsonSerialisation=Do;Do._controlCommandNames=(()=>{let n=[];n[K.ControlCommand.CommandType.EvalStart]="ev",n[K.ControlCommand.CommandType.EvalOutput]="out",n[K.ControlCommand.CommandType.EvalEnd]="/ev",n[K.ControlCommand.CommandType.Duplicate]="du",n[K.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[K.ControlCommand.CommandType.PopFunction]="~ret",n[K.ControlCommand.CommandType.PopTunnel]="->->",n[K.ControlCommand.CommandType.BeginString]="str",n[K.ControlCommand.CommandType.EndString]="/str",n[K.ControlCommand.CommandType.NoOp]="nop",n[K.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[K.ControlCommand.CommandType.Turns]="turn",n[K.ControlCommand.CommandType.TurnsSince]="turns",n[K.ControlCommand.CommandType.ReadCount]="readc",n[K.ControlCommand.CommandType.Random]="rnd",n[K.ControlCommand.CommandType.SeedRandom]="srnd",n[K.ControlCommand.CommandType.VisitIndex]="visit",n[K.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[K.ControlCommand.CommandType.StartThread]="thread",n[K.ControlCommand.CommandType.Done]="done",n[K.ControlCommand.CommandType.End]="end",n[K.ControlCommand.CommandType.ListFromInt]="listInt",n[K.ControlCommand.CommandType.ListRange]="range",n[K.ControlCommand.CommandType.ListRandom]="lrnd",n[K.ControlCommand.CommandType.BeginTag]="#",n[K.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<K.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var yd=y(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.CallStack=void 0;var md=En(),D0=Be(),t1=Fi(),w0=pr(),n1=ae(),r1=Cn(),wi=gi(),i1=ri(),A0=nr(),gd=Ae(),Ai=class n{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){i1.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=wi.Pointer.Null,arguments[0]instanceof t1.Story){let e=arguments[0];this._startOfRoot=wi.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new n.Thread),this._threads[0].callstack.push(new n.Element(md.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let r=e.threads;for(let i of r){let a=i,s=new n.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=wi.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let r of this._threads)r.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==md.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,r=0){let i=new n.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=r,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let r=this.callStack[t-1],i=(0, A0.tryGetValueFromMap)(r.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,r,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!r&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, A0.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&n1.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(r=>{if(r.threadIndex==e)return r});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new r1.StringBuilder;for(let t=0;t<this._threads.length;t++){let r=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
27
- `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<r.callstack.length;a++){r.callstack[a].type==md.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=r.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, gd.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Pi.CallStack=Ai;(function(n){class e{constructor(i,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}n.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=wi.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let s=i.callstack;for(let u of s){let l=u,c=parseInt(l.type),h=wi.Pointer.Null,d,p=l.cPath;if(typeof p<"u"){d=p.toString();let _=a.ContentAtPath(new D0.Path(d));if(h.container=_.container,h.index=parseInt(l.idx),_.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+d+". Has the story changed since this save data was created?");_.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+d+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let m=!!l.exp,f=new e(c,h,m),v=l.temp;typeof v<"u"?f.temporaryVariables=w0.JsonSerialisation.JObjectToDictionaryRuntimeObjs(v):f.temporaryVariables.clear(),this.callstack.push(f);}let o=i.previousContentObject;if(typeof o<"u"){let u=new D0.Path(o.toString());this.previousPointer=a.PointerAtPath(u);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, gd.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),w0.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, gd.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(Ai||(Pi.CallStack=Ai={}));});var F0=y(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.VariablesState=void 0;var _e=ae(),s1=si(),P0=pr(),Fe=Z(),Oi=nr(),Xt=Ae();function a1(){return class{}}var Ao=class n extends a1(){variableChangedEvent(e,t){for(let r of this.variableChangedEventCallbacks)r(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let r=this._globalVariables.get(t);this.variableChangedEvent(t,r);}if(this.patch!=null)for(let t of this.patch.changedVariables){let r=this.patch.TryGetGlobal(t,null);r.exists&&e.set(t,r);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,r]of e)this.variableChangedEvent(t,r);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let r=null;return this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)?r.result.valueObject:(r=this._globalVariables.get(e),typeof r>"u"&&(r=this._defaultGlobalVariables.get(e)),typeof r<"u"?r.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new s1.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let r=_e.Value.Create(t);if(r==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,r);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,s){return a in i?i[a]=s:i.$(a,s),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Xt.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,r]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=P0.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Xt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,r);}}WriteJson(e){e.WriteObjectStart();for(let[t,r]of this._globalVariables){let i=t,a=r;if(n.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),P0.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Xt.throwNullException)("obj1");if(t===null)return (0, Xt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, Fe.asOrNull)(e,_e.BoolValue);if(r!==null)return r.value===(0, Fe.asOrThrows)(t,_e.BoolValue).value;let i=(0, Fe.asOrNull)(e,_e.IntValue);if(i!==null)return i.value===(0, Fe.asOrThrows)(t,_e.IntValue).value;let a=(0, Fe.asOrNull)(e,_e.FloatValue);if(a!==null)return a.value===(0, Fe.asOrThrows)(t,_e.FloatValue).value;let s=(0, Fe.asOrNull)(e,_e.Value),o=(0, Fe.asOrNull)(t,_e.Value);if(s!==null&&o!==null)return (0, Fe.isEquatable)(s.valueObject)&&(0, Fe.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let r=this.GetRawVariableWithName(e,t),i=(0, Fe.asOrNull)(r,_e.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, Oi.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let r=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Oi.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Xt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return r=this._callStack.GetTemporaryVariableWithName(e,t),r}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let r=e.variableName;if(r===null)return (0, Xt.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, Fe.asOrNull)(t,_e.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Fe.asOrNull)(this.GetRawVariableWithName(r,i),_e.VariablePointerValue),s!=null&&(r=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(r,t):this._callStack.SetTemporaryVariable(r,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let r=(0, Fe.asOrThrows)(e,_e.ListValue),i=(0, Fe.asOrThrows)(t,_e.ListValue);r.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}SetGlobal(e,t){let r=null;if(this.patch===null&&(r=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null))),_e.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, Xt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&r!==null&&t!==r.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Xt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let r=this.GetRawVariableWithName(e.variableName,t),i=(0, Fe.asOrNull)(r,_e.VariablePointerValue);return i??new _e.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Po.VariablesState=Ao;Ao.dontSaveDefaultValues=true;});var vd=y(Fo=>{Object.defineProperty(Fo,"__esModule",{value:true});Fo.PRNG=void 0;var Cd=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Fo.PRNG=Cd;});var O0=y(Oo=>{Object.defineProperty(Oo,"__esModule",{value:true});Oo.StatePatch=void 0;var _d=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};Oo.StatePatch=_d;});var Ed=y(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.SimpleJson=void 0;var xi=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};Ni.SimpleJson=xi;(function(n){class e{constructor(i){if(JSON.parse("0",(s,o,u)=>u!=null)){let s=(o,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,s);}else {let s=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===n.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}n.Writer=t,(function(r){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(r.State||(r.State={}));class a{constructor(o){this.type=n.Writer.State.None,this.childCount=0,this.type=o;}}r.StateElement=a;})(t=n.Writer||(n.Writer={}));})(xi||(Ni.SimpleJson=xi={}));});var N0=y(No=>{Object.defineProperty(No,"__esModule",{value:true});No.Flow=void 0;var x0=yd(),xo=pr(),o1=Ae(),bd=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new x0.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=xo.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=xo.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let i=r.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),e.WriteProperty("outputStream",r=>xo.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, o1.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let i of this.currentChoices)xo.JsonSerialisation.WriteChoice(r,i);r.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let r of this.currentChoices){let i=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(i!==null)r.threadAtGeneration=i.Copy();else {let a=e[`${r.originalThreadIndex}`];r.threadAtGeneration=new x0.CallStack.Thread(a,t);}}}};No.Flow=bd;});var k0=y(Io=>{Object.defineProperty(Io,"__esModule",{value:true});Io.StoryState=void 0;var u1=yd(),l1=F0(),me=ae(),Qt=En(),c1=vo(),Sd=uo(),T0=Be(),ke=Pe(),Dd=Cn(),Yt=pr(),h1=vd(),d1=_n(),mr=gi(),Ti=nr(),de=Z(),f1=ri(),it=Ae(),p1=Fi(),m1=O0(),I0=Ed(),To=N0(),g1=Ge(),wd=class n{ToJson(e=false){let t=new I0.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=I0.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let r=this.story.ContentAtPath(new T0.Path(e)).container;if(r===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(r,0),t.exists)return t.result}return t=(0, Ti.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, it.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);return r.exists?r.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);r.exists?this._visitCounts.set(t,r.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._turnIndices,t,0);return r.exists?this.currentTurnIndex-r.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, it.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, it.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new Dd.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, de.asOrNull)(r,me.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, de.asOrNull)(r,ke.ControlCommand);a!==null&&(a.commandType==ke.ControlCommand.CommandType.BeginTag?t=true:a.commandType==ke.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new Dd.StringBuilder,r=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&r==-1&&(r=a),o||(s!=`
26
+ `);if(t=="<>")return new C0.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new H.ControlCommand(a)}if(t=="L^"&&(t="^"),gd.NativeFunctionCall.CallExistsWithName(t))return gd.NativeFunctionCall.CallWithName(t);if(t=="->->")return H.ControlCommand.PopTunnel();if(t=="~ret")return H.ControlCommand.PopFunction();if(t=="void")return new b0.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new He.DivertTargetValue(new e1.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new He.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=dr.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=dr.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=dr.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=dr.PushPopType.Function),i){let c=new v0.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=r.toString();return (r=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(r=t.exArgs)&&(c.externalArgs=parseInt(r)),c}if(r=t["*"]){let c=new _0.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new md.VariableReference(r.toString());if(r=t["CNT?"]){let c=new md.VariableReference;return c.pathStringForCount=r.toString(),c}let u=false,l=false;if((r=t["VAR="])?(u=true,l=true):(r=t["temp="])&&(u=true,l=false),u){let c=r.toString(),h=!t.re,f=new E0.VariableAssignment(c,h);return f.isGlobal=l,f}if(t["#"]!==void 0)return r=t["#"],new S0.Tag(r.toString());if(r=t.list){let c=r,h=new So.InkList;if(r=t.origins){let f=r;h.SetInitialOriginNames(f);}for(let f in c)if(c.hasOwnProperty(f)){let m=c[f],g=new So.InkListItem(f),p=parseInt(m);h.Add(g,p);}return new He.ListValue(h)}if(t.originalChoicePath!=null)return this.JObjectToChoice(t)}if(Array.isArray(e))return this.JArrayToContainer(e);if(e==null)return null;throw new Error("Failed to convert token to runtime object: "+this.toJson(e,["parent"]))}static toJson(e,t,r){return JSON.stringify(e,(i,a)=>t?.some(s=>s===i)?void 0:a,r)}static WriteRuntimeContainer(e,t,r=false){if(e.WriteArrayStart(),t===null)return (0, Dn.throwNullException)("container");for(let u of t.content)this.WriteRuntimeObject(e,u);let i=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!r,o=i!=null||a>0||s;if(o&&e.WriteObjectStart(),i!=null)for(let[u,l]of i){let c=u,h=(0, he.asOrNull)(l,bo.Container);e.WritePropertyStart(c),this.WriteRuntimeContainer(e,h,true),e.WritePropertyEnd();}a>0&&e.WriteIntProperty("#f",a),s&&e.WriteProperty("#n",t.name),o?e.WriteObjectEnd():e.WriteNull(),e.WriteArrayEnd();}static JArrayToContainer(e){let t=new bo.Container;t.content=this.JArrayToRuntimeObjList(e,true);let r=e[e.length-1];if(r!=null){let i=new Map;for(let a in r)if(a=="#f")t.countFlags=parseInt(r[a]);else if(a=="#n")t.name=r[a].toString();else {let s=this.JTokenToRuntimeObject(r[a]),o=(0, he.asOrNull)(s,bo.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new D0.Choice;return t.text=e.text.toString(),t.index=parseInt(e.index),t.sourcePath=e.originalChoicePath.toString(),t.originalThreadIndex=parseInt(e.originalThreadIndex),t.pathStringOnChoice=e.targetPath.toString(),t.tags=this.JArrayToTags(e),t.isInvisibleDefault=!!e.isInvisibleDefault,t}static JArrayToTags(e){return e.tags?e.tags:null}static WriteChoice(e,t){e.WriteObjectStart(),e.WriteProperty("text",t.text),e.WriteIntProperty("index",t.index),e.WriteProperty("originalChoicePath",t.sourcePath),e.WriteIntProperty("originalThreadIndex",t.originalThreadIndex),e.WriteProperty("targetPath",t.pathStringOnChoice),e.WriteProperty("isInvisibleDefault",t.isInvisibleDefault),this.WriteChoiceTags(e,t),e.WriteObjectEnd();}static WriteChoiceTags(e,t){if(t.tags&&t.tags.length>0){e.WritePropertyStart("tags"),e.WriteArrayStart();for(let r of t.tags)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let r=t.value;if(r===null)return (0, Dn.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=So.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Dn.throwNullException)("item.itemName");e.WritePropertyNameStart(),e.WritePropertyNameInner(s.originName?s.originName:"?"),e.WritePropertyNameInner("."),e.WritePropertyNameInner(s.itemName),e.WritePropertyNameEnd(),e.Write(o),e.WritePropertyEnd();}if(e.WriteObjectEnd(),e.WritePropertyEnd(),r.Count==0&&r.originNames!=null&&r.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let i of r.originNames)e.Write(i);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let r of e.lists){let i={};for(let[a,s]of r.items){let o=So.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Dn.throwNullException)("item.itemName");i[o.itemName]=s;}t[r.name]=i;}return t}static JTokenToListDefinitions(e){let t=e,r=[];for(let i in t)if(t.hasOwnProperty(i)){let a=i.toString(),s=t[i],o=new Map;for(let l in s)if(t.hasOwnProperty(i)){let c=s[l];o.set(l,parseInt(c));}let u=new t1.ListDefinition(a,o);r.push(u);}return new n1.ListDefinitionsOrigin(r)}};wo.JsonSerialisation=Do;Do._controlCommandNames=(()=>{let n=[];n[H.ControlCommand.CommandType.EvalStart]="ev",n[H.ControlCommand.CommandType.EvalOutput]="out",n[H.ControlCommand.CommandType.EvalEnd]="/ev",n[H.ControlCommand.CommandType.Duplicate]="du",n[H.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[H.ControlCommand.CommandType.PopFunction]="~ret",n[H.ControlCommand.CommandType.PopTunnel]="->->",n[H.ControlCommand.CommandType.BeginString]="str",n[H.ControlCommand.CommandType.EndString]="/str",n[H.ControlCommand.CommandType.NoOp]="nop",n[H.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[H.ControlCommand.CommandType.Turns]="turn",n[H.ControlCommand.CommandType.TurnsSince]="turns",n[H.ControlCommand.CommandType.ReadCount]="readc",n[H.ControlCommand.CommandType.Random]="rnd",n[H.ControlCommand.CommandType.SeedRandom]="srnd",n[H.ControlCommand.CommandType.VisitIndex]="visit",n[H.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[H.ControlCommand.CommandType.StartThread]="thread",n[H.ControlCommand.CommandType.Done]="done",n[H.ControlCommand.CommandType.End]="end",n[H.ControlCommand.CommandType.ListFromInt]="listInt",n[H.ControlCommand.CommandType.ListRange]="range",n[H.ControlCommand.CommandType.ListRandom]="lrnd",n[H.ControlCommand.CommandType.BeginTag]="#",n[H.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<H.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var vd=C(Pi=>{Object.defineProperty(Pi,"__esModule",{value:true});Pi.CallStack=void 0;var yd=_n(),w0=Be(),r1=Fi(),A0=fr(),i1=ae(),s1=yn(),wi=gi(),a1=ri(),P0=tr(),Cd=Ae(),Ai=class n{get elements(){return this.callStack}get depth(){return this.elements.length}get currentElement(){let t=this._threads[this._threads.length-1].callstack;return t[t.length-1]}get currentElementIndex(){return this.callStack.length-1}get currentThread(){return this._threads[this._threads.length-1]}set currentThread(e){a1.Debug.Assert(this._threads.length==1,"Shouldn't be directly setting the current thread when we have a stack of them"),this._threads.length=0,this._threads.push(e);}get canPop(){return this.callStack.length>1}constructor(){if(this._threadCounter=0,this._startOfRoot=wi.Pointer.Null,arguments[0]instanceof r1.Story){let e=arguments[0];this._startOfRoot=wi.Pointer.StartOf(e.rootContentContainer),this.Reset();}else {let e=arguments[0];this._threads=[];for(let t of e._threads)this._threads.push(t.Copy());this._threadCounter=e._threadCounter,this._startOfRoot=e._startOfRoot.copy();}}Reset(){this._threads=[],this._threads.push(new n.Thread),this._threads[0].callstack.push(new n.Element(yd.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let r=e.threads;for(let i of r){let a=i,s=new n.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=wi.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let r of this._threads)r.WriteJson(t);t.WriteArrayEnd(),t.WritePropertyEnd(),t.WritePropertyStart("threadCounter"),t.WriteInt(this._threadCounter),t.WritePropertyEnd();});}PushThread(){let e=this.currentThread.Copy();this._threadCounter++,e.threadIndex=this._threadCounter,this._threads.push(e);}ForkThread(){let e=this.currentThread.Copy();return this._threadCounter++,e.threadIndex=this._threadCounter,e}PopThread(){if(this.canPopThread)this._threads.splice(this._threads.indexOf(this.currentThread),1);else throw new Error("Can't pop thread")}get canPopThread(){return this._threads.length>1&&!this.elementIsEvaluateFromGame}get elementIsEvaluateFromGame(){return this.currentElement.type==yd.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,r=0){let i=new n.Element(e,this.currentElement.currentPointer,false);i.evaluationStackHeightWhenPushed=t,i.functionStartInOutputStream=r,this.callStack.push(i);}CanPop(e=null){return this.canPop?e==null?true:this.currentElement.type==e:false}Pop(e=null){if(this.CanPop(e)){this.callStack.pop();return}else throw new Error("Mismatched push/pop in Callstack")}GetTemporaryVariableWithName(e,t=-1){t==-1&&(t=this.currentElementIndex+1);let r=this.callStack[t-1],i=(0, P0.tryGetValueFromMap)(r.temporaryVariables,e,null);return i.exists?i.result:null}SetTemporaryVariable(e,t,r,i=-1){i==-1&&(i=this.currentElementIndex+1);let a=this.callStack[i-1];if(!r&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, P0.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&i1.ListValue.RetainListOriginsForAssignment(s.result,t),a.temporaryVariables.set(e,t);}ContextForVariableNamed(e){return this.currentElement.temporaryVariables.get(e)?this.currentElementIndex+1:0}ThreadWithIndex(e){let t=this._threads.filter(r=>{if(r.threadIndex==e)return r});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new s1.StringBuilder;for(let t=0;t<this._threads.length;t++){let r=this._threads[t],i=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
27
+ `,t+1,this._threads.length,i?"(current) ":"");for(let a=0;a<r.callstack.length;a++){r.callstack[a].type==yd.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=r.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, Cd.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Pi.CallStack=Ai;(function(n){class e{constructor(i,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=i;}Copy(){let i=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return i.temporaryVariables=new Map(this.temporaryVariables),i.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,i.functionStartInOutputStream=this.functionStartInOutputStream,i}}n.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=wi.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let i=arguments[0],a=arguments[1];this.threadIndex=parseInt(i.threadIndex);let s=i.callstack;for(let u of s){let l=u,c=parseInt(l.type),h=wi.Pointer.Null,f,m=l.cPath;if(typeof m<"u"){f=m.toString();let _=a.ContentAtPath(new w0.Path(f));if(h.container=_.container,h.index=parseInt(l.idx),_.obj==null)throw new Error("When loading state, internal story location couldn't be found: "+f+". Has the story changed since this save data was created?");_.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!l.exp,p=new e(c,h,g),v=l.temp;typeof v<"u"?p.temporaryVariables=A0.JsonSerialisation.JObjectToDictionaryRuntimeObjs(v):p.temporaryVariables.clear(),this.callstack.push(p);}let o=i.previousContentObject;if(typeof o<"u"){let u=new w0.Path(o.toString());this.previousPointer=a.PointerAtPath(u);}}}Copy(){let i=new t;i.threadIndex=this.threadIndex;for(let a of this.callstack)i.callstack.push(a.Copy());return i.previousPointer=this.previousPointer.copy(),i}WriteJson(i){i.WriteObjectStart(),i.WritePropertyStart("callstack"),i.WriteArrayStart();for(let a of this.callstack){if(i.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, Cd.throwNullException)("el.currentPointer.container");i.WriteProperty("cPath",a.currentPointer.container.path.componentsString),i.WriteIntProperty("idx",a.currentPointer.index);}i.WriteProperty("exp",a.inExpressionEvaluation),i.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(i.WritePropertyStart("temp"),A0.JsonSerialisation.WriteDictionaryRuntimeObjs(i,a.temporaryVariables),i.WritePropertyEnd()),i.WriteObjectEnd();}if(i.WriteArrayEnd(),i.WritePropertyEnd(),i.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, Cd.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(Ai||(Pi.CallStack=Ai={}));});var O0=C(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.VariablesState=void 0;var _e=ae(),o1=si(),F0=fr(),Fe=J(),Oi=tr(),Zt=Ae();function u1(){return class{}}var Ao=class n extends u1(){variableChangedEvent(e,t){for(let r of this.variableChangedEventCallbacks)r(e,t);}StartVariableObservation(){this._batchObservingVariableChanges=true,this._changedVariablesForBatchObs=new Set;}CompleteVariableObservation(){this._batchObservingVariableChanges=false;let e=new Map;if(this._changedVariablesForBatchObs!=null)for(let t of this._changedVariablesForBatchObs){let r=this._globalVariables.get(t);this.variableChangedEvent(t,r);}if(this.patch!=null)for(let t of this.patch.changedVariables){let r=this.patch.TryGetGlobal(t,null);r.exists&&e.set(t,r);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,r]of e)this.variableChangedEvent(t,r);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let r=null;return this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)?r.result.valueObject:(r=this._globalVariables.get(e),typeof r>"u"&&(r=this._defaultGlobalVariables.get(e)),typeof r<"u"?r.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new o1.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let r=_e.Value.Create(t);if(r==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,r);}}constructor(e,t){super(),this.variableChangedEventCallbacks=[],this.patch=null,this._defaultGlobalVariables=new Map,this._changedVariablesForBatchObs=new Set,this._batchObservingVariableChanges=false,this._globalVariables=new Map,this._callStack=e,this._listDefsOrigin=t;try{return new Proxy(this,{get(i,a){return a in i?i[a]:i.$(a)},set(i,a,s){return a in i?i[a]=s:i.$(a,s),!0},ownKeys(i){return [...new Set([...i._defaultGlobalVariables.keys(),...i._globalVariables.keys()])]},getOwnPropertyDescriptor(i,a){return {enumerable:!0,configurable:!0,value:i.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Zt.throwNullException)("this.patch");for(let[e,t]of this.patch.globals)this._globalVariables.set(e,t);if(this._changedVariablesForBatchObs!==null)for(let e of this.patch.changedVariables)this._changedVariablesForBatchObs.add(e);this.patch=null;}SetJsonToken(e){this._globalVariables.clear();for(let[t,r]of this._defaultGlobalVariables){let i=e[t];if(typeof i<"u"){let a=F0.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Zt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,r);}}WriteJson(e){e.WriteObjectStart();for(let[t,r]of this._globalVariables){let i=t,a=r;if(n.dontSaveDefaultValues&&this._defaultGlobalVariables.has(i)){let s=this._defaultGlobalVariables.get(i);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(i),F0.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Zt.throwNullException)("obj1");if(t===null)return (0, Zt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, Fe.asOrNull)(e,_e.BoolValue);if(r!==null)return r.value===(0, Fe.asOrThrows)(t,_e.BoolValue).value;let i=(0, Fe.asOrNull)(e,_e.IntValue);if(i!==null)return i.value===(0, Fe.asOrThrows)(t,_e.IntValue).value;let a=(0, Fe.asOrNull)(e,_e.FloatValue);if(a!==null)return a.value===(0, Fe.asOrThrows)(t,_e.FloatValue).value;let s=(0, Fe.asOrNull)(e,_e.Value),o=(0, Fe.asOrNull)(t,_e.Value);if(s!==null&&o!==null)return (0, Fe.isEquatable)(s.valueObject)&&(0, Fe.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let r=this.GetRawVariableWithName(e,t),i=(0, Fe.asOrNull)(r,_e.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, Oi.tryGetValueFromMap)(this._defaultGlobalVariables,e,null);return t.exists?t.result:null}GlobalVariableExistsWithName(e){return this._globalVariables.has(e)||this._defaultGlobalVariables!==null&&this._defaultGlobalVariables.has(e)}GetRawVariableWithName(e,t){let r=null;if(t==0||t==-1){let i=null;if(this.patch!==null&&(i=this.patch.TryGetGlobal(e,null),i.exists)||(i=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Oi.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Zt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return r=this._callStack.GetTemporaryVariableWithName(e,t),r}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let r=e.variableName;if(r===null)return (0, Zt.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, Fe.asOrNull)(t,_e.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Fe.asOrNull)(this.GetRawVariableWithName(r,i),_e.VariablePointerValue),s!=null&&(r=s.variableName,i=s.contextIndex,a=i==0);while(s!=null)}a?this.SetGlobal(r,t):this._callStack.SetTemporaryVariable(r,t,e.isNewDeclaration,i);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let r=(0, Fe.asOrThrows)(e,_e.ListValue),i=(0, Fe.asOrThrows)(t,_e.ListValue);r.value&&i.value&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}SetGlobal(e,t){let r=null;if(this.patch===null&&(r=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, Oi.tryGetValueFromMap)(this._globalVariables,e,null))),_e.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, Zt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&r!==null&&t!==r.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Zt.throwNullException)("this._changedVariablesForBatchObs");this.patch!==null?this.patch.AddChangedVariable(e):this._changedVariablesForBatchObs!==null&&this._changedVariablesForBatchObs.add(e);}else this.variableChangedEvent(e,t);}ResolveVariablePointer(e){let t=e.contextIndex;t==-1&&(t=this.GetContextIndexOfVariableNamed(e.variableName));let r=this.GetRawVariableWithName(e.variableName,t),i=(0, Fe.asOrNull)(r,_e.VariablePointerValue);return i??new _e.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Po.VariablesState=Ao;Ao.dontSaveDefaultValues=true;});var Ed=C(Fo=>{Object.defineProperty(Fo,"__esModule",{value:true});Fo.PRNG=void 0;var _d=class{constructor(e){this.seed=e%2147483647,this.seed<=0&&(this.seed+=2147483646);}next(){return this.seed=this.seed*48271%2147483647}nextFloat(){return (this.next()-1)/2147483646}};Fo.PRNG=_d;});var x0=C(Oo=>{Object.defineProperty(Oo,"__esModule",{value:true});Oo.StatePatch=void 0;var bd=class{get globals(){return this._globals}get changedVariables(){return this._changedVariables}get visitCounts(){return this._visitCounts}get turnIndices(){return this._turnIndices}constructor(){if(this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map,arguments.length===1&&arguments[0]!==null){let e=arguments[0];this._globals=new Map(e._globals),this._changedVariables=new Set(e._changedVariables),this._visitCounts=new Map(e._visitCounts),this._turnIndices=new Map(e._turnIndices);}else this._globals=new Map,this._changedVariables=new Set,this._visitCounts=new Map,this._turnIndices=new Map;}TryGetGlobal(e,t){return e!==null&&this._globals.has(e)?{result:this._globals.get(e),exists:true}:{result:t,exists:false}}SetGlobal(e,t){this._globals.set(e,t);}AddChangedVariable(e){return this._changedVariables.add(e)}TryGetVisitCount(e,t){return this._visitCounts.has(e)?{result:this._visitCounts.get(e),exists:true}:{result:t,exists:false}}SetVisitCount(e,t){this._visitCounts.set(e,t);}SetTurnIndex(e,t){this._turnIndices.set(e,t);}TryGetTurnIndex(e,t){return this._turnIndices.has(e)?{result:this._turnIndices.get(e),exists:true}:{result:t,exists:false}}};Oo.StatePatch=bd;});var Sd=C(Ni=>{Object.defineProperty(Ni,"__esModule",{value:true});Ni.SimpleJson=void 0;var xi=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};Ni.SimpleJson=xi;(function(n){class e{constructor(i){if(JSON.parse("0",(s,o,u)=>u!=null)){let s=(o,u,l)=>Number.isInteger(u)&&l.source.endsWith(".0")?l.source+"f":u;this._rootObject=JSON.parse(i,s);}else {let s=i.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}n.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(i){this.WriteObjectStart(),i(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let i={};if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===n.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(i,a){if(this.WritePropertyStart(i),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(i,a){this.WritePropertyStart(i),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(i,a){this.WritePropertyStart(i),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(i){this.Assert(this.state===n.Writer.State.Object),this._propertyNameStack.push(i),this.IncrementChildCount(),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===n.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===n.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Property)),this._stateStack.push(new n.Writer.StateElement(n.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(i){this.Assert(this.state===n.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=i;}WriteArrayStart(){this.StartNewObject(true);let i=[];if(this.state===n.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=i,this._collectionStack.push(i);}else this.state===n.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(i),this._collectionStack.push(i)):(this.Assert(this.state===n.Writer.State.None),this._jsonObject=i,this._collectionStack.push(i));this._stateStack.push(new n.Writer.StateElement(n.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===n.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(i,a=true){if(i===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(i);}WriteBool(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(i));}WriteInt(i){i!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(i)));}WriteFloat(i){i!==null&&(this.StartNewObject(false),i==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):i==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(i)?this._addToCurrentObject(0):this._addToCurrentObject(i));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new n.Writer.StateElement(n.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==n.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(i,a=true){if(this.Assert(this.state===n.Writer.State.String),i===null){console.error("Warning: trying to write a null string");return}this._currentString+=i;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(i){i?this.Assert(this.state===n.Writer.State.None||this.state===n.Writer.State.Property||this.state===n.Writer.State.Array):this.Assert(this.state===n.Writer.State.Property||this.state===n.Writer.State.Array),this.state===n.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===n.Writer.State.Array||this.state===n.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:n.Writer.State.None}get childCount(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].childCount:0}get currentCollection(){return this._collectionStack.length>0?this._collectionStack[this._collectionStack.length-1]:null}get currentPropertyName(){return this._propertyNameStack.length>0?this._propertyNameStack[this._propertyNameStack.length-1]:null}IncrementChildCount(){this.Assert(this._stateStack.length>0);let i=this._stateStack.pop();i.childCount++,this._stateStack.push(i);}Assert(i){if(!i)throw Error("Assert failed while writing JSON")}_addToCurrentObject(i){this.Assert(this.currentCollection!==null),this.state===n.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(i)):this.state===n.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=i,this._propertyNameStack.pop());}}n.Writer=t,(function(r){(function(s){s[s.None=0]="None",s[s.Object=1]="Object",s[s.Array=2]="Array",s[s.Property=3]="Property",s[s.PropertyName=4]="PropertyName",s[s.String=5]="String";})(r.State||(r.State={}));class a{constructor(o){this.type=n.Writer.State.None,this.childCount=0,this.type=o;}}r.StateElement=a;})(t=n.Writer||(n.Writer={}));})(xi||(Ni.SimpleJson=xi={}));});var T0=C(No=>{Object.defineProperty(No,"__esModule",{value:true});No.Flow=void 0;var N0=vd(),xo=fr(),l1=Ae(),Dd=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new N0.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=xo.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=xo.JsonSerialisation.JArrayToRuntimeObjList(r.currentChoices);let i=r.choiceThreads;typeof i<"u"&&this.LoadFlowChoiceThreads(i,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",r=>this.callStack.WriteJson(r)),e.WriteProperty("outputStream",r=>xo.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, l1.throwNullException)("c.threadAtGeneration");r.originalThreadIndex=r.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(r.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(r.originalThreadIndex),r.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",r=>{r.WriteArrayStart();for(let i of this.currentChoices)xo.JsonSerialisation.WriteChoice(r,i);r.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let r of this.currentChoices){let i=this.callStack.ThreadWithIndex(r.originalThreadIndex);if(i!==null)r.threadAtGeneration=i.Copy();else {let a=e[`${r.originalThreadIndex}`];r.threadAtGeneration=new N0.CallStack.Thread(a,t);}}}};No.Flow=Dd;});var $0=C(Io=>{Object.defineProperty(Io,"__esModule",{value:true});Io.StoryState=void 0;var c1=vd(),h1=O0(),me=ae(),Xt=_n(),d1=vo(),wd=uo(),I0=Be(),ke=Pe(),Ad=yn(),Qt=fr(),f1=Ed(),p1=vn(),pr=gi(),Ti=tr(),de=J(),m1=ri(),it=Ae(),g1=Fi(),y1=x0(),k0=Sd(),To=T0(),C1=Ge(),Pd=class n{ToJson(e=false){let t=new k0.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=k0.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let r=this.story.ContentAtPath(new I0.Path(e)).container;if(r===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(r,0),t.exists)return t.result}return t=(0, Ti.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, it.throwNullException)("container");if(!e.visitsShouldBeCounted)return this.story.Error("Read count for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),0;if(this._patch!==null){let i=this._patch.TryGetVisitCount(e,0);if(i.exists)return i.result}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);return r.exists?r.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let i=this.VisitCountForContainer(e);i++,this._patch.SetVisitCount(e,i);return}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);r.exists?this._visitCounts.set(t,r.result+1):this._visitCounts.set(t,1);}RecordTurnIndexVisitToContainer(e){if(this._patch!==null){this._patch.SetTurnIndex(e,this.currentTurnIndex);return}let t=e.path.toString();this._turnIndices.set(t,this.currentTurnIndex);}TurnsSinceForContainer(e){if(e.turnIndexShouldBeCounted||this.story.Error("TURNS_SINCE() for target ("+e.name+" - on "+e.debugMetadata+") unknown. The story may need to be compiled with countAllVisits flag (-c)."),this._patch!==null){let i=this._patch.TryGetTurnIndex(e,0);if(i.exists)return this.currentTurnIndex-i.result}let t=e.path.toString(),r=(0, Ti.tryGetValueFromMap)(this._turnIndices,t,0);return r.exists?this.currentTurnIndex-r.result:-1}get callstackDepth(){return this.callStack.depth}get outputStream(){return this._currentFlow.outputStream}get currentChoices(){return this.canContinue?[]:this._currentFlow.currentChoices}get generatedChoices(){return this._currentFlow.currentChoices}get currentErrors(){return this._currentErrors}get currentWarnings(){return this._currentWarnings}get variablesState(){return this._variablesState}set variablesState(e){this._variablesState=e;}get callStack(){return this._currentFlow.callStack}get evaluationStack(){return this._evaluationStack}get currentTurnIndex(){return this._currentTurnIndex}set currentTurnIndex(e){this._currentTurnIndex=e;}get currentPathString(){let e=this.currentPointer;return e.isNull?null:e.path===null?(0, it.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, it.throwNullException)("previousPointer.path"):e.path.toString()}get currentPointer(){return this.callStack.currentElement.currentPointer.copy()}set currentPointer(e){this.callStack.currentElement.currentPointer=e.copy();}get previousPointer(){return this.callStack.currentThread.previousPointer.copy()}set previousPointer(e){this.callStack.currentThread.previousPointer=e.copy();}get canContinue(){return !this.currentPointer.isNull&&!this.hasError}get hasError(){return this.currentErrors!=null&&this.currentErrors.length>0}get hasWarning(){return this.currentWarnings!=null&&this.currentWarnings.length>0}get currentText(){if(this._outputStreamTextDirty){let e=new Ad.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, de.asOrNull)(r,me.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, de.asOrNull)(r,ke.ControlCommand);a!==null&&(a.commandType==ke.ControlCommand.CommandType.BeginTag?t=true:a.commandType==ke.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new Ad.StringBuilder,r=-1,i=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&r==-1&&(r=a),o||(s!=`
28
28
  `&&r>0&&r!=i&&t.Append(" "),r=-1),s==`
29
- `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new Dd.StringBuilder;for(let r of this.outputStream){let i=(0, de.asOrNull)(r,ke.ControlCommand);if(i!=null){if(i.commandType==ke.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==ke.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, de.asOrNull)(r,me.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, de.asOrNull)(r,c1.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let r=this.CleanOutputWhitespace(t.toString());this._currentTags.push(r),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=mr.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new To.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new l1.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new h1.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=mr.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,r=(0, Ti.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new To.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, it.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new n(this.story);if(t._patch=new m1.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new u1.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let r of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(r.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[r,i]of this._namedFlows)t._namedFlows.set(r,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,r){(r?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,r]of this._namedFlows)e.WriteProperty(t,i=>r.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>Yt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, it.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Yt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Yt.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",p1.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,r=t.inkSaveVersion;if(r==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(r)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+r+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=t.flows;if(i!=null){let s=i;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[u,l]of o){let c=u,h=l,d=new To.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new To.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, it.throwNullException)("this._namedFlows");this._namedFlows.set(c,d);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=t.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Yt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Yt.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Yt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new T0.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Yt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Yt.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, de.asOrNull)(e,me.StringValue);if(t!==null){let r=this.TrySplittingHeadTailWhitespace(t);if(r!==null){for(let i of r)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, it.throwNullException)("single.value");let r=-1,i=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
29
+ `&&(i=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new Ad.StringBuilder;for(let r of this.outputStream){let i=(0, de.asOrNull)(r,ke.ControlCommand);if(i!=null){if(i.commandType==ke.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(i.commandType==ke.ControlCommand.CommandType.EndTag){if(t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=false;}}else if(e){let a=(0, de.asOrNull)(r,me.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, de.asOrNull)(r,d1.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let r=this.CleanOutputWhitespace(t.toString());this._currentTags.push(r),t.Clear();}this._outputStreamTagsDirty=false;}return this._currentTags}get currentFlowName(){return this._currentFlow.name}get currentFlowIsDefaultFlow(){return this._currentFlow.name==this.kDefaultFlowName}get aliveFlowNames(){if(this._aliveFlowNamesDirty){if(this._aliveFlowNames=[],this._namedFlows!=null)for(let e of this._namedFlows.keys())e!=this.kDefaultFlowName&&this._aliveFlowNames.push(e);this._aliveFlowNamesDirty=false;}return this._aliveFlowNames}get inExpressionEvaluation(){return this.callStack.currentElement.inExpressionEvaluation}set inExpressionEvaluation(e){this.callStack.currentElement.inExpressionEvaluation=e;}constructor(e){this.kInkSaveStateVersion=10,this.kMinCompatibleLoadVersion=8,this.onDidLoadState=null,this._currentErrors=null,this._currentWarnings=null,this.divertedPointer=pr.Pointer.Null,this._currentTurnIndex=0,this.storySeed=0,this.previousRandom=0,this.didSafeExit=false,this._currentText=null,this._currentTags=null,this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true,this._patch=null,this._aliveFlowNames=null,this._namedFlows=null,this.kDefaultFlowName="DEFAULT_FLOW",this._aliveFlowNamesDirty=true,this.story=e,this._currentFlow=new To.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new h1.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new f1.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=pr.Pointer.StartOf(this.story.mainContentContainer);}SwitchFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.SwitchFlow");if(this._namedFlows===null&&(this._namedFlows=new Map,this._namedFlows.set(this.kDefaultFlowName,this._currentFlow)),e===this._currentFlow.name)return;let t,r=(0, Ti.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new To.Flow(e,this.story),this._namedFlows.set(e,t),this._aliveFlowNamesDirty=true),this._currentFlow=t,this.variablesState.callStack=this._currentFlow.callStack,this.OutputStreamDirty();}SwitchToDefaultFlow_Internal(){this._namedFlows!==null&&this.SwitchFlow_Internal(this.kDefaultFlowName);}RemoveFlow_Internal(e){if(e===null)throw new Error("Must pass a non-null string to Story.DestroyFlow");if(e===this.kDefaultFlowName)throw new Error("Cannot destroy default flow");if(this._currentFlow.name===e&&this.SwitchToDefaultFlow_Internal(),this._namedFlows===null)return (0, it.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new n(this.story);if(t._patch=new y1.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new c1.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let r of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(r.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[r,i]of this._namedFlows)t._namedFlows.set(r,i),t._aliveFlowNamesDirty=true;t._namedFlows.set(this._currentFlow.name,t._currentFlow);}return this.hasError&&(t._currentErrors=[],t._currentErrors.push(...this.currentErrors||[])),this.hasWarning&&(t._currentWarnings=[],t._currentWarnings.push(...this.currentWarnings||[])),t.variablesState=this.variablesState,t.variablesState.callStack=t.callStack,t.variablesState.patch=t._patch,t.evaluationStack.push(...this.evaluationStack),this.divertedPointer.isNull||(t.divertedPointer=this.divertedPointer.copy()),t.previousPointer=this.previousPointer.copy(),t._visitCounts=this._visitCounts,t._turnIndices=this._turnIndices,t.currentTurnIndex=this.currentTurnIndex,t.storySeed=this.storySeed,t.previousRandom=this.previousRandom,t.didSafeExit=this.didSafeExit,t}RestoreAfterPatch(){this.variablesState.callStack=this.callStack,this.variablesState.patch=this._patch;}ApplyAnyPatch(){if(this._patch!==null){this.variablesState.ApplyPatch();for(let[e,t]of this._patch.visitCounts)this.ApplyCountChanges(e,t,true);for(let[e,t]of this._patch.turnIndices)this.ApplyCountChanges(e,t,false);this._patch=null;}}ApplyCountChanges(e,t,r){(r?this._visitCounts:this._turnIndices).set(e.path.toString(),t);}WriteJson(e){if(e.WriteObjectStart(),e.WritePropertyStart("flows"),e.WriteObjectStart(),this._namedFlows!==null)for(let[t,r]of this._namedFlows)e.WriteProperty(t,i=>r.WriteJson(i));else e.WriteProperty(this._currentFlow.name,t=>this._currentFlow.WriteJson(t));if(e.WriteObjectEnd(),e.WritePropertyEnd(),e.WriteProperty("currentFlowName",this._currentFlow.name),e.WriteProperty("variablesState",t=>this.variablesState.WriteJson(t)),e.WriteProperty("evalStack",t=>Qt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, it.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Qt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Qt.JsonSerialisation.WriteIntDictionary(t,this._turnIndices)),e.WriteIntProperty("turnIdx",this.currentTurnIndex),e.WriteIntProperty("storySeed",this.storySeed),e.WriteIntProperty("previousRandom",this.previousRandom),e.WriteIntProperty("inkSaveVersion",this.kInkSaveStateVersion),e.WriteIntProperty("inkFormatVersion",g1.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,r=t.inkSaveVersion;if(r==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(r)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+r+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let i=t.flows;if(i!=null){let s=i;Object.keys(s).length===1?this._namedFlows=null:this._namedFlows===null?this._namedFlows=new Map:this._namedFlows.clear();let o=Object.entries(s);for(let[u,l]of o){let c=u,h=l,f=new To.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new To.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, it.throwNullException)("this._namedFlows");this._namedFlows.set(c,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let u=t.currentFlowName;this._currentFlow=this._namedFlows.get(u);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Qt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Qt.JsonSerialisation.JArrayToRuntimeObjList(t.currentChoices);let s=t.choiceThreads;this._currentFlow.LoadFlowChoiceThreads(s,this.story);}this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this.variablesState.SetJsonToken(t.variablesState),this.variablesState.callStack=this._currentFlow.callStack,this._evaluationStack=Qt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new I0.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Qt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Qt.JsonSerialisation.JObjectToIntDictionary(t.turnIndices),this.currentTurnIndex=parseInt(t.turnIdx),this.storySeed=parseInt(t.storySeed),this.previousRandom=parseInt(t.previousRandom);}ResetErrors(){this._currentErrors=null,this._currentWarnings=null;}ResetOutput(e=null){this.outputStream.length=0,e!==null&&this.outputStream.push(...e),this.OutputStreamDirty();}PushToOutputStream(e){let t=(0, de.asOrNull)(e,me.StringValue);if(t!==null){let r=this.TrySplittingHeadTailWhitespace(t);if(r!==null){for(let i of r)this.PushToOutputStreamIndividual(i);this.OutputStreamDirty();return}}this.PushToOutputStreamIndividual(e),this.OutputStreamDirty();}PopFromOutputStream(e){this.outputStream.splice(this.outputStream.length-e,e),this.OutputStreamDirty();}TrySplittingHeadTailWhitespace(e){let t=e.value;if(t===null)return (0, it.throwNullException)("single.value");let r=-1,i=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
30
30
  `)r==-1&&(r=c),i=c;else {if(h==" "||h==" ")continue;break}}let a=-1,s=-1;for(let c=t.length-1;c>=0;c--){let h=t[c];if(h==`
31
31
  `)a==-1&&(a=c),s=c;else {if(h==" "||h==" ")continue;break}}if(r==-1&&a==-1)return null;let o=[],u=0,l=t.length;if(r!=-1){if(r>0){let c=new me.StringValue(t.substring(0,r));o.push(c);}o.push(new me.StringValue(`
32
32
  `)),u=i+1;}if(a!=-1&&(l=s),l>u){let c=t.substring(u,l);o.push(new me.StringValue(c));}if(a!=-1&&s>i&&(o.push(new me.StringValue(`
33
- `)),a<t.length-1)){let c=t.length-a-1,h=new me.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, de.asOrNull)(e,Sd.Glue),r=(0, de.asOrNull)(e,me.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==Qt.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let l=this.outputStream.length-1;l>=0;l--){let c=this.outputStream[l],h=c instanceof ke.ControlCommand?c:null;if((c instanceof Sd.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==ke.ControlCommand.CommandType.BeginString){l>=a&&(a=-1);break}}let u=-1;if(o!=-1&&a!=-1?u=Math.min(a,o):o!=-1?u=o:u=a,u!=-1){if(r.isNewline)i=false;else if(r.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let l=this.callStack.elements;for(let c=l.length-1;c>=0;c--){let h=l[c];if(h.type==Qt.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, it.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let r=this.outputStream[t],i=(0, de.asOrNull)(r,ke.ControlCommand),a=(0, de.asOrNull)(r,me.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, de.asOrNull)(this.outputStream[t],me.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof Sd.Glue)this.outputStream.splice(e,1);else if(t instanceof ke.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof ke.ControlCommand);e--){let r=this.outputStream[e];if(r instanceof me.StringValue){if(r.isNewline)return true;if(r.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof me.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, de.asOrNull)(this.outputStream[e],ke.ControlCommand);if(t instanceof ke.ControlCommand&&t.commandType==ke.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, de.asOrNull)(e,me.ListValue);if(t){let r=t.value;if(r===null)return (0, it.throwNullException)("rawList");if(r.originNames!=null){r.origins||(r.origins=[]),r.origins.length=0;for(let i of r.originNames){if(this.story.listDefinitions===null)return (0, it.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, it.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, it.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, de.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, de.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=mr.Pointer.Null,this.previousPointer=mr.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){f1.Debug.Assert(this.callStack.currentElement.type==Qt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let r=this.outputStream[t],i=(0, de.asOrNull)(r,me.StringValue),a=(0, de.asOrNull)(r,ke.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==Qt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let r=this.story.PointerAtPath(e);!r.isNull&&r.index==-1&&(r.index=0),this.currentPointer=r,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(Qt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=mr.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof g1.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, de.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(me.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Qt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=mr.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Qt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let r=this.PopEvaluationStack();t===null&&(t=r);}if(this.PopCallStack(Qt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof d1.Void)return null;let r=(0, de.asOrThrows)(t,me.Value);return r.valueType==me.ValueType.DivertTarget?"-> "+r.valueObject.toString():r.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Io.StoryState=wd;});var $0=y(ko=>{Object.defineProperty(ko,"__esModule",{value:true});ko.Stopwatch=void 0;var Ad=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};ko.Stopwatch=Ad;});var V0=y($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.ErrorType=void 0;var R0;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(R0||($o.ErrorType=R0={}));});var Fi=y(Fn=>{Object.defineProperty(Fn,"__esModule",{value:true});Fn.Story=Fn.InkList=void 0;var Oe=ce(),Pd=We(),Fd=pr(),y1=k0(),q=Pe(),st=En(),C1=ta(),v1=cd(),q0=Et(),x=ae(),Od=Be(),Ii=_n(),Ro=vo(),_1=zt(),E1=hr(),b1=_t(),An=si(),xd=vd(),Pn=Cn(),S1=dd(),D1=$0(),en=gi(),ki=Ge(),B=Z(),z=Ae(),j0=Ed(),L0=V0(),w1=Ge();Object.defineProperty(Fn,"InkList",{enumerable:true,get:function(){return w1.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var gr=class n extends Pd.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, z.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let e,t=null,r=null;if(arguments[0]instanceof Oe.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];r=j0.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new S1.ListDefinitionsOrigin(t)),this._externals=new Map,r!==null){let i=r,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>n.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=n.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${n.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=Fd.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, B.asOrThrows)(Fd.JsonSerialisation.JTokenToRuntimeObject(o),Oe.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new j0.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>Fd.JsonSerialisation.WriteRuntimeContainer(r,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let r of this._listDefinitions.lists){e.WritePropertyStart(r.name),e.WriteObjectStart();for(let[i,a]of r.items){let s=ki.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new y1.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, z.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, z.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Od.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let r=new D1.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof An.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&r.ElapsedMilliseconds>e)break}while(this.canContinue);r.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(st.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(st.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,L0.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,L0.ErrorType.Warning);this.ResetErrors();}else {let s=new Pn.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new An.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, z.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, z.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==n.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==n.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,r,i){if(e===null)return (0, z.throwNullException)("prevText");if(t===null)return (0, z.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
34
- `;if(r==i&&e.length==t.length&&a)return n.OutputStateChange.NoChange;if(!a)return n.OutputStateChange.NewlineRemoved;if(i>r)return n.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return n.OutputStateChange.ExtendedBeyondNewline}return n.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new Pn.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof Oe.Container?t:null}PointerAtPath(e){if(e.length==0)return en.Pointer.Null;let t=new en.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, z.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(r=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,r),t.container=i.container,t.index=e.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(e),t.container=i.container,t.index=-1),i.obj==null||i.obj==this.mainContentContainer&&r>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+i.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, z.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let r=(0, B.asOrNull)(t.Resolve(),Oe.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=en.Pointer.StartOf(r),r=(0, B.asOrNull)(t.Resolve(),Oe.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, B.asOrNull)(i,C1.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof Oe.Container&&(e=false),e){let u=(0, B.asOrNull)(i,x.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new x.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, B.asOrNull)(i,q.ControlCommand);o&&o.commandType==q.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, B.asOrNull)(s,Oe.Container)||(0, B.asOrNull)(e.container,Oe.Container);for(;o;)this._prevContainers.push(o),o=(0, B.asOrNull)(o.parent,Oe.Container);}let r=t.Resolve();if(r==null)return;let i=(0, B.asOrNull)(r.parent,Oe.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let s=i.content.length>0&&r==i.content[0]&&a;s||(a=false),this.VisitContainer(i,s),r=i,i=(0, B.asOrNull)(i.parent,Oe.Container);}}PopChoiceStringAndTags(e){let t=(0, B.asOrThrows)(this.state.PopEvaluationStack(),x.StringValue);for(;this.state.evaluationStack.length>0&&(0, B.asOrNull)(this.state.PeekEvaluationStack(),Ro.Tag)!=null;){let r=(0, B.asOrNull)(this.state.PopEvaluationStack(),Ro.Tag);r&&e.push(r.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let r="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(r=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new v1.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(r+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof x.Value){let r=e;if(r instanceof x.DivertTargetValue){let i=r;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return r.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof q0.Divert){let t=e;if(t.isConditional){let r=this.state.PopEvaluationStack();if(!this.IsTruthy(r))return true}if(t.hasVariableTarget){let r=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(r);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+r+")");else if(!(i instanceof x.DivertTargetValue)){let s=(0, B.asOrNull)(i,x.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof x.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, B.asOrThrows)(i,x.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof q.ControlCommand){let t=e;switch(t.commandType){case q.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case q.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case q.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof Ii.Void)){let S=new x.StringValue(C.toString());this.state.PushToOutputStream(S);}}break;case q.ControlCommand.CommandType.NoOp:break;case q.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case q.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case q.ControlCommand.CommandType.PopFunction:case q.ControlCommand.CommandType.PopTunnel:let r=t.commandType==q.ControlCommand.CommandType.PopFunction?st.PushPopType.Function:st.PushPopType.Tunnel,i=null;if(r==st.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();i=(0, B.asOrNull)(C,x.DivertTargetValue),i===null&&this.Assert(C instanceof Ii.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=r||!this.state.callStack.canPop){let C=new Map;C.set(st.PushPopType.Function,"function return statement (~ return)"),C.set(st.PushPopType.Tunnel,"tunnel onwards statement (->->)");let S=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(S="end of flow (-> END or choice)");let w="Found "+C.get(r)+", when expected "+S;this.Error(w);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case q.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case q.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case q.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],S=0;for(let A=this.state.outputStream.length-1;A>=0;--A){let $=this.state.outputStream[A];S++;let Ee=(0, B.asOrNull)($,q.ControlCommand);if(Ee!=null){if(Ee.commandType==q.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}$ instanceof x.StringValue&&C.push($);}this.state.PopFromOutputStream(S);let w=new Pn.StringBuilder;for(let A of C.reverse())w.Append(A.toString());let O=new Ro.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(O);}else this.state.PushToOutputStream(t);break}case q.ControlCommand.CommandType.EndString:{let C=[],S=[],w=0;for(let A=this.state.outputStream.length-1;A>=0;--A){let $=this.state.outputStream[A];w++;let Ee=(0, B.asOrNull)($,q.ControlCommand);if(Ee&&Ee.commandType==q.ControlCommand.CommandType.BeginString)break;$ instanceof Ro.Tag&&S.push($),$ instanceof x.StringValue&&C.push($);}this.state.PopFromOutputStream(w);for(let A of S)this.state.PushToOutputStream(A);C=C.reverse();let O=new Pn.StringBuilder;for(let A of C)O.Append(A.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new x.StringValue(O.toString()));break}case q.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new x.IntValue(a));break;case q.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new x.IntValue(this.state.currentTurnIndex+1));break;case q.ControlCommand.CommandType.TurnsSince:case q.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof x.DivertTargetValue)){let C="";s instanceof x.IntValue&&(C=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+C);break}let o=(0, B.asOrThrows)(s,x.DivertTargetValue),u=(0, B.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Oe.Container),l;u!=null?t.commandType==q.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==q.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new x.IntValue(l));break;case q.ControlCommand.CommandType.Random:{let C=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.IntValue),S=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(S==null||!(S instanceof x.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(C==null||!(C instanceof x.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(C.value===null)return (0, z.throwNullException)("maxInt.value");if(S.value===null)return (0, z.throwNullException)("minInt.value");let w=C.value-S.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+S.value+" and maximum as "+C.value+". The maximum must be larger");let O=this.state.storySeed+this.state.previousRandom,$=new xd.PRNG(O).next(),Ee=$%w+S.value;this.state.PushEvaluationStack(new x.IntValue(Ee)),this.state.previousRandom=$;break}case q.ControlCommand.CommandType.SeedRandom:let c=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(c==null||!(c instanceof x.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, z.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Ii.Void);break;case q.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new x.IntValue(h));break;case q.ControlCommand.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new x.IntValue(d));break;case q.ControlCommand.CommandType.StartThread:break;case q.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=en.Pointer.Null);break;case q.ControlCommand.CommandType.End:this.state.ForceEnd();break;case q.ControlCommand.CommandType.ListFromInt:let p=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.IntValue),m=(0, B.asOrThrows)(this.state.PopEvaluationStack(),x.StringValue);if(p===null)throw new An.StoryException("Passed non-integer when creating a list element from a numerical value.");let f=null;if(this.listDefinitions===null)return (0, z.throwNullException)("this.listDefinitions");let v=this.listDefinitions.TryListGetDefinition(m.value,null);if(v.exists){if(p.value===null)return (0, z.throwNullException)("minInt.value");let C=v.result.TryGetItemWithValue(p.value,ki.InkListItem.Null);C.exists&&(f=new x.ListValue(C.result,p.value));}else throw new An.StoryException("Failed to find LIST called "+m.value);f==null&&(f=new x.ListValue),this.state.PushEvaluationStack(f);break;case q.ControlCommand.CommandType.ListRange:let _=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.Value),b=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.Value),E=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.ListValue);if(E===null||b===null||_===null)throw new An.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(E.value===null)return (0, z.throwNullException)("targetList.value");let g=E.value.ListWithSubRange(b.valueObject,_.valueObject);this.state.PushEvaluationStack(new x.ListValue(g));break;case q.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new An.StoryException("Expected list for LIST_RANDOM");let S=C.value,w=null;if(S===null)throw (0, z.throwNullException)("list");if(S.Count==0)w=new ki.InkList;else {let O=this.state.storySeed+this.state.previousRandom,$=new xd.PRNG(O).next(),Ee=$%S.Count,Rt=S.entries();for(let Kd=0;Kd<=Ee-1;Kd++)Rt.next();let Er=Rt.next().value,xn={Key:ki.InkListItem.fromSerializedKey(Er[0]),Value:Er[1]};if(xn.Key.originName===null)return (0, z.throwNullException)("randomItem.Key.originName");w=new ki.InkList(xn.Key.originName,this),w.Add(xn.Key,xn.Value),this.state.previousRandom=$;}this.state.PushEvaluationStack(new x.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof _1.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof E1.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new x.IntValue(a);}else r=this.state.variablesState.GetVariableWithName(t.name),r==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),r=new x.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof b1.NativeFunctionCall){let t=e,r=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(r);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,r=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,r),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==st.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
35
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(r),this.ChoosePath(new Od.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let r=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(r),r.threadAtGeneration===null)return (0, z.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, z.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=r.threadAtGeneration,this.ChoosePath(r.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],r=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new Pn.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,u),r?{returned:u,output:o}:u}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(st.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let r=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>r?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, z.throwNullException)("funcName");let r=this._externals.get(e),i=null,a=typeof r<"u";if(a&&!r.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!r.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(e),this.Assert(i!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(st.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=en.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let l=0;l<t;++l){let h=(0, B.asOrThrows)(this.state.PopEvaluationStack(),x.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=x.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new Ii.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(e,t,r=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:r});}TryCoerce(e){return e}BindExternalFunction(e,t,r=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},r);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,r=arguments[1]||new Set;if(arguments[0]instanceof Oe.Container&&(e=arguments[0]),arguments[0]instanceof Pd.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,r),this._hasValidatedExternals=true,r.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=r.size>1?"s":"",i+=": '",i+=Array.from(r).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(e!=null){for(let i of e.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,r);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, B.asOrNull)(i,Pd.InkObject),r);}else if(t!=null){let i=(0, B.asOrNull)(t,q0.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, z.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||r.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let r=0,i=e.length;r<i;r++)this.ObserveVariable(e[r],t[r]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let r=this._variableObservers.get(t);r!=null&&(r.splice(r.indexOf(e),1),r.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let r=this._variableObservers.keys();for(let i of r){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let r=this._variableObservers.get(e);if(typeof r<"u"){if(!(t instanceof x.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, B.asOrThrows)(t,x.Value);for(let a of r)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Od.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, z.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof Oe.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, B.asOrNull)(s,q.ControlCommand);if(o!=null)o.commandType==q.ControlCommand.CommandType.BeginTag?i=true:o.commandType==q.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, B.asOrNull)(s,x.StringValue);u!==null?(a===null&&(a=[]),u.value!==null&&a.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new Pn.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new Pn.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=en.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(st.PushPopType.Function)?(this.state.PopCallStack(st.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Ii.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, z.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, B.asOrNull)(t.container.parent,Oe.Container);if(!(r instanceof Oe.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new en.Pointer(r,i),t.index++,e=true,t.container===null)return (0, z.throwNullException)("pointer.container")}return e||(t=en.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let r=t[0];return r.targetPath===null?(0, z.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, z.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=r.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(r.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, B.asOrNull)(this.state.PopEvaluationStack(),x.IntValue);if(!(e instanceof x.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, z.throwNullException)("seqContainer");if(e.value===null)return (0, z.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, B.asOrThrows)(this.state.PopEvaluationStack(),x.IntValue).value;if(a===null)return (0, z.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let p=0,m=u.length;p<m;p++)l+=u.charCodeAt(p)||0;let c=l+s+this.state.storySeed,h=new xd.PRNG(Math.floor(c)),d=[];for(let p=0;p<r;++p)d.push(p);for(let p=0;p<=o;++p){let m=h.next()%d.length,f=d[m];if(d.splice(m,1),p==o)return f}throw new Error("Should never reach here")}Error(e,t=false){let r=new An.StoryException(e);throw r.useEndLineNumber=t,r}Warning(e){this.AddError(e,true);}AddError(e,t=false,r=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=r?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.callStack.elements.length-1;r>=0;--r)if(t=this.state.callStack.elements[r].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.outputStream.length-1;r>=0;--r)if(e=this.state.outputStream[r].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Fn.Story=gr;gr.inkVersionCurrent=21;(function(n){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(n.OutputStateChange||(n.OutputStateChange={}));})(gr||(Fn.Story=gr={}));});var W0=y(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.Story=void 0;var A1=Is(),P1=Ca(),Vo=ce(),qo=Pe(),$i=ti(),jo=bt(),B0=or(),F1=Qh(),O1=za(),x1=id(),N1=Fi(),yr=It(),T1=Zt(),I1=zt(),Ri=Z(),k1=vi(),$1=_i(),R1=Sn(),Lo=class n extends jo.FlowBase{get flowLevel(){return B0.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(r=null)=>{var i,a;this._errorHandler=r,this.constants=new Map;for(let c of this.FindAll(P1.ConstantDeclaration)()){let h=this.constants.get(c.constantName);if(h&&!h.Equals(c.expression)){let d=`CONST '${c.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${h.debugMetadata}.`;this.Error(d,c,false);}this.constants.set(c.constantName,c.expression);}this._listDefs=new Map;for(let c of this.FindAll(O1.ListDefinition)())!((i=c.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=c.identifier)===null||a===void 0?void 0:a.name,c);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new Vo.Container;o.AddContent(qo.ControlCommand.EvalStart());let u=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),u.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let d=new I1.VariableAssignment(c,true);d.isGlobal=true,o.AddContent(d);}o.AddContent(qo.ControlCommand.EvalEnd()),o.AddContent(qo.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(qo.ControlCommand.Done());let l=new N1.Story(s,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=r=>{let i=this._listDefs.get(r);return i||null},this.ResolveListItem=(r,i,a=null)=>{let s=null;if(r)return (s=this._listDefs.get(r))?s.ItemNamed(i):null;{let o=null,u=null;for(let[,l]of this._listDefs.entries()){let c=l.ItemNamed(i);c&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,a,false):(o=c,u=l));}return o}},this.FlattenContainersIn=r=>{let i=new Set;if(r.content)for(let a of r.content){let s=(0, Ri.asOrNull)(a,Vo.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, Ri.asOrNull)(a,Vo.Container);s&&i.add(s);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=r=>{if(r.namedContent&&r.namedContent.size>0||r.hasValidName||this._dontFlattenContainers.has(r))return;let i=(0, Ri.asOrNull)(r.parent,Vo.Container);if(i){let a=i.content.indexOf(r);i.content.splice(a,1);let s=r.ownDebugMetadata;if(r.content)for(let o of r.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),i.InsertContent(o,a),a+=1;}},this.Error=(r,i,a)=>{let s=a?$i.ErrorType.Warning:$i.ErrorType.Error,o="";if(i instanceof A1.AuthorWarning?(o+="TODO: ",s=$i.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=r,r=o,this._errorHandler!==null)this._errorHandler(r,s);else throw new Error(r);this._hadError=s===$i.ErrorType.Error,this._hadWarning=s===$i.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=r=>this.externals.has(r),this.AddExternal=r=>{this.externals.has(r.name)?this.Error(`Duplicate EXTERNAL definition of '${r.name}'`,r,false):r.name&&this.externals.set(r.name,r);},this.DontFlattenContainer=r=>{this._dontFlattenContainers.add(r);},this.NameConflictError=(r,i,a,s)=>{r.Error(`${s} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(r,i,a,s="")=>{var o;let u=s||r.typeName;if(n.IsReservedKeyword(i?.name)){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if($1.FunctionCall.IsBuiltIn(i?.name||"")){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",B0.FlowLevel.Knot),c=(0, Ri.asOrNull)(l,jo.FlowBase);if(c&&(c!==r||a===yr.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<yr.SymbolType.List)return;for(let[m,f]of this._listDefs)if(i?.name===m&&r!==f&&f.variableAssignment!==r&&this.NameConflictError(r,i?.name,f,u),!(r instanceof x1.ListElementDefinition))for(let v of f.itemDefinitions)i?.name===v.name&&this.NameConflictError(r,i?.name||"",v,u);if(a<=yr.SymbolType.Var)return;let h=i?.name&&this.variableDeclarations.get(i?.name)||null;if(h&&h!==r&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(r,i?.name||"",h,u),a<yr.SymbolType.SubFlowAndWeave)return;let p=new R1.Path(i).ResolveFromContext(r);if(p&&p!==r){this.NameConflictError(r,i?.name||"",p,u);return}if(!(a<yr.SymbolType.Arg)&&a!==yr.SymbolType.Arg){let m=(0, Ri.asOrNull)(r,jo.FlowBase);if(m||(m=(0, k1.ClosestFlowBase)(r)),m&&m.hasParameters&&m.args){for(let f of m.args)if(((o=f.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${i}': name has already been used for a argument to ${m.identifier} on ${m.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let r of e)if(r instanceof F1.IncludedFile){let i=r,a=e.indexOf(r);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let u of o.content)u instanceof jo.FlowBase?t.push(u):s.push(u);s.push(new T1.Text(`
36
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};Bo.Story=Lo;Lo.IsReservedKeyword=n=>{switch(n){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var G0=y(Wo=>{Object.defineProperty(Wo,"__esModule",{value:true});Wo.StringExpression=void 0;var M0=Pe(),V1=et(),q1=Zt(),j1=Z(),Nd=class n extends V1.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof q1.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(M0.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(M0.ControlCommand.EndString());},this.toString=()=>{let t="";for(let r of this.content)t+=r;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, j1.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};Wo.StringExpression=Nd;});var H0=y(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.LegacyTag=Cr.Tag=void 0;var L1=se(),U0=Pe(),Td=class extends L1.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?U0.ControlCommand.BeginTag():U0.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};Cr.Tag=Td;var B1=Kh(),Id=class extends B1.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};Cr.LegacyTag=Id;});var K0=y(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.DefaultFileHandler=void 0;var kd=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Mo.DefaultFileHandler=kd;});var qd=y(Ko=>{Object.defineProperty(Ko,"__esModule",{value:true});Ko.InkParser=void 0;var W1=gg(),M1=Is(),G1=Wc(),dt=Og(),ye=pi(),U1=ar(),H1=qg(),K1=ma(),Vi=bh(),Ke=Oa(),z1=Ca(),Go=a0(),J1=o0(),On=cr(),$d=lr(),Z1=et(),X1=u0(),z0=l0(),Uo=_i(),Q1=Ci(),Y1=c0(),eF=uo(),Ho=d0(),J0=Qh(),tF=f0(),nF=td(),Z0=m0(),rF=za(),iF=id(),sF=Ch(),X0=se(),aF=Sn(),Q0=lh(),Y0=Nh(),ge=Fh(),$e=sd(),oF=od(),ey=W0(),qi=G0(),kt=Yc(),vr=H0(),$t=Zt(),ty=Ih(),Rd=jh(),Vd=dr(),uF=Lc(),tn=Z(),ji=Aa(),_r=Js(),ny=ti(),lF=K0(),Q=class n extends kt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,r=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel($e.StatementLevel.Top);return new ey.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let u=this.Parse(s);if(u===null)return null;let l=[];l.push(u);do{let c=this.BeginRule();if(o()===null){this.FailRule(c);break}let d=this.Parse(s);if(d===null){this.FailRule(c);break}this.SucceedRule(c),l.push(d);}while(true);return l},this.CreateDebugMetadata=(s,o)=>{let u=new J1.DebugMetadata;return u.startLineNumber=(s?.lineIndex||0)+1,u.endLineNumber=o.lineIndex+1,u.startCharacterNumber=(s?.characterInLineIndex||0)+1,u.endCharacterNumber=o.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(s,o,u)=>{let l=(0, tn.asOrNull)(s,X0.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let d of c)(0, tn.asOrNull)(d,X0.ParsedObject)&&(d.hasOwnDebugMetadata||(d.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, tn.asOrNull)(s,ji.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,u));},this.OnStringParserError=(s,o,u=0,l=false)=>{let h=l?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${u+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,l?ny.ErrorType.Warning:ny.ErrorType.Error);else throw new Error(h)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
37
- \r`);return o?new M1.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=n.ListAllCharacterRanges();for(let u of o)s.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let c=null,h=this.Parse(this.MixedTextAndLogic);h&&(c=new Ke.ContentList(h));let d=null,p=null,m=this.ParseString("[")!==null;if(m){this.EndTagIfNecessary(c);let b=this.Parse(this.MixedTextAndLogic);b!==null&&(d=new Ke.ContentList(b)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(d);let E=this.Parse(this.MixedTextAndLogic);E!==null&&(p=new Ke.ContentList(E));}this.Whitespace(),this.EndTagIfNecessary(p??c);let f=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let v=!c&&!p&&!d;if(v&&f===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&m&&!d&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),p||(p=new Ke.ContentList),this.EndTagIfNecessary(p),f!==null)for(let b of f){let E=(0, tn.asOrNull)(b,On.Divert);E&&E.isEmpty||p.AddContent(b);}p.AddContent(new $t.Text(`
38
- `));let _=new U1.Choice(c,d,p);return u&&(_.identifier=u),_.indentationDepth=o.length,_.hasWeaveStyleInlineBrackets=m,_.condition=l,_.onceOnly=s,_.isInvisibleDefault=v,_},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new sF.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),kt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),u=this.Parse(this.BracketedName),l=new Q1.Gather(u,o);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let h=this.Parse(this.ConditionExpression),d=this.Parse(()=>this.InnerConditionalContent(h));return d===null?null:d}let o,u=s!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel($e.StatementLevel.InnerBlock);if(h!==null){o=[new Vi.ConditionalSingleBranch(h)];let p=this.Parse(this.SingleMultilineCondition);p&&(p.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",p),p.isElse=true),o.push(p));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Vi.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let d=0;d<o.length;++d){let p=o[d],m=d===o.length-1;p.ownExpression?(p.matchingEquality=true,h=true):h&&m?(p.matchingEquality=true,p.isElse=true):!m&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",p):d===0?p.isTrueBranch=true:p.isElse=true;}}else {for(let h=0;h<o.length;++h){let d=o[h],p=h===o.length-1;if(d.ownExpression===null)if(p)d.isElse=true;else if(d.isElse){let m=o[o.length-1];m.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",m):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",d);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",d);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let h of o)h.isInline=l;return new K1.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new Vi.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new Vi.ConditionalSingleBranch(s[1]);l.isElse=true,o.push(l);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel($e.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new $t.Text("")]),this.MultilineWhitespace();let l=new Vi.ConditionalSingleBranch(u);return l.ownExpression=s,l.isElse=o,l},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:kt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let u=s.length-1,l=s[u];if(l instanceof $t.Text){let c=l;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(u,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof On.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof vr.Tag&&s[0].isStart||s.push(new $t.Text(`
33
+ `)),a<t.length-1)){let c=t.length-a-1,h=new me.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, de.asOrNull)(e,wd.Glue),r=(0, de.asOrNull)(e,me.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==Xt.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let l=this.outputStream.length-1;l>=0;l--){let c=this.outputStream[l],h=c instanceof ke.ControlCommand?c:null;if((c instanceof wd.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==ke.ControlCommand.CommandType.BeginString){l>=a&&(a=-1);break}}let u=-1;if(o!=-1&&a!=-1?u=Math.min(a,o):o!=-1?u=o:u=a,u!=-1){if(r.isNewline)i=false;else if(r.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let l=this.callStack.elements;for(let c=l.length-1;c>=0;c--){let h=l[c];if(h.type==Xt.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, it.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let r=this.outputStream[t],i=(0, de.asOrNull)(r,ke.ControlCommand),a=(0, de.asOrNull)(r,me.StringValue);if(i!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, de.asOrNull)(this.outputStream[t],me.StringValue)?this.outputStream.splice(t,1):t++;this.OutputStreamDirty();}RemoveExistingGlue(){for(let e=this.outputStream.length-1;e>=0;e--){let t=this.outputStream[e];if(t instanceof wd.Glue)this.outputStream.splice(e,1);else if(t instanceof ke.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof ke.ControlCommand);e--){let r=this.outputStream[e];if(r instanceof me.StringValue){if(r.isNewline)return true;if(r.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof me.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, de.asOrNull)(this.outputStream[e],ke.ControlCommand);if(t instanceof ke.ControlCommand&&t.commandType==ke.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, de.asOrNull)(e,me.ListValue);if(t){let r=t.value;if(r===null)return (0, it.throwNullException)("rawList");if(r.originNames!=null){r.origins||(r.origins=[]),r.origins.length=0;for(let i of r.originNames){if(this.story.listDefinitions===null)return (0, it.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, it.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, it.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, de.nullIfUndefined)(t)}else {if(e>this.evaluationStack.length)throw new Error("trying to pop too many objects");let t=this.evaluationStack.splice(this.evaluationStack.length-e,e);return (0, de.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=pr.Pointer.Null,this.previousPointer=pr.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){m1.Debug.Assert(this.callStack.currentElement.type==Xt.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let r=this.outputStream[t],i=(0, de.asOrNull)(r,me.StringValue),a=(0, de.asOrNull)(r,ke.ControlCommand);if(i!=null){if(a)break;if(i.isNewline||i.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==Xt.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let r=this.story.PointerAtPath(e);!r.isNull&&r.index==-1&&(r.index=0),this.currentPointer=r,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push(Xt.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=pr.Pointer.StartOf(e),this.PassArgumentsToEvaluationStack(t);}PassArgumentsToEvaluationStack(e){if(e!==null)for(let t=0;t<e.length;t++){if(!(typeof e[t]=="number"||typeof e[t]=="string"||typeof e[t]=="boolean"||e[t]instanceof C1.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, de.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(me.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Xt.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=pr.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Xt.PushPopType.FunctionEvaluationFromGame)throw new Error("Expected external function evaluation to be complete. Stack trace: "+this.callStack.callStackTrace);let e=this.callStack.currentElement.evaluationStackHeightWhenPushed,t=null;for(;this.evaluationStack.length>e;){let r=this.PopEvaluationStack();t===null&&(t=r);}if(this.PopCallStack(Xt.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof p1.Void)return null;let r=(0, de.asOrThrows)(t,me.Value);return r.valueType==me.ValueType.DivertTarget?"-> "+r.valueObject.toString():r.valueObject}return null}AddError(e,t){t?(this._currentWarnings==null&&(this._currentWarnings=[]),this._currentWarnings.push(e)):(this._currentErrors==null&&(this._currentErrors=[]),this._currentErrors.push(e));}OutputStreamDirty(){this._outputStreamTextDirty=true,this._outputStreamTagsDirty=true;}};Io.StoryState=Pd;});var R0=C(ko=>{Object.defineProperty(ko,"__esModule",{value:true});ko.Stopwatch=void 0;var Fd=class{constructor(){this.startTime=void 0;}get ElapsedMilliseconds(){return typeof this.startTime>"u"?0:new Date().getTime()-this.startTime}Start(){this.startTime=new Date().getTime();}Stop(){this.startTime=void 0;}};ko.Stopwatch=Fd;});var q0=C($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.ErrorType=void 0;var V0;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(V0||($o.ErrorType=V0={}));});var Fi=C(Pn=>{Object.defineProperty(Pn,"__esModule",{value:true});Pn.Story=Pn.InkList=void 0;var Oe=ce(),Od=We(),xd=fr(),v1=$0(),V=Pe(),st=_n(),_1=ta(),E1=dd(),j0=Et(),O=ae(),Nd=Be(),Ii=vn(),Ro=vo(),b1=Kt(),S1=cr(),D1=_t(),wn=si(),Td=Ed(),An=yn(),w1=pd(),A1=R0(),Yt=gi(),ki=Ge(),L=J(),K=Ae(),L0=Sd(),B0=q0(),P1=Ge();Object.defineProperty(Pn,"InkList",{enumerable:true,get:function(){return P1.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var mr=class n extends Od.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, K.throwNullException)("this._state");for(let t of this._state.currentChoices)t.isInvisibleDefault||(t.index=e.length,e.push(t));return e}get currentText(){return this.IfAsyncWeCant("call currentText since it's a work in progress"),this.state.currentText}get currentTags(){return this.IfAsyncWeCant("call currentTags since it's a work in progress"),this.state.currentTags}get currentErrors(){return this.state.currentErrors}get currentWarnings(){return this.state.currentWarnings}get currentFlowName(){return this.state.currentFlowName}get currentFlowIsDefaultFlow(){return this.state.currentFlowIsDefaultFlow}get aliveFlowNames(){return this.state.aliveFlowNames}get hasError(){return this.state.hasError}get hasWarning(){return this.state.hasWarning}get variablesState(){return this.state.variablesState}get listDefinitions(){return this._listDefinitions}get state(){return this._state}StartProfiling(){}EndProfiling(){}constructor(){super(),this.inkVersionMinimumCompatible=18,this.onError=null,this.onDidContinue=null,this.onMakeChoice=null,this.onEvaluateFunction=null,this.onCompleteEvaluateFunction=null,this.onChoosePathString=null,this._prevContainers=[],this.allowExternalFunctionFallbacks=false,this._listDefinitions=null,this._variableObservers=null,this._hasValidatedExternals=false,this._temporaryEvaluationContainer=null,this._asyncContinueActive=false,this._stateSnapshotAtLastNewline=null,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount=0,this._asyncSaving=false,this._profiler=null;let e,t=null,r=null;if(arguments[0]instanceof Oe.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let i=arguments[0];r=L0.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new w1.ListDefinitionsOrigin(t)),this._externals=new Map,r!==null){let i=r,a=i.inkVersion;if(a==null)throw new Error("ink version number not found. Are you sure it's a valid .ink.json file?");let s=parseInt(a);if(s>n.inkVersionCurrent)throw new Error("Version of ink used to build story was newer than the current version of the engine");if(s<this.inkVersionMinimumCompatible)throw new Error("Version of ink used to build story is too old to be loaded by this version of the engine");s!=n.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${n.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=i.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let u;(u=i.listDefs)&&(this._listDefinitions=xd.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, L.asOrThrows)(xd.JsonSerialisation.JTokenToRuntimeObject(o),Oe.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new L0.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>xd.JsonSerialisation.WriteRuntimeContainer(r,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let r of this._listDefinitions.lists){e.WritePropertyStart(r.name),e.WriteObjectStart();for(let[i,a]of r.items){let s=ki.InkListItem.fromSerializedKey(i),o=a;e.WriteIntProperty(s.itemName,o);}e.WriteObjectEnd(),e.WritePropertyEnd();}e.WriteObjectEnd(),e.WritePropertyEnd();}if(e.WriteObjectEnd(),t)return e.toString()}ResetState(){this.IfAsyncWeCant("ResetState"),this._state=new v1.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, K.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, K.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Nd.Path("global decl"),false),this.ContinueInternal(),this.state.currentPointer=e;}this.state.variablesState.SnapshotDefaultGlobals();}SwitchFlow(e){if(this.IfAsyncWeCant("switch flow"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't switch flow to "+e);this.state.SwitchFlow_Internal(e);}RemoveFlow(e){this.state.RemoveFlow_Internal(e);}SwitchToDefaultFlow(){this.state.SwitchToDefaultFlow_Internal();}Continue(){return this.ContinueAsync(0),this.currentText}get canContinue(){return this.state.canContinue}get asyncContinueComplete(){return !this._asyncContinueActive}ContinueAsync(e){this._hasValidatedExternals||this.ValidateExternalBindings(),this.ContinueInternal(e);}ContinueInternal(e=0){this._profiler!=null&&this._profiler.PreContinue();let t=e>0;if(this._recursiveContinueCount++,this._asyncContinueActive)this._asyncContinueActive&&!t&&(this._asyncContinueActive=false);else {if(this._asyncContinueActive=t,!this.canContinue)throw new Error("Can't continue - should check canContinue before calling Continue");this._state.didSafeExit=false,this._state.ResetOutput(),this._recursiveContinueCount==1&&this._state.variablesState.StartVariableObservation();}let r=new A1.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof wn.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(i||this._asyncContinueActive&&r.ElapsedMilliseconds>e)break}while(this.canContinue);r.Stop();let a=null;if((i||!this.canContinue)&&(this._stateSnapshotAtLastNewline!==null&&this.RestoreStateSnapshot(),this.canContinue||(this.state.callStack.canPopThread&&this.AddError("Thread available to pop, threads should always be flat by the end of evaluation?"),this.state.generatedChoices.length==0&&!this.state.didSafeExit&&this._temporaryEvaluationContainer==null&&(this.state.callStack.CanPop(st.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(st.PushPopType.Function)?this.AddError("unexpectedly reached end of content. Do you need a '~ return'?"):this.state.callStack.canPop?this.AddError("unexpectedly reached end of content for unknown reason. Please debug compiler!"):this.AddError("ran out of content. Do you need a '-> DONE' or '-> END'?"))),this.state.didSafeExit=false,this._sawLookaheadUnsafeFunctionAfterNewline=false,this._recursiveContinueCount==1&&(a=this._state.variablesState.CompleteVariableObservation()),this._asyncContinueActive=false,this.onDidContinue!==null&&this.onDidContinue()),this._recursiveContinueCount--,this._profiler!=null&&this._profiler.PostContinue(),this.state.hasError||this.state.hasWarning)if(this.onError!==null){if(this.state.hasError)for(let s of this.state.currentErrors)this.onError(s,B0.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,B0.ErrorType.Warning);this.ResetErrors();}else {let s=new An.StringBuilder;throw s.Append("Ink had "),this.state.hasError&&(s.Append(`${this.state.currentErrors.length}`),s.Append(this.state.currentErrors.length==1?" error":" errors"),this.state.hasWarning&&s.Append(" and ")),this.state.hasWarning&&(s.Append(`${this.state.currentWarnings.length}`),s.Append(this.state.currentWarnings.length==1?" warning":" warnings"),this.state.hasWarning&&s.Append(" and ")),s.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "),s.Append(this.state.hasError?this.state.currentErrors[0]:this.state.currentWarnings[0]),new wn.StoryException(s.toString())}a!=null&&Object.keys(a).length>0&&this._state.variablesState.NotifyObservers(a);}ContinueSingleStep(){if(this._profiler!=null&&this._profiler.PreStep(),this.Step(),this._profiler!=null&&this._profiler.PostStep(),!this.canContinue&&!this.state.callStack.elementIsEvaluateFromGame&&this.TryFollowDefaultInvisibleChoice(),this._profiler!=null&&this._profiler.PreSnapshot(),!this.state.inStringEvaluation){if(this._stateSnapshotAtLastNewline!==null){if(this._stateSnapshotAtLastNewline.currentTags===null)return (0, K.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, K.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==n.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==n.OutputStateChange.NewlineRemoved&&this.DiscardSnapshot();}this.state.outputStreamEndsInNewline&&(this.canContinue?this._stateSnapshotAtLastNewline==null&&this.StateSnapshot():this.DiscardSnapshot());}return this._profiler!=null&&this._profiler.PostSnapshot(),false}CalculateNewlineOutputStateChange(e,t,r,i){if(e===null)return (0, K.throwNullException)("prevText");if(t===null)return (0, K.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
34
+ `;if(r==i&&e.length==t.length&&a)return n.OutputStateChange.NoChange;if(!a)return n.OutputStateChange.NewlineRemoved;if(i>r)return n.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return n.OutputStateChange.ExtendedBeyondNewline}return n.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new An.StringBuilder;for(;this.canContinue;)e.Append(this.Continue());return e.toString()}ContentAtPath(e){return this.mainContentContainer.ContentAtPath(e)}KnotContainerWithName(e){let t=this.mainContentContainer.namedContent.get(e);return t instanceof Oe.Container?t:null}PointerAtPath(e){if(e.length==0)return Yt.Pointer.Null;let t=new Yt.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, K.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(r=e.length-1,i=this.mainContentContainer.ContentAtPath(e,void 0,r),t.container=i.container,t.index=e.lastComponent.index):(i=this.mainContentContainer.ContentAtPath(e),t.container=i.container,t.index=-1),i.obj==null||i.obj==this.mainContentContainer&&r>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):i.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+i.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, K.throwNullException)("_stateSnapshotAtLastNewline"),this._stateSnapshotAtLastNewline.RestoreAfterPatch(),this._state=this._stateSnapshotAtLastNewline,this._stateSnapshotAtLastNewline=null,this._asyncSaving||this._state.ApplyAnyPatch();}DiscardSnapshot(){this._asyncSaving||this._state.ApplyAnyPatch(),this._stateSnapshotAtLastNewline=null;}CopyStateForBackgroundThreadSave(){if(this.IfAsyncWeCant("start saving on a background thread"),this._asyncSaving)throw new Error("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");let e=this._state;return this._state=this._state.CopyAndStartPatching(true),this._asyncSaving=true,e}BackgroundSaveComplete(){this._stateSnapshotAtLastNewline===null&&this._state.ApplyAnyPatch(),this._asyncSaving=false;}Step(){let e=true,t=this.state.currentPointer.copy();if(t.isNull)return;let r=(0, L.asOrNull)(t.Resolve(),Oe.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=Yt.Pointer.StartOf(r),r=(0, L.asOrNull)(t.Resolve(),Oe.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let i=t.Resolve(),a=this.PerformLogicAndFlowControl(i);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, L.asOrNull)(i,_1.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof Oe.Container&&(e=false),e){let u=(0, L.asOrNull)(i,O.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new O.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, L.asOrNull)(i,V.ControlCommand);o&&o.commandType==V.ControlCommand.CommandType.StartThread&&this.state.callStack.PushThread();}VisitContainer(e,t){(!e.countingAtStartOnly||t)&&(e.visitsShouldBeCounted&&this.state.IncrementVisitCountForContainer(e),e.turnIndexShouldBeCounted&&this.state.RecordTurnIndexVisitToContainer(e));}VisitChangedContainersDueToDivert(){let e=this.state.previousPointer.copy(),t=this.state.currentPointer.copy();if(t.isNull||t.index==-1)return;if(this._prevContainers.length=0,!e.isNull){let s=e.Resolve(),o=(0, L.asOrNull)(s,Oe.Container)||(0, L.asOrNull)(e.container,Oe.Container);for(;o;)this._prevContainers.push(o),o=(0, L.asOrNull)(o.parent,Oe.Container);}let r=t.Resolve();if(r==null)return;let i=(0, L.asOrNull)(r.parent,Oe.Container),a=true;for(;i&&(this._prevContainers.indexOf(i)<0||i.countingAtStartOnly);){let s=i.content.length>0&&r==i.content[0]&&a;s||(a=false),this.VisitContainer(i,s),r=i,i=(0, L.asOrNull)(i.parent,Oe.Container);}}PopChoiceStringAndTags(e){let t=(0, L.asOrThrows)(this.state.PopEvaluationStack(),O.StringValue);for(;this.state.evaluationStack.length>0&&(0, L.asOrNull)(this.state.PeekEvaluationStack(),Ro.Tag)!=null;){let r=(0, L.asOrNull)(this.state.PopEvaluationStack(),Ro.Tag);r&&e.push(r.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let r="",i="",a=[];if(e.hasChoiceOnlyContent&&(i=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(r=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new E1.Choice;return s.targetPath=e.pathOnChoice,s.sourcePath=e.path.toString(),s.isInvisibleDefault=e.isInvisibleDefault,s.threadAtGeneration=this.state.callStack.ForkThread(),s.tags=a.reverse(),s.text=(r+i).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof O.Value){let r=e;if(r instanceof O.DivertTargetValue){let i=r;return this.Error("Shouldn't use a divert target (to "+i.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return r.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof j0.Divert){let t=e;if(t.isConditional){let r=this.state.PopEvaluationStack();if(!this.IsTruthy(r))return true}if(t.hasVariableTarget){let r=t.variableDivertName,i=this.state.variablesState.GetVariableWithName(r);if(i==null)this.Error("Tried to divert using a target from a variable that could not be found ("+r+")");else if(!(i instanceof O.DivertTargetValue)){let s=(0, L.asOrNull)(i,O.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof O.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, L.asOrThrows)(i,O.DivertTargetValue);this.state.divertedPointer=this.PointerAtPath(a.targetPath);}else {if(t.isExternal)return this.CallExternalFunction(t.targetPathString,t.externalArgs),true;this.state.divertedPointer=t.targetPointer.copy();}return t.pushesToStack&&this.state.callStack.Push(t.stackPushType,void 0,this.state.outputStream.length),this.state.divertedPointer.isNull&&!t.isExternal&&(t&&t.debugMetadata&&t.debugMetadata.sourceName!=null?this.Error("Divert target doesn't exist: "+t.debugMetadata.sourceName):this.Error("Divert resolution failed: "+t)),true}else if(e instanceof V.ControlCommand){let t=e;switch(t.commandType){case V.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case V.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case V.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let y=this.state.PopEvaluationStack();if(!(y instanceof Ii.Void)){let D=new O.StringValue(y.toString());this.state.PushToOutputStream(D);}}break;case V.ControlCommand.CommandType.NoOp:break;case V.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case V.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case V.ControlCommand.CommandType.PopFunction:case V.ControlCommand.CommandType.PopTunnel:let r=t.commandType==V.ControlCommand.CommandType.PopFunction?st.PushPopType.Function:st.PushPopType.Tunnel,i=null;if(r==st.PushPopType.Tunnel){let y=this.state.PopEvaluationStack();i=(0, L.asOrNull)(y,O.DivertTargetValue),i===null&&this.Assert(y instanceof Ii.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=r||!this.state.callStack.canPop){let y=new Map;y.set(st.PushPopType.Function,"function return statement (~ return)"),y.set(st.PushPopType.Tunnel,"tunnel onwards statement (->->)");let D=y.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(D="end of flow (-> END or choice)");let w="Found "+y.get(r)+", when expected "+D;this.Error(w);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case V.ControlCommand.CommandType.BeginString:this.state.PushToOutputStream(t),this.Assert(this.state.inExpressionEvaluation===true,"Expected to be in an expression when evaluating a string"),this.state.inExpressionEvaluation=false;break;case V.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case V.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let y=[],D=0;for(let $=this.state.outputStream.length-1;$>=0;--$){let X=this.state.outputStream[$];D++;let Ee=(0, L.asOrNull)(X,V.ControlCommand);if(Ee!=null){if(Ee.commandType==V.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}X instanceof O.StringValue&&y.push(X);}this.state.PopFromOutputStream(D);let w=new An.StringBuilder;for(let $ of y.reverse())w.Append($.toString());let F=new Ro.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(F);}else this.state.PushToOutputStream(t);break}case V.ControlCommand.CommandType.EndString:{let y=[],D=[],w=0;for(let $=this.state.outputStream.length-1;$>=0;--$){let X=this.state.outputStream[$];w++;let Ee=(0, L.asOrNull)(X,V.ControlCommand);if(Ee&&Ee.commandType==V.ControlCommand.CommandType.BeginString)break;X instanceof Ro.Tag&&D.push(X),X instanceof O.StringValue&&y.push(X);}this.state.PopFromOutputStream(w);for(let $ of D)this.state.PushToOutputStream($);y=y.reverse();let F=new An.StringBuilder;for(let $ of y)F.Append($.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new O.StringValue(F.toString()));break}case V.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new O.IntValue(a));break;case V.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new O.IntValue(this.state.currentTurnIndex+1));break;case V.ControlCommand.CommandType.TurnsSince:case V.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof O.DivertTargetValue)){let y="";s instanceof O.IntValue&&(y=". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"),this.Error("TURNS_SINCE / READ_COUNT expected a divert target (knot, stitch, label name), but saw "+s+y);break}let o=(0, L.asOrThrows)(s,O.DivertTargetValue),u=(0, L.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Oe.Container),l;u!=null?t.commandType==V.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==V.ControlCommand.CommandType.TurnsSince?l=-1:l=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new O.IntValue(l));break;case V.ControlCommand.CommandType.Random:{let y=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.IntValue),D=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.IntValue);if(D==null||!(D instanceof O.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(y==null||!(y instanceof O.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(y.value===null)return (0, K.throwNullException)("maxInt.value");if(D.value===null)return (0, K.throwNullException)("minInt.value");let w=y.value-D.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+D.value+" and maximum as "+y.value+". The maximum must be larger");let F=this.state.storySeed+this.state.previousRandom,X=new Td.PRNG(F).next(),Ee=X%w+D.value;this.state.PushEvaluationStack(new O.IntValue(Ee)),this.state.previousRandom=X;break}case V.ControlCommand.CommandType.SeedRandom:let c=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.IntValue);if(c==null||!(c instanceof O.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, K.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Ii.Void);break;case V.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new O.IntValue(h));break;case V.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new O.IntValue(f));break;case V.ControlCommand.CommandType.StartThread:break;case V.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Yt.Pointer.Null);break;case V.ControlCommand.CommandType.End:this.state.ForceEnd();break;case V.ControlCommand.CommandType.ListFromInt:let m=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.IntValue),g=(0, L.asOrThrows)(this.state.PopEvaluationStack(),O.StringValue);if(m===null)throw new wn.StoryException("Passed non-integer when creating a list element from a numerical value.");let p=null;if(this.listDefinitions===null)return (0, K.throwNullException)("this.listDefinitions");let v=this.listDefinitions.TryListGetDefinition(g.value,null);if(v.exists){if(m.value===null)return (0, K.throwNullException)("minInt.value");let y=v.result.TryGetItemWithValue(m.value,ki.InkListItem.Null);y.exists&&(p=new O.ListValue(y.result,m.value));}else throw new wn.StoryException("Failed to find LIST called "+g.value);p==null&&(p=new O.ListValue),this.state.PushEvaluationStack(p);break;case V.ControlCommand.CommandType.ListRange:let _=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.Value),b=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.Value),d=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.ListValue);if(d===null||b===null||_===null)throw new wn.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, K.throwNullException)("targetList.value");let E=d.value.ListWithSubRange(b.valueObject,_.valueObject);this.state.PushEvaluationStack(new O.ListValue(E));break;case V.ControlCommand.CommandType.ListRandom:{let y=this.state.PopEvaluationStack();if(y===null)throw new wn.StoryException("Expected list for LIST_RANDOM");let D=y.value,w=null;if(D===null)throw (0, K.throwNullException)("list");if(D.Count==0)w=new ki.InkList;else {let F=this.state.storySeed+this.state.previousRandom,X=new Td.PRNG(F).next(),Ee=X%D.Count,_r=D.entries();for(let Jd=0;Jd<=Ee-1;Jd++)_r.next();let Er=_r.next().value,On={Key:ki.InkListItem.fromSerializedKey(Er[0]),Value:Er[1]};if(On.Key.originName===null)return (0, K.throwNullException)("randomItem.Key.originName");w=new ki.InkList(On.Key.originName,this),w.Add(On.Key,On.Value),this.state.previousRandom=X;}this.state.PushEvaluationStack(new O.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof b1.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof S1.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new O.IntValue(a);}else r=this.state.variablesState.GetVariableWithName(t.name),r==null&&(this.Warning("Variable not found: '"+t.name+"'. Using default value of 0 (false). This can happen with temporary variables if the declaration hasn't yet been hit. Globals are always given a default value on load if a value doesn't exist in the save state."),r=new O.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof D1.NativeFunctionCall){let t=e,r=this.state.PopEvaluationStack(t.numberOfParameters),i=t.Call(r);return this.state.PushEvaluationStack(i),true}return false}ChoosePathString(e,t=true,r=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,r),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==st.PushPopType.Function){let i="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(i="("+a.path.toString()+") "),new Error("Story was running a function "+i+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
35
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(r),this.ChoosePath(new Nd.Path(e));}IfAsyncWeCant(e){if(this._asyncContinueActive)throw new Error("Can't "+e+". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single Continue() call beforehand.")}ChoosePath(e,t=true){this.state.SetChosenPath(e,t),this.VisitChangedContainersDueToDivert();}ChooseChoiceIndex(e){e=e;let t=this.currentChoices;this.Assert(e>=0&&e<t.length,"choice out of range");let r=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(r),r.threadAtGeneration===null)return (0, K.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, K.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=r.threadAtGeneration,this.ChoosePath(r.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],r=false){if(this.onEvaluateFunction!==null&&this.onEvaluateFunction(e,t),this.IfAsyncWeCant("evaluate a function"),e==null)throw new Error("Function is null");if(e==""||e.trim()=="")throw new Error("Function is empty or white space.");let i=this.KnotContainerWithName(e);if(i==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(i,t);let s=new An.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let u=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,u),r?{returned:u,output:o}:u}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(st.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let r=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>r?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, K.throwNullException)("funcName");let r=this._externals.get(e),i=null,a=typeof r<"u";if(a&&!r.lookAheadSafe&&this._state.inStringEvaluation&&this.Error("External function "+e+` could not be called because 1) it wasn't marked as lookaheadSafe when BindExternalFunction was called and 2) the story is in the middle of string generation, either because choice text is being generated, or because you have ink like "hello {func()}". You can work around this by generating the result of your function into a temporary variable before the string or choice gets generated: ~ temp x = `+e+"()"),a&&!r.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){i=this.KnotContainerWithName(e),this.Assert(i!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(st.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Yt.Pointer.StartOf(i);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let l=0;l<t;++l){let h=(0, L.asOrThrows)(this.state.PopEvaluationStack(),O.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=O.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new Ii.Void,this.state.PushEvaluationStack(u);}BindExternalFunctionGeneral(e,t,r=true){this.IfAsyncWeCant("bind an external function"),this.Assert(!this._externals.has(e),"Function '"+e+"' has already been bound."),this._externals.set(e,{function:t,lookAheadSafe:r});}TryCoerce(e){return e}BindExternalFunction(e,t,r=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,i=>{this.Assert(i.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=i.length;s<o;s++)a[s]=this.TryCoerce(i[s]);return t.apply(null,a)},r);}UnbindExternalFunction(e){this.IfAsyncWeCant("unbind an external a function"),this.Assert(this._externals.has(e),"Function '"+e+"' has not been bound."),this._externals.delete(e);}ValidateExternalBindings(){let e=null,t=null,r=arguments[1]||new Set;if(arguments[0]instanceof Oe.Container&&(e=arguments[0]),arguments[0]instanceof Od.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,r),this._hasValidatedExternals=true,r.size==0)this._hasValidatedExternals=true;else {let i="Error: Missing function binding for external";i+=r.size>1?"s":"",i+=": '",i+=Array.from(r).join("', '"),i+="' ",i+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(i);}else if(e!=null){for(let i of e.content){let a=i;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(i,r);}for(let[,i]of e.namedContent)this.ValidateExternalBindings((0, L.asOrNull)(i,Od.InkObject),r);}else if(t!=null){let i=(0, L.asOrNull)(t,j0.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, K.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||r.add(a);}}}ObserveVariable(e,t){if(this.IfAsyncWeCant("observe a new variable"),this._variableObservers===null&&(this._variableObservers=new Map),!this.state.variablesState.GlobalVariableExistsWithName(e))throw new Error("Cannot observe variable '"+e+"' because it wasn't declared in the ink story.");this._variableObservers.has(e)?this._variableObservers.get(e).push(t):this._variableObservers.set(e,[t]);}ObserveVariables(e,t){for(let r=0,i=e.length;r<i;r++)this.ObserveVariable(e[r],t[r]);}RemoveVariableObserver(e,t){if(this.IfAsyncWeCant("remove a variable observer"),this._variableObservers!==null){if(t!=null){if(this._variableObservers.has(t))if(e!=null){let r=this._variableObservers.get(t);r!=null&&(r.splice(r.indexOf(e),1),r.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let r=this._variableObservers.keys();for(let i of r){let a=this._variableObservers.get(i);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(i));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let r=this._variableObservers.get(e);if(typeof r<"u"){if(!(t instanceof O.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, L.asOrThrows)(t,O.Value);for(let a of r)a(e,i.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Nd.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, K.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof Oe.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, L.asOrNull)(s,V.ControlCommand);if(o!=null)o.commandType==V.ControlCommand.CommandType.BeginTag?i=true:o.commandType==V.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, L.asOrNull)(s,O.StringValue);u!==null?(a===null&&(a=[]),u.value!==null&&a.push(u.value)):this.Error("Tag contained non-text content. Only plain text is allowed when using globalTags or TagsAtContentPath. If you want to evaluate dynamic content, you need to use story.Continue().");}else break}return a}BuildStringOfHierarchy(){let e=new An.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new An.StringBuilder;return e.BuildStringOfHierarchy(t,0,this.state.currentPointer.Resolve()),t.toString()}NextContent(){if(this.state.previousPointer=this.state.currentPointer.copy(),!this.state.divertedPointer.isNull&&(this.state.currentPointer=this.state.divertedPointer.copy(),this.state.divertedPointer=Yt.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(st.PushPopType.Function)?(this.state.PopCallStack(st.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Ii.Void),t=true):this.state.callStack.canPopThread?(this.state.callStack.PopThread(),t=true):this.state.TryExitFunctionEvaluationFromGame(),t&&!this.state.currentPointer.isNull&&this.NextContent();}}IncrementContentPointer(){let e=true,t=this.state.callStack.currentElement.currentPointer.copy();if(t.index++,t.container===null)return (0, K.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, L.asOrNull)(t.container.parent,Oe.Container);if(!(r instanceof Oe.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new Yt.Pointer(r,i),t.index++,e=true,t.container===null)return (0, K.throwNullException)("pointer.container")}return e||(t=Yt.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(i=>i.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let r=t[0];return r.targetPath===null?(0, K.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, K.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=r.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(r.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, L.asOrNull)(this.state.PopEvaluationStack(),O.IntValue);if(!(e instanceof O.IntValue))return this.Error("expected number of elements in sequence for shuffle index"),0;let t=this.state.currentPointer.container;if(t===null)return (0, K.throwNullException)("seqContainer");if(e.value===null)return (0, K.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, L.asOrThrows)(this.state.PopEvaluationStack(),O.IntValue).value;if(a===null)return (0, K.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let m=0,g=u.length;m<g;m++)l+=u.charCodeAt(m)||0;let c=l+s+this.state.storySeed,h=new Td.PRNG(Math.floor(c)),f=[];for(let m=0;m<r;++m)f.push(m);for(let m=0;m<=o;++m){let g=h.next()%f.length,p=f[g];if(f.splice(g,1),m==o)return p}throw new Error("Should never reach here")}Error(e,t=false){let r=new wn.StoryException(e);throw r.useEndLineNumber=t,r}Warning(e){this.AddError(e,true);}AddError(e,t=false,r=false){let i=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(i!=null){let s=r?i.endLineNumber:i.startLineNumber;e="RUNTIME "+a+": '"+i.fileName+"' line "+s+": "+e;}else this.state.currentPointer.isNull?e="RUNTIME "+a+": "+e:e="RUNTIME "+a+": ("+this.state.currentPointer+"): "+e;this.state.AddError(e,t),t||this.state.ForceEnd();}Assert(e,t=null){if(e==false)throw t==null&&(t="Story assert"),new Error(t+" "+this.currentDebugMetadata)}get currentDebugMetadata(){let e,t=this.state.currentPointer;if(!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.callStack.elements.length-1;r>=0;--r)if(t=this.state.callStack.elements[r].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let r=this.state.outputStream.length-1;r>=0;--r)if(e=this.state.outputStream[r].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};Pn.Story=mr;mr.inkVersionCurrent=21;(function(n){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(n.OutputStateChange||(n.OutputStateChange={}));})(mr||(Pn.Story=mr={}));});var M0=C(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.Story=void 0;var F1=Is(),O1=Ca(),Vo=ce(),qo=Pe(),$i=ti(),jo=bt(),W0=ar(),x1=ed(),N1=za(),T1=ad(),I1=Fi(),gr=It(),k1=Jt(),$1=Kt(),Ri=J(),R1=vi(),V1=_i(),q1=bn(),Lo=class n extends jo.FlowBase{get flowLevel(){return W0.FlowLevel.Story}get hadError(){return this._hadError}get hadWarning(){return this._hadWarning}constructor(e,t=false){super(null,e,null,false,t),this._errorHandler=null,this._hadError=false,this._hadWarning=false,this._dontFlattenContainers=new Set,this._listDefs=new Map,this.constants=new Map,this.externals=new Map,this.countAllVisits=false,this.ExportRuntime=(r=null)=>{var i,a;this._errorHandler=r,this.constants=new Map;for(let c of this.FindAll(O1.ConstantDeclaration)()){let h=this.constants.get(c.constantName);if(h&&!h.Equals(c.expression)){let f=`CONST '${c.constantName}' has been redefined with a different value. Multiple definitions of the same CONST are valid so long as they contain the same value. Initial definition was on ${h.debugMetadata}.`;this.Error(f,c,false);}this.constants.set(c.constantName,c.expression);}this._listDefs=new Map;for(let c of this.FindAll(N1.ListDefinition)())!((i=c.identifier)===null||i===void 0)&&i.name&&this._listDefs.set((a=c.identifier)===null||a===void 0?void 0:a.name,c);this.externals=new Map,this.ResolveWeavePointNaming();let s=this.runtimeObject,o=new Vo.Container;o.AddContent(qo.ControlCommand.EvalStart());let u=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),u.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let f=new $1.VariableAssignment(c,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(qo.ControlCommand.EvalEnd()),o.AddContent(qo.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(qo.ControlCommand.Done());let l=new I1.Story(s,u);return this.runtimeObject=l,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(l.ResetState(),l)},this.ResolveList=r=>{let i=this._listDefs.get(r);return i||null},this.ResolveListItem=(r,i,a=null)=>{let s=null;if(r)return (s=this._listDefs.get(r))?s.ItemNamed(i):null;{let o=null,u=null;for(let[,l]of this._listDefs.entries()){let c=l.ItemNamed(i);c&&(o?this.Error(`Ambiguous item name '${i}' found in multiple sets, including ${u.identifier} and ${l.identifier}`,a,false):(o=c,u=l));}return o}},this.FlattenContainersIn=r=>{let i=new Set;if(r.content)for(let a of r.content){let s=(0, Ri.asOrNull)(a,Vo.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, Ri.asOrNull)(a,Vo.Container);s&&i.add(s);}for(let a of i)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=r=>{if(r.namedContent&&r.namedContent.size>0||r.hasValidName||this._dontFlattenContainers.has(r))return;let i=(0, Ri.asOrNull)(r.parent,Vo.Container);if(i){let a=i.content.indexOf(r);i.content.splice(a,1);let s=r.ownDebugMetadata;if(r.content)for(let o of r.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),i.InsertContent(o,a),a+=1;}},this.Error=(r,i,a)=>{let s=a?$i.ErrorType.Warning:$i.ErrorType.Error,o="";if(i instanceof F1.AuthorWarning?(o+="TODO: ",s=$i.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",i&&i.debugMetadata!==null&&i.debugMetadata.startLineNumber>=1&&(i.debugMetadata.fileName!=null&&(o+=`'${i.debugMetadata.fileName}' `),o+=`line ${i.debugMetadata.startLineNumber}: `),o+=r,r=o,this._errorHandler!==null)this._errorHandler(r,s);else throw new Error(r);this._hadError=s===$i.ErrorType.Error,this._hadWarning=s===$i.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=r=>this.externals.has(r),this.AddExternal=r=>{this.externals.has(r.name)?this.Error(`Duplicate EXTERNAL definition of '${r.name}'`,r,false):r.name&&this.externals.set(r.name,r);},this.DontFlattenContainer=r=>{this._dontFlattenContainers.add(r);},this.NameConflictError=(r,i,a,s)=>{r.Error(`${s} '${i}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(r,i,a,s="")=>{var o;let u=s||r.typeName;if(n.IsReservedKeyword(i?.name)){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a reserved keyword`);return}else if(V1.FunctionCall.IsBuiltIn(i?.name||"")){r.Error(`'${i}' cannot be used for the name of a ${u.toLowerCase()} because it's a built in function`);return}let l=this.ContentWithNameAtLevel(i?.name||"",W0.FlowLevel.Knot),c=(0, Ri.asOrNull)(l,jo.FlowBase);if(c&&(c!==r||a===gr.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<gr.SymbolType.List)return;for(let[g,p]of this._listDefs)if(i?.name===g&&r!==p&&p.variableAssignment!==r&&this.NameConflictError(r,i?.name,p,u),!(r instanceof T1.ListElementDefinition))for(let v of p.itemDefinitions)i?.name===v.name&&this.NameConflictError(r,i?.name||"",v,u);if(a<=gr.SymbolType.Var)return;let h=i?.name&&this.variableDeclarations.get(i?.name)||null;if(h&&h!==r&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(r,i?.name||"",h,u),a<gr.SymbolType.SubFlowAndWeave)return;let m=new q1.Path(i).ResolveFromContext(r);if(m&&m!==r){this.NameConflictError(r,i?.name||"",m,u);return}if(!(a<gr.SymbolType.Arg)&&a!==gr.SymbolType.Arg){let g=(0, Ri.asOrNull)(r,jo.FlowBase);if(g||(g=(0, R1.ClosestFlowBase)(r)),g&&g.hasParameters&&g.args){for(let p of g.args)if(((o=p.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${i}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let r of e)if(r instanceof x1.IncludedFile){let i=r,a=e.indexOf(r);if(e.splice(a,1),i.includedStory){let s=[],o=i.includedStory;if(o.content!=null){for(let u of o.content)u instanceof jo.FlowBase?t.push(u):s.push(u);s.push(new k1.Text(`
36
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};Bo.Story=Lo;Lo.IsReservedKeyword=n=>{switch(n){case "true":case "false":case "not":case "return":case "else":case "VAR":case "CONST":case "temp":case "LIST":case "function":return true}return false};});var U0=C(Wo=>{Object.defineProperty(Wo,"__esModule",{value:true});Wo.StringExpression=void 0;var G0=Pe(),j1=et(),L1=Jt(),B1=J(),Id=class n extends j1.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof L1.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(G0.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(G0.ControlCommand.EndString());},this.toString=()=>{let t="";for(let r of this.content)t+=r;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, B1.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};Wo.StringExpression=Id;});var K0=C(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.LegacyTag=yr.Tag=void 0;var W1=se(),H0=Pe(),kd=class extends W1.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?H0.ControlCommand.BeginTag():H0.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};yr.Tag=kd;var M1=Jh(),$d=class extends M1.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};yr.LegacyTag=$d;});var z0=C(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.DefaultFileHandler=void 0;var Rd=class{constructor(e){this.rootPath=e,this.ResolveInkFilename=()=>{throw Error("Can't resolve filename because no FileHandler was provided when instantiating the parser / compiler.")},this.LoadInkFileContents=()=>{throw Error("Can't load ink content because no FileHandler was provided when instantiating the parser / compiler.")};}};Mo.DefaultFileHandler=Rd;});var Ld=C(Ko=>{Object.defineProperty(Ko,"__esModule",{value:true});Ko.InkParser=void 0;var G1=yg(),U1=Is(),H1=Gc(),dt=xg(),ye=pi(),K1=sr(),z1=jg(),J1=ma(),Vi=Dh(),Ke=Oa(),Z1=Ca(),Go=o0(),X1=u0(),Fn=lr(),Vd=ur(),Q1=et(),Y1=l0(),J0=c0(),Uo=_i(),eF=Ci(),tF=h0(),nF=uo(),Ho=f0(),Z0=ed(),rF=p0(),iF=rd(),X0=g0(),sF=za(),aF=ad(),oF=_h(),Q0=se(),uF=bn(),Y0=hh(),ey=Ih(),ge=xh(),$e=od(),lF=ld(),ty=M0(),qi=U0(),kt=th(),Cr=K0(),$t=Jt(),ny=$h(),qd=Bh(),jd=hr(),cF=Wc(),en=J(),ji=Aa(),vr=Js(),ry=ti(),hF=z0(),Q=class n extends kt.StringParser{get fileHandler(){if(!this._fileHandler)throw new Error("No FileHandler defined");return this._fileHandler}set fileHandler(e){this._fileHandler=e;}constructor(e,t=null,r=null,i=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel($e.StatementLevel.Top);return new ty.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let u=this.Parse(s);if(u===null)return null;let l=[];l.push(u);do{let c=this.BeginRule();if(o()===null){this.FailRule(c);break}let f=this.Parse(s);if(f===null){this.FailRule(c);break}this.SucceedRule(c),l.push(f);}while(true);return l},this.CreateDebugMetadata=(s,o)=>{let u=new X1.DebugMetadata;return u.startLineNumber=(s?.lineIndex||0)+1,u.endLineNumber=o.lineIndex+1,u.startCharacterNumber=(s?.characterInLineIndex||0)+1,u.endCharacterNumber=o.characterInLineIndex+1,u.fileName=this._filename,u},this.RuleDidSucceed=(s,o,u)=>{let l=(0, en.asOrNull)(s,Q0.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let f of c)(0, en.asOrNull)(f,Q0.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, en.asOrNull)(s,ji.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,u));},this.OnStringParserError=(s,o,u=0,l=false)=>{let h=l?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${u+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,l?ry.ErrorType.Warning:ry.ErrorType.Error);else throw new Error(h)},this.AuthorWarning=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!=="TODO")return null;this.Whitespace(),this.ParseString(":"),this.Whitespace();let o=this.ParseUntilCharactersFromString(`
37
+ \r`);return o?new U1.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=n.ListAllCharacterRanges();for(let u of o)s.AddCharacters(u.ToCharacterSet());},this._parsingChoice=false,this.Choice=()=>{let s=true,o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("*"));if(!o){if(o=this.Interleave(this.OptionalExclude(this.Whitespace),this.String("+")),o===null)return null;s=false;}let u=this.Parse(this.BracketedName);this.Whitespace(),u!=null&&this.Newline();let l=this.Parse(this.ChoiceCondition);if(this.Whitespace(),this._parsingChoice)throw new Error("Already parsing a choice - shouldn't have nested choices");this._parsingChoice=true;let c=null,h=this.Parse(this.MixedTextAndLogic);h&&(c=new Ke.ContentList(h));let f=null,m=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(c);let b=this.Parse(this.MixedTextAndLogic);b!==null&&(f=new Ke.ContentList(b)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(m=new Ke.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(m??c);let p=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let v=!c&&!m&&!f;if(v&&p===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),m||(m=new Ke.ContentList),this.EndTagIfNecessary(m),p!==null)for(let b of p){let d=(0, en.asOrNull)(b,Fn.Divert);d&&d.isEmpty||m.AddContent(b);}m.AddContent(new $t.Text(`
38
+ `));let _=new K1.Choice(c,f,m);return u&&(_.identifier=u),_.indentationDepth=o.length,_.hasWeaveStyleInlineBrackets=g,_.condition=l,_.onceOnly=s,_.isInvisibleDefault=v,_},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new oF.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),kt.ParseSuccess),this.ChoiceSingleCondition=()=>{if(this.ParseString("{")===null)return null;let s=this.Expect(this.Expression,"choice condition inside { }");return this.DisallowIncrement(s),this.Expect(this.String("}"),"closing '}' for choice condition"),s},this.Gather=()=>{let s=this.Parse(this.GatherDashes);if(s===null)return null;let o=Number(s),u=this.Parse(this.BracketedName),l=new eF.Gather(u,o);return this.Newline(),l},this.GatherDashes=()=>{this.Whitespace();let s=0;for(;this.ParseDashNotArrow()!==null;)s+=1,this.Whitespace();return s===0?null:s},this.ParseDashNotArrow=()=>{let s=this.BeginRule();return this.ParseString("->")===null&&this.ParseSingleCharacter()==="-"?this.SucceedRule(s):this.FailRule(s)},this.BracketedName=()=>{if(this.ParseString("(")===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing ')' for bracketed name"),s)},this.InnerConditionalContent=s=>{if(s===void 0){let h=this.Parse(this.ConditionExpression),f=this.Parse(()=>this.InnerConditionalContent(h));return f===null?null:f}let o,u=s!==null,l=this.Parse(this.Newline)===null;if(l&&!u)return null;if(l)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel($e.StatementLevel.InnerBlock);if(h!==null){o=[new Vi.ConditionalSingleBranch(h)];let m=this.Parse(this.SingleMultilineCondition);m&&(m.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",m),m.isElse=true),o.push(m));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Vi.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let f=0;f<o.length;++f){let m=o[f],g=f===o.length-1;m.ownExpression?(m.matchingEquality=true,h=true):h&&g?(m.matchingEquality=true,m.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",m):f===0?m.isTrueBranch=true:m.isElse=true;}}else {for(let h=0;h<o.length;++h){let f=o[h],m=h===o.length-1;if(f.ownExpression===null)if(m)f.isElse=true;else if(f.isElse){let g=o[o.length-1];g.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",g):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let h of o)h.isInline=l;return new J1.Conditional(s,o)},this.InlineConditionalBranches=()=>{let s=this.Interleave(this.MixedTextAndLogic,this.Exclude(this.String("|")),null,false);if(s===null||s.length===0)return null;let o=[];if(s.length>2)this.Error("Expected one or two alternatives separated by '|' in inline conditional");else {let u=new Vi.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new Vi.ConditionalSingleBranch(s[1]);l.isElse=true,o.push(l);}}return o},this.MultilineConditionalBranches=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineCondition);return s===null?null:(this.MultilineWhitespace(),s)},this.SingleMultilineCondition=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=null,o=this.Parse(this.ElseExpression)!==null;o||(s=this.Parse(this.ConditionExpression));let u=this.StatementsAtLevel($e.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new $t.Text("")]),this.MultilineWhitespace();let l=new Vi.ConditionalSingleBranch(u);return l.ownExpression=s,l.isElse=o,l},this.ConditionExpression=()=>{let s=this.Parse(this.Expression);return s===null||(this.DisallowIncrement(s),this.Whitespace(),this.ParseString(":")===null)?null:s},this.ElseExpression=()=>this.ParseString("else")===null||(this.Whitespace(),this.ParseString(":")===null)?null:kt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let u=s.length-1,l=s[u];if(l instanceof $t.Text){let c=l;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(u,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof Fn.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Cr.Tag&&s[0].isStart||s.push(new $t.Text(`
39
39
  `)),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),s)},this.MixedTextAndLogic=()=>{this.ParseObject(this.Spaced(this.String("~")))!==null&&this.Error("You shouldn't use a '~' here - tildas are for logic that's on its own line. To do inline logic, use { curly braces } instead");let o=this.Interleave(this.Optional(this.ContentText),this.Optional(this.InlineLogicOrGlueOrStartTag));if(!this._parsingChoice){let u=this.Parse(this.MultiDivert);u!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...u));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),u=this.ParseString("\\")!==null;if(u||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),u){let l=this.ParseSingleCharacter();s+=l;}}else break}while(true);return s!==null?new $t.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new ye.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new ye.CharacterSet(`{}|
40
- \r\\#`),this._notTextEndCharactersChoice=new ye.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new ye.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let u=this.ParseUntil(s,this._nonTextPauseCharacters,o);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;s=[],this.EndTagIfNecessary(s);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let d=new ty.TunnelOnwards;if(l<u.length-1){let p=(0, tn.asOrNull)(u[l+1],On.Divert);d.divertAfter=p;}s.push(d);break}}else {let h=u[l];l<u.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&u.length===1){let l=new On.Divert(null);l.isEmpty=true,s.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new On.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new aF.Path(s);return new On.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof ty.TunnelOnwards)return null;let u=s[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let c=this.Expect(this.Expression,"value expression to be assigned");return u||l?new Ho.IncDecExpression(o,c,u):new Rd.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof Ho.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Q0.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>s){let c=`right side of '${l.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,l),c);if(h===null)return this.FailRule(u),null;o=this.SucceedRule(u,h);continue}this.FailRule(u);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&o!==null&&(u=this.ExpressionUnary()),u===null)return null;o!==null&&(u=uF.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof Vd.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new Ho.IncDecExpression(h.identifier,c);}}return u},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new $d.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new _r.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new _r.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new $t.Text("")]:o.find(u=>u instanceof On.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new qi.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new _r.NumberExpression(true,"bool"):s==="false"?new _r.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new Uo.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||ey.Story.IsReservedKeyword(s[0].name)?null:new Vd.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(o.precedence));return u?new G1.BinaryExpression(s,u,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new Z0.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${u?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,u=false)=>{let l=new tF.InfixOperator(s,o,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
40
+ \r\\#`),this._notTextEndCharactersChoice=new ye.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new ye.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersString.AddCharacters('"'));let s=()=>this.OneOf([this.ParseDivertArrow,this.ParseThreadArrow,this.EndOfLine,this.Glue]),o=null;this.parsingStringExpression?o=this._notTextEndCharactersString:this._parsingChoice?o=this._notTextEndCharactersChoice:o=this._nonTextEndCharacters;let u=this.ParseUntil(s,this._nonTextPauseCharacters,o);return u!==null?u:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let u=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!u)return null;s=[],this.EndTagIfNecessary(s);for(let l=0;l<u.length;++l)if(l%2===0){if(u[l]==="->->"){l===0||l===u.length-1||l===u.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new ny.TunnelOnwards;if(l<u.length-1){let m=(0, en.asOrNull)(u[l+1],Fn.Divert);f.divertAfter=m;}s.push(f);break}}else {let h=u[l];l<u.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&u.length===1){let l=new Fn.Divert(null);l.isEmpty=true,s.push(l),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new Fn.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let u=new uF.Path(s);return new Fn.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof ny.TunnelOnwards)return null;let u=s[0];return u.isTunnel?null:u},this.DotSeparatedDivertPathComponents=()=>this.Interleave(this.Spaced(this.IdentifierWithMetadata),this.Exclude(this.String("."))),this.ParseDivertArrowOrTunnelOnwards=()=>{let s=0;for(;this.ParseString("->")!==null;)s+=1;return s===0?null:s===1?"->":(s===2||this.Error("Unexpected number of arrows in divert. Should only have '->' or '->->'"),"->->")},this.ParseDivertArrow=()=>this.ParseString("->"),this.ParseThreadArrow=()=>this.ParseString("<-"),this._binaryOperators=[],this._maxBinaryOpLength=0,this.TempDeclarationOrAssignment=()=>{this.Whitespace();let s=this.ParseTempKeyword();this.Whitespace();let o=null;if(s?o=this.Expect(this.IdentifierWithMetadata,"variable name"):o=this.Parse(this.IdentifierWithMetadata),o===null)return null;this.Whitespace();let u=this.ParseString("+")!==null,l=this.ParseString("-")!==null;if(u&&l&&this.Error("Unexpected sequence '+-'"),this.ParseString("=")===null)return s&&this.Error("Expected '='"),null;let c=this.Expect(this.Expression,"value expression to be assigned");return u||l?new Ho.IncDecExpression(o,c,u):new qd.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof Ho.IncDecExpression&&this.Error("Can't use increment/decrement here. It can only be used on a ~ line");},this.ParseTempKeyword=()=>{let s=this.BeginRule();return this.Parse(this.Identifier)==="temp"?(this.SucceedRule(s),true):(this.FailRule(s),false)},this.ReturnStatement=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="return")return null;this.Whitespace();let o=this.Parse(this.Expression);return new Y0.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let u=this.BeginRule(),l=this.ParseInfixOperator();if(l!==null&&l.precedence>s){let c=`right side of '${l.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,l),c);if(h===null)return this.FailRule(u),null;o=this.SucceedRule(u,h);continue}this.FailRule(u);break}return this.Whitespace(),o},this.ExpressionUnary=()=>{let s=this.Parse(this.ExpressionDivertTarget);if(s!==null)return s;let o=this.OneOf([this.String("-"),this.String("!")]);o===null&&(o=this.Parse(this.ExpressionNot)),this.Whitespace();let u=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(u===null&&o!==null&&(u=this.ExpressionUnary()),u===null)return null;o!==null&&(u=cF.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof jd.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new Ho.IncDecExpression(h.identifier,c);}}return u},this.ExpressionNot=()=>{let s=this.Identifier();return s==="not"?s:null},this.ExpressionLiteral=()=>this.OneOf([this.ExpressionFloat,this.ExpressionInt,this.ExpressionBool,this.ExpressionString]),this.ExpressionDivertTarget=()=>{this.Whitespace();let s=this.Parse(this.SingleDivert);return !s||s&&s.isThread?null:(this.Whitespace(),new Vd.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new vr.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new vr.NumberExpression(s,"float")},this.ExpressionString=()=>{if(this.ParseString('"')===null)return null;this.parsingStringExpression=true;let o=this.Parse(this.MixedTextAndLogic);return this.Expect(this.String('"'),"close quote for string expression"),this.parsingStringExpression=false,o===null?o=[new $t.Text("")]:o.find(u=>u instanceof Fn.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new qi.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new vr.NumberExpression(true,"bool"):s==="false"?new vr.NumberExpression(false,"bool"):null},this.ExpressionFunctionCall=()=>{let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);return o===null?null:new Uo.FunctionCall(s,o)},this.ExpressionFunctionCallArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Exclude(this.String(",")),o=this.Interleave(this.Expression,s);return o===null&&(o=[]),this.Whitespace(),this.Expect(this.String(")"),"closing ')' for function call"),o},this.ExpressionVariableName=()=>{let s=this.Interleave(this.IdentifierWithMetadata,this.Exclude(this.Spaced(this.String("."))));return s===null||ty.Story.IsReservedKeyword(s[0].name)?null:new jd.VariableReference(s)},this.ExpressionParen=()=>{if(this.ParseString("(")===null)return null;let s=this.Parse(this.Expression);return s===null?null:(this.Whitespace(),this.Expect(this.String(")"),"closing parenthesis ')' for expression"),s)},this.ExpressionInfixRight=(s,o)=>{if(!s)return null;this.Whitespace();let u=this.Parse(()=>this.Expression(o.precedence));return u?new H1.BinaryExpression(s,u,o.type):null},this.ParseInfixOperator=()=>{for(let s of this._binaryOperators){let o=this.BeginRule();if(this.ParseString(s.type)!==null){if(s.requireWhitespace&&this.Whitespace()===null){this.FailRule(o);continue}return this.SucceedRule(o,s)}this.FailRule(o);}return null},this.ExpressionList=()=>{if(this.Whitespace(),this.ParseString("(")===null)return null;this.Whitespace();let s=this.SeparatedList(this.ListMember,this.Spaced(this.String(",")));return this.Whitespace(),this.ParseString(")")===null?null:new X0.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let u=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${u?.name}`;}return this.Whitespace(),s},this.RegisterExpressionOperators=()=>{this.RegisterBinaryOperator("&&",1),this.RegisterBinaryOperator("||",1),this.RegisterBinaryOperator("and",1,true),this.RegisterBinaryOperator("or",1,true),this.RegisterBinaryOperator("==",2),this.RegisterBinaryOperator(">=",2),this.RegisterBinaryOperator("<=",2),this.RegisterBinaryOperator("<",2),this.RegisterBinaryOperator(">",2),this.RegisterBinaryOperator("!=",2),this.RegisterBinaryOperator("?",3),this.RegisterBinaryOperator("has",3,true),this.RegisterBinaryOperator("!?",3),this.RegisterBinaryOperator("hasnt",3,true),this.RegisterBinaryOperator("^",3),this.RegisterBinaryOperator("+",4),this.RegisterBinaryOperator("-",5),this.RegisterBinaryOperator("*",6),this.RegisterBinaryOperator("/",7),this.RegisterBinaryOperator("%",8),this.RegisterBinaryOperator("mod",8,true);},this.RegisterBinaryOperator=(s,o,u=false)=>{let l=new rF.InfixOperator(s,o,u);this._binaryOperators.push(l),this._maxBinaryOpLength=Math.max(this._maxBinaryOpLength,s.length);},this._openFilenames=[],this.IncludeStatement=()=>{if(this.Whitespace(),this.ParseString("INCLUDE")===null)return null;this.Whitespace();let s=this.Expect(()=>this.ParseUntilCharactersFromString(`
41
41
  \r`),"filename for include statement");s=s.replace(new RegExp(/[ \t]+$/g),"");let o=this.fileHandler.ResolveInkFilename(s,this._filename);if(this.FilenameIsAlreadyOpen(o))return this.Error(`Recursive INCLUDE detected: '${o}' is already open.`),this.ParseUntilCharactersFromString(`\r
42
- `),new J0.IncludedFile(null);this.AddOpenFilename(o);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
43
- Error:${c}`);}return l!=null&&(u=new n(l,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new J0.IncludedFile(u)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel($e.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new nF.Knot(s.name,u,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,u=s?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),o=new ji.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new z0.FlowDecl(o,l,u)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel($e.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new oF.Stitch(s.name,u,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new z0.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new ye.CharacterSet("="),null),[new $t.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(s==null&&u===null)return null;let l=new W1.Argument;return o!==null&&(l.isDivertTarget=true),s!==null&&s.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=s,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new ji.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);u===null&&(u=[]);let l=u.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(tn.filterUndef);return new X1.ExternalDeclaration(o,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new Ke.ContentList;o instanceof Z1.Expression&&!(o instanceof Uo.FunctionCall||o instanceof Ho.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
42
+ `),new Z0.IncludedFile(null);this.AddOpenFilename(o);let u=null,l="";try{l=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
43
+ Error:${c}`);}return l!=null&&(u=new n(l,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Z0.IncludedFile(u)},this.FilenameIsAlreadyOpen=s=>this._rootParser._openFilenames.includes(s),this.AddOpenFilename=s=>{this._rootParser._openFilenames.push(s);},this.RemoveOpenFilename=s=>{this._rootParser._openFilenames.splice(this._rootParser._openFilenames.indexOf(s),1);},this.KnotDefinition=()=>{let s=this.Parse(this.KnotDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after knot name definition",this.SkipToNextLine);let o=()=>this.StatementsAtLevel($e.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new iF.Knot(s.name,u,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,u=s?.name==="function";u?(this.Expect(this.Whitespace,"whitespace after the 'function' keyword"),o=this.Parse(this.IdentifierWithMetadata)):o=s,o===null&&(this.Error(`Expected the name of the ${u?"function":"knot"}`),o=new ji.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new J0.FlowDecl(o,l,u)},this.KnotTitleEquals=()=>{let s=this.ParseCharactersFromString("=");return s===null||s.length<=1?null:s},this.StitchDefinition=()=>{let s=this.Parse(this.StitchDeclaration);if(s===null)return null;this.Expect(this.EndOfLine,"end of line after stitch name",this.SkipToNextLine);let o=()=>this.StatementsAtLevel($e.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new lF.Stitch(s.name,u,s.args,s.isFunction)},this.StitchDeclaration=()=>{if(this.Whitespace(),this.ParseString("=")===null||this.ParseString("=")!==null)return null;this.Whitespace();let s=this.ParseString("function")!==null;s&&this.Whitespace();let o=this.Parse(this.IdentifierWithMetadata);if(o===null)return null;this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new J0.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new ye.CharacterSet("="),null),[new $t.Text("<ERROR IN FLOW>")]),this.BracketedKnotDeclArguments=()=>{if(this.ParseString("(")===null)return null;let s=this.Interleave(this.Spaced(this.FlowDeclArgument),this.Exclude(this.String(",")));return this.Expect(this.String(")"),"closing ')' for parameter list"),s===null&&(s=[]),s},this.FlowDeclArgument=()=>{let s=this.Parse(this.IdentifierWithMetadata);this.Whitespace();let o=this.ParseDivertArrow();this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(s==null&&u===null)return null;let l=new G1.Argument;return o!==null&&(l.isDivertTarget=true),s!==null&&s.name==="ref"?(u===null&&this.Error("Expected an parameter name after 'ref'"),l.identifier=u,l.isByReference=true):(l.isDivertTarget?l.identifier=u:l.identifier=s,l.identifier===null&&this.Error("Expected an parameter name"),l.isByReference=false),l},this.ExternalDeclaration=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null||s.name!="EXTERNAL")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"name of external function")||new ji.Identifier("");this.Whitespace();let u=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);u===null&&(u=[]);let l=u.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(en.filterUndef);return new Y1.ExternalDeclaration(o,l)},this._identifierCharSet=null,this.LogicLine=()=>{if(this.Whitespace(),this.ParseString("~")===null)return null;this.Whitespace();let s=()=>this.OneOf([this.ReturnStatement,this.TempDeclarationOrAssignment,this.Expression]),o=this.Expect(s,"expression after '~'",this.SkipToNextLine);if(o===null)return new Ke.ContentList;o instanceof Q1.Expression&&!(o instanceof Uo.FunctionCall||o instanceof Ho.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
44
44
  ~ return
45
45
  ~ var x = blah
46
46
  ~ x++
47
- ~ myFunction()`);let u=(0, tn.asOrNull)(o,Uo.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(Uo.FunctionCall)()!==null&&(o=new Ke.ContentList(o,new $t.Text(`
48
- `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof _r.NumberExpression||l instanceof qi.StringExpression||l instanceof $d.DivertTarget||l instanceof Vd.VariableReference||l instanceof Z0.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof qi.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Rd.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new ji.Identifier(o.name),new Rd.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new rF.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(l=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new iF.ListElementDefinition(u,s,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof _r.NumberExpression||u instanceof $d.DivertTarget||u instanceof qi.StringExpression?u instanceof qi.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new z1.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new Y1.Glue(new eF.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(u);let l=(0, tn.asOrNull)(u,Ke.ContentList);return l||(l=new Ke.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new Y0.Sequence(l,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let c=this.BeginRule(),h=this.ParseObject(l);if(h)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(c);else return this.SucceedRule(c,h);else this.FailRule(c);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new ji.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let u of s)if(!(u>="0"&&u<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new ye.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=ge.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new Y0.Sequence(u,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case ge.SequenceType.Once:case ge.SequenceType.Cycle:case ge.SequenceType.Stopping:case ge.SequenceType.Shuffle:case ge.SequenceType.Shuffle|ge.SequenceType.Stopping:case ge.SequenceType.Shuffle|ge.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),ge.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new ye.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=ge.SequenceType.Once;break;case "&":s|=ge.SequenceType.Cycle;break;case "~":s|=ge.SequenceType.Shuffle;break;case "$":s|=ge.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let u of s)o|=u;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=ge.SequenceType.Once;break;case "cycle":s=ge.SequenceType.Cycle;break;case "shuffle":s=ge.SequenceType.Shuffle;break;case "stopping":s=ge.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],u=false;for(let l of s)if(l==="|")u||o.push(new Ke.ContentList),u=false;else {let c=l;c===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):o.push(new Ke.ContentList(c)),u=true;}return u||o.push(new Ke.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel($e.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new $t.Text(`
49
- `)),new Ke.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===$e.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],u=this.OneOf(o);return s===$e.StatementLevel.Top&&u instanceof Q0.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],u=this.OneOf(o);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let s=Object.values($e.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let u=[],l=[];u.push(this.Line(this.MultiDivert)),o>=$e.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>$e.StatementLevel.InnerBlock&&u.push(this.Gather),o>=$e.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),o<=$e.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=$e.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=$e.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[o]=u,this._statementBreakRulesAtLevel[o]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
50
- \r`),this.ParseNewline(),kt.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new Ke.ContentList;o.AddContent(new vr.Tag(false)),o.AddContent(new vr.Tag(true)),s=o;}else s=new vr.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new ye.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?kt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?kt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?kt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?kt.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?kt.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=r,a===null?this._fileHandler=new lF.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=i;}PreProcessInputString(e){return new H1.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Go.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Go.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Go.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Go.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new ye.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof Ke.ContentList?e.AddContent(new vr.Tag(false)):e.push(new vr.Tag(false))),this.tagActive=false);}};Ko.InkParser=Q;Q.LatinBasic=dt.CharacterRange.Define("A","z",new ye.CharacterSet().AddRange("[","`"));Q.LatinExtendedA=dt.CharacterRange.Define("\u0100","\u017F");Q.LatinExtendedB=dt.CharacterRange.Define("\u0180","\u024F");Q.Greek=dt.CharacterRange.Define("\u0370","\u03FF",new ye.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));Q.Cyrillic=dt.CharacterRange.Define("\u0400","\u04FF",new ye.CharacterSet().AddRange("\u0482","\u0489"));Q.Armenian=dt.CharacterRange.Define("\u0530","\u058F",new ye.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));Q.Hebrew=dt.CharacterRange.Define("\u0590","\u05FF",new ye.CharacterSet);Q.Arabic=dt.CharacterRange.Define("\u0600","\u06FF",new ye.CharacterSet);Q.Korean=dt.CharacterRange.Define("\uAC00","\uD7AF",new ye.CharacterSet);Q.Latin1Supplement=dt.CharacterRange.Define("\x80","\xFF",new ye.CharacterSet);Q.Chinese=dt.CharacterRange.Define("\u4E00","\u9FFF",new ye.CharacterSet);Q.ListAllCharacterRanges=()=>[Q.LatinBasic,Q.LatinExtendedA,Q.LatinExtendedB,Q.Arabic,Q.Armenian,Q.Cyrillic,Q.Greek,Q.Hebrew,Q.Korean,Q.Latin1Supplement,Q.Chinese];});var ry=y(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.GenerateStoryStats=void 0;var cF=ar(),hF=cr(),dF=Ci(),fF=td(),pF=od(),mF=Zt();function gF(n){let e=n.FindAll(mF.Text)(),t=0;for(let u of e){let l=0,c=true;for(let h of u.text)h==" "||h==" "||h==`
51
- `||h=="\r"?c=true:c&&(l++,c=false);t+=l;}let r=n.FindAll(fF.Knot)(),i=n.FindAll(pF.Stitch)(),a=n.FindAll(cF.Choice)(),s=n.FindAll(dF.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(hF.Divert)();return {words:t,knots:r.length,functions:r.filter(u=>u.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}zo.GenerateStoryStats=gF;});var iy=y(Jo=>{Object.defineProperty(Jo,"__esModule",{value:true});Jo.JsonFileHandler=void 0;var jd=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};Jo.JsonFileHandler=jd;});var ay=y(xe=>{Object.defineProperty(xe,"__esModule",{value:true});xe.Compiler=xe.Story=xe.InkList=xe.JsonFileHandler=xe.StatementLevel=xe.InkParser=xe.CompilerOptions=void 0;var yF=Sc(),CF=pg(),Ld=ti(),vF=qd(),_F=ae(),EF=Z(),bF=ry(),SF=Sc();Object.defineProperty(xe,"CompilerOptions",{enumerable:true,get:function(){return SF.CompilerOptions}});var DF=qd();Object.defineProperty(xe,"InkParser",{enumerable:true,get:function(){return DF.InkParser}});var wF=sd();Object.defineProperty(xe,"StatementLevel",{enumerable:true,get:function(){return wF.StatementLevel}});var AF=iy();Object.defineProperty(xe,"JsonFileHandler",{enumerable:true,get:function(){return AF.JsonFileHandler}});var sy=Fi();Object.defineProperty(xe,"InkList",{enumerable:true,get:function(){return sy.InkList}});Object.defineProperty(xe,"Story",{enumerable:true,get:function(){return sy.Story}});var Bd=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new vF.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var r;for(let i of this.runtimeStory.state.outputStream){let a=(0, EF.asOrNull)(i,_F.StringValue);if(a!==null){let s=new CF.DebugSourceRange(((r=a.value)===null||r===void 0?void 0:r.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, bF.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=r=>{let i=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),r>=i&&r<i+s.length)return a;i+=s.length;}return null},this.OnError=(r,i)=>{switch(i){case Ld.ErrorType.Author:this._authorMessages.push(r);break;case Ld.ErrorType.Warning:this._warnings.push(r);break;case Ld.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new yF.CompilerOptions;}};xe.Compiler=Bd;});var Nn;(i=>(i.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),i.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),i.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),i.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(Nn||={});var by=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Sy=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,Dy=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,nu={Space_Separator:by,ID_Start:Sy,ID_Continue:Dy},ue={isSpaceSeparator(n){return typeof n=="string"&&nu.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||nu.ID_Start.test(n))},isIdContinueChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="$"||n==="_"||n==="\u200C"||n==="\u200D"||nu.ID_Continue.test(n))},isDigit(n){return typeof n=="string"&&/[0-9]/.test(n)},isHexDigit(n){return typeof n=="string"&&/[0-9A-Fa-f]/.test(n)}},iu,Ne,Pt,Mi,Vt,at,fe,ou,Sr,wy=function(e,t){iu=String(e),Ne="start",Pt=[],Mi=0,Vt=1,at=0,fe=void 0,ou=void 0,Sr=void 0;do fe=Ay(),Oy[Ne]();while(fe.type!=="eof");return typeof t=="function"?su({"":Sr},"",t):Sr};function su(n,e,t){let r=n[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let i=0;i<r.length;i++){let a=String(i),s=su(r,a,t);s===void 0?delete r[a]:Object.defineProperty(r,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in r){let a=su(r,i,t);a===void 0?delete r[i]:Object.defineProperty(r,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(n,e,r)}var R,T,br,At,W;function Ay(){for(R="default",T="",br=false,At=1;;){W=Ft();let n=Zd[R]();if(n)return n}}function Ft(){if(iu[Mi])return String.fromCodePoint(iu.codePointAt(Mi))}function D(){let n=Ft();return n===`
52
- `?(Vt++,at=0):n?at+=n.length:at++,n&&(Mi+=n.length),n}var Zd={default(){switch(W){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
- `:case "\r":case "\u2028":case "\u2029":D();return;case "/":D(),R="comment";return;case void 0:return D(),Y("eof")}if(ue.isSpaceSeparator(W)){D();return}return Zd[Ne]()},comment(){switch(W){case "*":D(),R="multiLineComment";return;case "/":D(),R="singleLineComment";return}throw ee(D())},multiLineComment(){switch(W){case "*":D(),R="multiLineCommentAsterisk";return;case void 0:throw ee(D())}D();},multiLineCommentAsterisk(){switch(W){case "*":D();return;case "/":D(),R="default";return;case void 0:throw ee(D())}D(),R="multiLineComment";},singleLineComment(){switch(W){case `
54
- `:case "\r":case "\u2028":case "\u2029":D(),R="default";return;case void 0:return D(),Y("eof")}D();},value(){switch(W){case "{":case "[":return Y("punctuator",D());case "n":return D(),nn("ull"),Y("null",null);case "t":return D(),nn("rue"),Y("boolean",true);case "f":return D(),nn("alse"),Y("boolean",false);case "-":case "+":D()==="-"&&(At=-1),R="sign";return;case ".":T=D(),R="decimalPointLeading";return;case "0":T=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":T=D(),R="decimalInteger";return;case "I":return D(),nn("nfinity"),Y("numeric",1/0);case "N":return D(),nn("aN"),Y("numeric",NaN);case '"':case "'":br=D()==='"',T="",R="string";return}throw ee(D())},identifierNameStartEscape(){if(W!=="u")throw ee(D());D();let n=au();switch(n){case "$":case "_":break;default:if(!ue.isIdStartChar(n))throw Jd();break}T+=n,R="identifierName";},identifierName(){switch(W){case "$":case "_":case "\u200C":case "\u200D":T+=D();return;case "\\":D(),R="identifierNameEscape";return}if(ue.isIdContinueChar(W)){T+=D();return}return Y("identifier",T)},identifierNameEscape(){if(W!=="u")throw ee(D());D();let n=au();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ue.isIdContinueChar(n))throw Jd();break}T+=n,R="identifierName";},sign(){switch(W){case ".":T=D(),R="decimalPointLeading";return;case "0":T=D(),R="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":T=D(),R="decimalInteger";return;case "I":return D(),nn("nfinity"),Y("numeric",At*(1/0));case "N":return D(),nn("aN"),Y("numeric",NaN)}throw ee(D())},zero(){switch(W){case ".":T+=D(),R="decimalPoint";return;case "e":case "E":T+=D(),R="decimalExponent";return;case "x":case "X":T+=D(),R="hexadecimal";return}return Y("numeric",At*0)},decimalInteger(){switch(W){case ".":T+=D(),R="decimalPoint";return;case "e":case "E":T+=D(),R="decimalExponent";return}if(ue.isDigit(W)){T+=D();return}return Y("numeric",At*Number(T))},decimalPointLeading(){if(ue.isDigit(W)){T+=D(),R="decimalFraction";return}throw ee(D())},decimalPoint(){switch(W){case "e":case "E":T+=D(),R="decimalExponent";return}if(ue.isDigit(W)){T+=D(),R="decimalFraction";return}return Y("numeric",At*Number(T))},decimalFraction(){switch(W){case "e":case "E":T+=D(),R="decimalExponent";return}if(ue.isDigit(W)){T+=D();return}return Y("numeric",At*Number(T))},decimalExponent(){switch(W){case "+":case "-":T+=D(),R="decimalExponentSign";return}if(ue.isDigit(W)){T+=D(),R="decimalExponentInteger";return}throw ee(D())},decimalExponentSign(){if(ue.isDigit(W)){T+=D(),R="decimalExponentInteger";return}throw ee(D())},decimalExponentInteger(){if(ue.isDigit(W)){T+=D();return}return Y("numeric",At*Number(T))},hexadecimal(){if(ue.isHexDigit(W)){T+=D(),R="hexadecimalInteger";return}throw ee(D())},hexadecimalInteger(){if(ue.isHexDigit(W)){T+=D();return}return Y("numeric",At*Number(T))},string(){switch(W){case "\\":D(),T+=Py();return;case '"':if(br)return D(),Y("string",T);T+=D();return;case "'":if(!br)return D(),Y("string",T);T+=D();return;case `
55
- `:case "\r":throw ee(D());case "\u2028":case "\u2029":xy(W);break;case void 0:throw ee(D())}T+=D();},start(){switch(W){case "{":case "[":return Y("punctuator",D())}R="value";},beforePropertyName(){switch(W){case "$":case "_":T=D(),R="identifierName";return;case "\\":D(),R="identifierNameStartEscape";return;case "}":return Y("punctuator",D());case '"':case "'":br=D()==='"',R="string";return}if(ue.isIdStartChar(W)){T+=D(),R="identifierName";return}throw ee(D())},afterPropertyName(){if(W===":")return Y("punctuator",D());throw ee(D())},beforePropertyValue(){R="value";},afterPropertyValue(){switch(W){case ",":case "}":return Y("punctuator",D())}throw ee(D())},beforeArrayValue(){if(W==="]")return Y("punctuator",D());R="value";},afterArrayValue(){switch(W){case ",":case "]":return Y("punctuator",D())}throw ee(D())},end(){throw ee(D())}};function Y(n,e){return {type:n,value:e,line:Vt,column:at}}function nn(n){for(let e of n){if(Ft()!==e)throw ee(D());D();}}function Py(){switch(Ft()){case "b":return D(),"\b";case "f":return D(),"\f";case "n":return D(),`
56
- `;case "r":return D(),"\r";case "t":return D()," ";case "v":return D(),"\v";case "0":if(D(),ue.isDigit(Ft()))throw ee(D());return "\0";case "x":return D(),Fy();case "u":return D(),au();case `
57
- `:case "\u2028":case "\u2029":return D(),"";case "\r":return D(),Ft()===`
58
- `&&D(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw ee(D());case void 0:throw ee(D())}return D()}function Fy(){let n="",e=Ft();if(!ue.isHexDigit(e)||(n+=D(),e=Ft(),!ue.isHexDigit(e)))throw ee(D());return n+=D(),String.fromCodePoint(parseInt(n,16))}function au(){let n="",e=4;for(;e-- >0;){let t=Ft();if(!ue.isHexDigit(t))throw ee(D());n+=D();}return String.fromCodePoint(parseInt(n,16))}var Oy={start(){if(fe.type==="eof")throw rn();ru();},beforePropertyName(){switch(fe.type){case "identifier":case "string":ou=fe.value,Ne="afterPropertyName";return;case "punctuator":Wi();return;case "eof":throw rn()}},afterPropertyName(){if(fe.type==="eof")throw rn();Ne="beforePropertyValue";},beforePropertyValue(){if(fe.type==="eof")throw rn();ru();},beforeArrayValue(){if(fe.type==="eof")throw rn();if(fe.type==="punctuator"&&fe.value==="]"){Wi();return}ru();},afterPropertyValue(){if(fe.type==="eof")throw rn();switch(fe.value){case ",":Ne="beforePropertyName";return;case "}":Wi();}},afterArrayValue(){if(fe.type==="eof")throw rn();switch(fe.value){case ",":Ne="beforeArrayValue";return;case "]":Wi();}},end(){}};function ru(){let n;switch(fe.type){case "punctuator":switch(fe.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=fe.value;break}if(Sr===void 0)Sr=n;else {let e=Pt[Pt.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,ou,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")Pt.push(n),Array.isArray(n)?Ne="beforeArrayValue":Ne="beforePropertyName";else {let e=Pt[Pt.length-1];e==null?Ne="end":Array.isArray(e)?Ne="afterArrayValue":Ne="afterPropertyValue";}}function Wi(){Pt.pop();let n=Pt[Pt.length-1];n==null?Ne="end":Array.isArray(n)?Ne="afterArrayValue":Ne="afterPropertyValue";}function ee(n){return Gi(n===void 0?`JSON5: invalid end of input at ${Vt}:${at}`:`JSON5: invalid character '${Xd(n)}' at ${Vt}:${at}`)}function rn(){return Gi(`JSON5: invalid end of input at ${Vt}:${at}`)}function Jd(){return at-=5,Gi(`JSON5: invalid identifier character at ${Vt}:${at}`)}function xy(n){console.warn(`JSON5: '${Xd(n)}' in strings is not valid ECMAScript; consider escaping`);}function Xd(n){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[n])return e[n];if(n<" "){let t=n.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return n}function Gi(n){let e=new SyntaxError(n);return e.lineNumber=Vt,e.columnNumber=at,e}var Ny=function(e,t,r){let i=[],a="",s,o,u="",l;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t.space,l=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let f of t){let v;typeof f=="string"?v=f:(typeof f=="number"||f instanceof String||f instanceof Number)&&(v=String(f)),v!==void 0&&s.indexOf(v)<0&&s.push(v);}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),c("",{"":e});function c(f,v){let _=v[f];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(f):typeof _.toJSON=="function"&&(_=_.toJSON(f))),o&&(_=o.call(v,f,_)),_ instanceof Number?_=Number(_):_ instanceof String?_=String(_):_ instanceof Boolean&&(_=_.valueOf()),_){case null:return "null";case true:return "true";case false:return "false"}if(typeof _=="string")return h(_);if(typeof _=="number")return String(_);if(typeof _=="object")return Array.isArray(_)?m(_):d(_)}function h(f){let v={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},b="";for(let g=0;g<f.length;g++){let C=f[g];switch(C){case "'":case '"':v[C]++,b+=C;continue;case "\0":if(ue.isDigit(f[g+1])){b+="\\x00";continue}}if(_[C]){b+=_[C];continue}if(C<" "){let S=C.charCodeAt(0).toString(16);b+="\\x"+("00"+S).substring(S.length);continue}b+=C;}let E=l||Object.keys(v).reduce((g,C)=>v[g]<v[C]?g:C);return b=b.replace(new RegExp(E,"g"),_[E]),E+b+E}function d(f){if(i.indexOf(f)>=0)throw TypeError("Converting circular structure to JSON5");i.push(f);let v=a;a=a+u;let _=s||Object.keys(f),b=[];for(let g of _){let C=c(g,f);if(C!==void 0){let S=p(g)+":";u!==""&&(S+=" "),S+=C,b.push(S);}}let E;if(b.length===0)E="{}";else {let g;if(u==="")g=b.join(","),E="{"+g+"}";else {let C=`,
59
- `+a;g=b.join(C),E=`{
60
- `+a+g+`,
61
- `+v+"}";}}return i.pop(),a=v,E}function p(f){if(f.length===0)return h(f);let v=String.fromCodePoint(f.codePointAt(0));if(!ue.isIdStartChar(v))return h(f);for(let _=v.length;_<f.length;_++)if(!ue.isIdContinueChar(String.fromCodePoint(f.codePointAt(_))))return h(f);return f}function m(f){if(i.indexOf(f)>=0)throw TypeError("Converting circular structure to JSON5");i.push(f);let v=a;a=a+u;let _=[];for(let E=0;E<f.length;E++){let g=c(String(E),f);_.push(g!==void 0?g:"null");}let b;if(_.length===0)b="[]";else if(u==="")b="["+_.join(",")+"]";else {let E=`,
62
- `+a,g=_.join(E);b=`[
63
- `+a+g+`,
64
- `+v+"]";}return i.pop(),a=v,b}},Ty={parse:wy,stringify:Ny},Iy=Ty,uu=Iy;var Yd="\xA7SPACE\xA7",ef="\xA7DOUBLE_QUOTES\xA7",tf="\xA7QUOTES\xA7",nf="SPECIAL_\xA7QUOTES\xA7",rf="\xA7CURLY_BRACKETS1\xA7",ky="\xA7INK_VAR\xA7",sf="\xA7CURLY_BRACKETS2\xA7",Ui;(E=>{let n=[],e=[];async function t(g,C){for(let S=0;S<n.length;S++)try{let{validation:w}=n[S].opts;if(w instanceof RegExp){if(!w.test(g.join(" ")))continue}else if(w instanceof zod.ZodType&&!w.safeParse(g).success)continue;let O=await n[S].fn(g,C,h);if(O===!0||typeof O=="string")return O}catch{}return false}function r(g,C={name:"custom-command",validation:/^/}){n.unshift({fn:g,opts:C});}E.add=r;function i(){return [...e.map(g=>g.opts),...n.map(g=>g.opts)]}E.info=i;function a(g,C){e.unshift({fn:g,opts:C});}E.addMapper=a;function s(){n.length=0;}E.clear=s;function o(){e.length=0;}E.clearMappers=o;async function u(g,C,S){try{let w=l(g),O=await t(w,S);return O===!0?void 0:typeof O=="string"?(O.startsWith("#")&&(O=O.substring(1)),await E.run(O,C,S)):c(w,C)}catch(w){throw Nn.error("Error parsing ink hashtag-command",g),w}}E.run=u;function l(g,C){if(g=g.replaceAll('\\"',ef),g=g.replaceAll("\\'",tf),g=g.replaceAll("\\`",nf),g=g.replaceAll("\\{",rf),g=g.replaceAll("\\}",sf),C?.mergeInkVariables){let A;do A=g,g=g.replace(/\{[^{}:]*\}/g,ky);while(g!==A)}g=g.replaceAll("{"," { "),g=g.replaceAll("}"," } "),g=g.replaceAll(rf,"{"),g=g.replaceAll(sf,"}");let S=[],w,O="";for(let A=0;A<g.length;A++){let $=g[A];$==='"'||$==="'"||$==="`"?w===void 0?(S.push(O),O="",w=$,O+=$):w===$?(w=void 0,O+=$,S.push(O),O=""):O+=$:O+=$;}return O!==""&&S.push(O),S.forEach((A,$)=>{$%2===1&&(S[$]=A.replaceAll(" ",Yd));}),g=S.join(""),S=g.split(" ").filter(A=>A!==""),S=S.map(A=>A.replaceAll(Yd," ").replaceAll(ef,'"').replaceAll(tf,"'").replaceAll(nf,"`")),S=f(S),S=S.flatMap(A=>b(A)),S=S.map(A=>A.startsWith('"')&&A.endsWith('"')||A.startsWith("'")&&A.endsWith("'")||A.startsWith("`")&&A.endsWith("`")?A.slice(1,-1):A),S}E.convertTagTolist=l;function c(g,C,S){for(let w of e){let{validation:O}=w.opts,A=false;if(O instanceof RegExp?A=O.test(g.join(" ")):O instanceof zod.ZodType&&(A=O.safeParse(g).success),A)return w.fn(g,C)}S?.silent||Nn.error("The operation is not valid",g);}E.convertOperation=c;function h(g){return d(g)}E.convertListStringToObj=h;function d(g){if(g.length===0)return {};if(g.length%2!==0)throw Nn.error("The props list must have a pair number of elements",g),new Error("The props list must have a pair number of elements");let C="{";g.forEach((S,w)=>{if(w%2===0)C+=`"${S}": `;else {switch(S){case "null":case "undefined":case "true":case "false":C+=`${S}`;break;default:m(S)?(S=p(S),C+=`"${S}"`):S.startsWith("{")&&S.endsWith("}")?C+=`${S}`:S.startsWith('"')&&S.endsWith('"')?C+=`${S}`:Number.isNaN(parseFloat(S))?C+=`"${S}"`:C+=`${S}`;}w<g.length-1&&(C+=", ");}}),C+="}";try{return uu.parse(C)}catch(S){throw Nn.error("Error parsing ink json",C),S}}function p(g){return g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")||g.startsWith("`")&&g.endsWith("`")?g.substring(1,g.length-1):g}function m(g){return !!(g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'")||g.startsWith("`")&&g.endsWith("`"))}function f(g){return v(g).tokens}E.mergeJsonBlocks=f;function v(g){let C=[],S=false;for(let w=0;w<g.length;w++){let O=g[w];if(O!=="{"){C.push(O);continue}let A=_(g,w);if(A===-1){C.push(O);continue}let $=v(g.slice(w+1,A)),Ee=["{",...$.tokens,"}"],Rt=Ee.join(" ");if(!$.hasInvalidMatchedBlock)try{uu.parse(Rt),C.push(Rt),w=A;continue}catch{}S=true,C.push(...Ee),w=A;}return {tokens:C,hasInvalidMatchedBlock:S}}function _(g,C){let S=0;for(let w=C;w<g.length;w++)if(g[w]==="{")S++;else if(g[w]==="}"&&(S--,S===0))return w;return -1}function b(g){if(g==="["||g==="]")return [g];let C=0,S=g.length,w=[];for(;C<S&&g[C]==="[";)w.push("["),C++;let O=[];for(;S>C&&g[S-1]==="]";)O.unshift("]"),S--;let A=g.slice(C,S);return A===""?[...w,...O]:[...w,A,...O]}})(Ui||={});var Ud=Bi(Vm()),hy=Bi(fg()),dy=Bi(ay()),fy=Bi(ti()),PF=/(?:^|<>)\s*#\s*([^\r\n]+)/g,FF=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,OF=new Set(["DONE","END"]),xF="_|_",oy=new Map;function py(n,e){let t=JSON.stringify([e,n]),r=oy.get(t);if(r)return r;let i=new RegExp(n,e);return oy.set(t,i),i}function Li(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>Li(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>Li(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Li(n,s));if(typeof t.const=="string")return n===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===n);if(t.type!=="string"||typeof t.minLength=="number"&&n.length<t.minLength||typeof t.maxLength=="number"&&n.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!py(t.pattern,"").test(n))return !1}catch{return false}return true}function Zo(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>Zo(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>Zo(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>Zo(n,o));if(t.type!=="array"||typeof t.minItems=="number"&&n.length<t.minItems||typeof t.maxItems=="number"&&n.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(n.length<s.length)return false;for(let o=0;o<s.length;o++)if(!Li(n[o],s[o]))return false;return n.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:n.slice(s.length).every(o=>Li(o,t.items))}function Wd(n,e){if(e.type==="regexp")try{let t=py(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:Zo(n,e.schema)}function Xo(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(Xo);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(Xo);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return Xo(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function uy(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-my(n,e)/t)}function NF(n,e){if(e&&typeof e=="object"){let t=e;if(typeof t.const=="string")return {weight:2,matched:n===void 0?0:2*uy(n,t.const)};if(Array.isArray(t.enum))return {weight:2,matched:2*(n===void 0?0:Math.max(0,...t.enum.filter(i=>typeof i=="string").map(i=>uy(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function TF(n,e){let t=Array.isArray(e.prefixItems)?e.prefixItems:[],r=Math.min(t.length,n.length),i=0,a=0,s=false;for(let o=0;o<r;o++){let u=NF(n[o],t[o]);i+=u.weight,a+=u.matched,u.weight>1&&(s=true);}return {score:i===0?0:a/i,hasDiscriminant:s}}var IF=.8,ly=new Map;function kF(n){let e=JSON.stringify(n),t=ly.get(e);if(t)return t;let r=new hy.default({strict:false,allErrors:true}).compile(n);return ly.set(e,r),r}function $F(n){if("items"in n)return n;let e=Array.isArray(n.prefixItems)?n.prefixItems.length:0;return {...n,minItems:e,maxItems:e,items:false}}function RF(n,e){let[t]=tu(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return Hd(n)}function VF(n){return n.keyword==="const"?`must be "${n.params.allowedValue}"`:n.keyword==="enum"?`must be one of ${(n.params.allowedValues??[]).map(t=>`"${t}"`).join(", ")}`:n.message??"invalid value"}function Md(n){let e=n.split(/\r?\n/),t=[];for(let r=0;r<e.length;r++){let i=e[r];for(let a of i.matchAll(PF)){let s=(a[1]??"").trim();if(!s)continue;let o=Ui.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function Hd(n){return n.keyword==="required"&&typeof n.params?.missingProperty=="string"?n.params.missingProperty:n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"?n.params.additionalProperty:n.instancePath.split("/").pop()||"(root)"}function my(n,e){let t=n.length+1,r=e.length+1,i=Array.from({length:t},(a,s)=>[s,...Array(r-1).fill(0)]);for(let a=1;a<r;a++)i[0][a]=a;for(let a=1;a<t;a++)for(let s=1;s<r;s++){let o=n[a-1]===e[s-1]?0:1;i[a][s]=Math.min(i[a-1][s]+1,i[a][s-1]+1,i[a-1][s-1]+o);}return i[t-1][r-1]}function qF(n,e){let t,r=1/0;for(let a of e){let s=my(n,a);s<r&&(r=s,t=a);}let i=Math.max(1,Math.floor(n.length/3));return r<=i?t:void 0}function jF(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&qF(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function tu(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function LF(n,e){let t=n,r,i=a=>{a&&typeof a=="object"&&typeof a.$origin=="string"&&(r=a.$origin);};i(t);for(let a of tu(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function BF(n,e){let t=tu(e);for(let r=t.length;r>=0;r--){let i=t.slice(0,r),a=n;for(let s of i){if(a===null||typeof a!="object"){a=void 0;break}a=a[s];}if(a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.type=="string")return {path:`/${i.map(o=>o.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`,node:a}}}function Yo(n,e,t=new Set){if(!n||typeof n!="object")return n;let r=n.$ref;if(typeof r!="string")return n;let i=r.match(/^#\/definitions\/([^/]+)$/);return !i?.[1]||t.has(i[1])||!(i[1]in e)?{}:(t.add(i[1]),Yo(e[i[1]],e,t))}function eu(n,e){let t=Yo(n,e);if(!t||typeof t!="object")return;let r=t;if(!(r.anyOf||r.oneOf)){if(Array.isArray(r.allOf)){let i={properties:{},required:[]};for(let a of r.allOf){let s=eu(a,e);if(!s)return;Object.assign(i.properties,s.properties),i.required.push(...s.required);}return i}return {properties:r.properties??{},required:r.required??[]}}}function cy(n,e){if(!n||typeof n!="object")return true;let t=n;return "const"in t?t.const===e:Array.isArray(t.enum)?t.enum.includes(e):true}function WF(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=eu(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&cy(o,e.type)&&cy(s.properties.operationType,e.operationType)&&r.push(i);}return r}function MF(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new Ud.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function GF(n,e,t){let r=n.definitions??{},i=Yo(r[e],r);for(let a of tu(t)){let o=eu(i,r)?.properties[a];if(o===void 0)return [];i=Yo(o,r);}return Object.keys(eu(i,r)?.properties??{})}function Qo(n){let e=n.map(o=>o.instancePath),t=o=>e.some(u=>u!==o&&u.startsWith(`${o}/`)),r=n.filter(o=>!t(o.instancePath)),i=new Map;for(let o of r){let u=i.get(o.instancePath)??[];u.push(o),i.set(o.instancePath,u);}let a=[];for(let o of i.values()){let u=o.filter(l=>l.keyword!=="anyOf"&&l.keyword!=="oneOf");a.push(...u.length>0?u:o);}let s=new Set;return a.filter(o=>{let u=`${Hd(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function Gd(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:Hd(r),message:jF(r,t?.(r)),origin:LF(e,r.instancePath)}))}function UF(n,e,t){let r=n.map(c=>c.instancePath),i=c=>r.some(h=>h!==c&&h.startsWith(`${c}/`)),a=n.filter(c=>!i(c.instancePath)),s=t&&typeof t=="object"?t:void 0,o=new Map,u=[];for(let c of a){let h=s?BF(e,c.instancePath):void 0;if(!h){u.push(c);continue}let d=o.get(h.path);d?d.errors.push(c):o.set(h.path,{node:h.node,errors:[c]});}let l=Gd(Qo(u),e);for(let[c,h]of o){let d=s?WF(s,h.node):[],p=d.length===1?d[0]:void 0;if(!p||!s){l.push(...Gd(Qo(h.errors),e));continue}let f=Qo(MF(s,p,h.node)).map(v=>({...v,instancePath:`${c}${v.instancePath}`}));l.push(...Gd(f,e,v=>GF(s,p,v.instancePath.slice(c.length))));}return l}exports.InkCompiler=void 0;(h=>{function n(d,p={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let m=[];try{return {json:new dy.Compiler(d,{errorHandler:(b,E)=>{let g=b.replace(/^[A-Z]+: line \d+: ?/,""),C=b.match(/line (\d+)/);m.push({message:g,type:E,line:C?Number(C[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:b=>b,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:m}}catch{let v=false,_={...p,textSource:d};return e(m,()=>{v=true;},_),v?n(_.textSource,p):{issues:m}}}h.compile=n;function e(d,p,m){let{functions:f,initialVarsToRemove:v,labelToRemove:_}=m,b=d.find(E=>E.type===fy.ErrorType.Error);if(b){if(b.message.includes("Divert target not found")){let E=b.message.match(/Divert target not found: '-> (\w+)'/);if(E?.[1]){let g=E[1],C=`
47
+ ~ myFunction()`);let u=(0, en.asOrNull)(o,Uo.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(Uo.FunctionCall)()!==null&&(o=new Ke.ContentList(o,new $t.Text(`
48
+ `))),this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o},this.VariableDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="VAR")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"variable name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let l=this.Expect(this.Expression,"initial value for ");return l?(l instanceof vr.NumberExpression||l instanceof qi.StringExpression||l instanceof Vd.DivertTarget||l instanceof jd.VariableReference||l instanceof X0.List||this.Error("initial value for a variable must be a number, constant, list or divert target"),this.Parse(this.ListElementDefinitionSeparator)!==null?this.Error("Unexpected ','. If you're trying to declare a new list, use the LIST keyword, not VAR"):l instanceof qi.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new qd.VariableAssignment({assignedExpression:l,isGlobalDeclaration:true,variableIdentifier:o})):null},this.ListDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!="LIST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"list name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of the list definition"),this.Whitespace();let u=this.Expect(this.ListDefinition,"list item names");return u?(u.identifier=new ji.Identifier(o.name),new qd.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new sF.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let u=this.Parse(this.IdentifierWithMetadata);if(u===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let l=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(l=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new aF.ListElementDefinition(u,s,l)},this.ConstDeclaration=()=>{if(this.Whitespace(),this.Parse(this.Identifier)!=="CONST")return null;this.Whitespace();let o=this.Expect(this.IdentifierWithMetadata,"constant name");this.Whitespace(),this.Expect(this.String("="),"the '=' for an assignment of a value, e.g. '= 5' (initial values are mandatory)"),this.Whitespace();let u=this.Expect(this.Expression,"initial value for ");return u instanceof vr.NumberExpression||u instanceof Vd.DivertTarget||u instanceof qi.StringExpression?u instanceof qi.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new Z1.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new tF.Glue(new nF.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let u=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(u===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(u);let l=(0, en.asOrNull)(u,Ke.ContentList);return l||(l=new Ke.ContentList(u)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(l),l},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let l=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return l===null?null:new ey.Sequence(l,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let u=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let l of u){let c=this.BeginRule(),h=this.ParseObject(l);if(h)if(this.Peek(this.Spaced(this.String("}")))===null)this.FailRule(c);else return this.SucceedRule(c,h);else this.FailRule(c);}return null},this.InnerExpression=()=>{let s=this.Parse(this.Expression);return s&&(s.outputWhenComplete=true),s},this.IdentifierWithMetadata=()=>{let s=this.Identifier();return s===null?null:new ji.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let u of s)if(!(u>="0"&&u<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new ye.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=ge.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let u=this.Parse(this.InnerSequenceObjects);return u===null||u.length<=1?null:new ey.Sequence(u,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case ge.SequenceType.Once:case ge.SequenceType.Cycle:case ge.SequenceType.Stopping:case ge.SequenceType.Shuffle:case ge.SequenceType.Shuffle|ge.SequenceType.Stopping:case ge.SequenceType.Shuffle|ge.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),ge.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new ye.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=ge.SequenceType.Once;break;case "&":s|=ge.SequenceType.Cycle;break;case "~":s|=ge.SequenceType.Shuffle;break;case "$":s|=ge.SequenceType.Stopping;break}return s===0?null:s},this.SequenceTypeWordAnnotation=()=>{let s=this.Interleave(this.SequenceTypeSingleWord,this.Exclude(this.Whitespace));if(s===null||s.length===0||this.ParseString(":")===null)return null;let o=0;for(let u of s)o|=u;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=ge.SequenceType.Once;break;case "cycle":s=ge.SequenceType.Cycle;break;case "shuffle":s=ge.SequenceType.Shuffle;break;case "stopping":s=ge.SequenceType.Stopping;break}return s===null?null:s},this.InnerSequenceObjects=()=>{let s=this.Parse(this.Newline)!==null,o=null;return s?o=this.Parse(this.InnerMultilineSequenceObjects):o=this.Parse(this.InnerInlineSequenceObjects),o},this.InnerInlineSequenceObjects=()=>{let s=this.Interleave(this.Optional(this.MixedTextAndLogic),this.String("|"),null,false);if(s===null)return null;let o=[],u=false;for(let l of s)if(l==="|")u||o.push(new Ke.ContentList),u=false;else {let c=l;c===null?this.Error(`Expected content, but got ${l} (this is an ink compiler bug!)`):o.push(new Ke.ContentList(c)),u=true;}return u||o.push(new Ke.ContentList),o},this.InnerMultilineSequenceObjects=()=>{this.MultilineWhitespace();let s=this.OneOrMore(this.SingleMultilineSequenceElement);return s===null?null:s},this.SingleMultilineSequenceElement=()=>{if(this.Whitespace(),this.ParseString("->")!==null||this.ParseString("-")===null)return null;this.Whitespace();let s=this.StatementsAtLevel($e.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new $t.Text(`
49
+ `)),new Ke.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===$e.StatementLevel.InnerBlock&&this.Parse(this.GatherDashes)!==null&&this.Error("You can't use a gather (the dashes) within the { curly braces } context. For multi-line sequences and conditions, you should only use one dash."),this.Interleave(this.Optional(this.MultilineWhitespace),()=>this.StatementAtLevel(s),()=>this.StatementsBreakForLevel(s))),this.StatementAtLevel=s=>{let o=this._statementRulesAtLevel[s],u=this.OneOf(o);return s===$e.StatementLevel.Top&&u instanceof Y0.ReturnType&&this.Error("should not have return statement outside of a knot"),u},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],u=this.OneOf(o);return u===null?null:u},this.GenerateStatementLevelRules=()=>{let s=Object.values($e.StatementLevel);this._statementRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]),this._statementBreakRulesAtLevel="f".repeat(s.length).split("f").map(()=>[]);for(let o of s){let u=[],l=[];u.push(this.Line(this.MultiDivert)),o>=$e.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>$e.StatementLevel.InnerBlock&&u.push(this.Gather),o>=$e.StatementLevel.Knot&&u.push(this.StitchDefinition),u.push(this.Line(this.ListDeclaration)),u.push(this.Line(this.VariableDeclaration)),u.push(this.Line(this.ConstDeclaration)),u.push(this.Line(this.ExternalDeclaration)),u.push(this.Line(this.IncludeStatement)),u.push(this.LogicLine),u.push(this.LineOfMixedTextAndLogic),o<=$e.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=$e.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=$e.StatementLevel.InnerBlock&&(l.push(this.ParseDashNotArrow),l.push(this.String("}"))),this._statementRulesAtLevel[o]=u,this._statementBreakRulesAtLevel[o]=l;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
50
+ \r`),this.ParseNewline(),kt.ParseSuccess),this.Line=s=>()=>{let o=this.ParseObject(s);return o===null?null:(this.Expect(this.EndOfLine,"end of line",this.SkipToNextLine),o)},this.StartTag=()=>{if(this.Whitespace(),this.ParseString("#")===null)return null;this.parsingStringExpression&&this.Error("Tags aren't allowed inside of strings. Please use \\# if you want a hash symbol.");let s=null;if(this.tagActive){let o=new Ke.ContentList;o.AddContent(new Cr.Tag(false)),o.AddContent(new Cr.Tag(true)),s=o;}else s=new Cr.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new ye.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?kt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?kt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?kt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?kt.ParseSuccess:null,this.Spaced=s=>()=>{this.Whitespace();let o=this.ParseObject(s);return o===null?null:(this.Whitespace(),o)},this.AnyWhitespace=()=>{let s=false;for(;this.OneOf([this.Whitespace,this.MultilineWhitespace])!==null;)s=true;return s?kt.ParseSuccess:null},this.MultiSpaced=s=>()=>{this.AnyWhitespace();let o=this.ParseObject(s);return o===null?null:(this.AnyWhitespace(),o)},this._filename=null,this._externalErrorHandler=null,this._fileHandler=null,this._filename=t,this.RegisterExpressionOperators(),this.GenerateStatementLevelRules(),this.errorHandler=this.OnStringParserError,this._externalErrorHandler=r,a===null?this._fileHandler=new hF.DefaultFileHandler:this._fileHandler=a,i===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=i;}PreProcessInputString(e){return new z1.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(Go.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(Go.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(Go.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(Go.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new ye.CharacterSet).AddRange("A","Z").AddRange("a","z").AddRange("0","9").Add("_"),this.ExtendIdentifierCharacterRanges(this._identifierCharSet)),this._identifierCharSet}EndTagIfNecessary(e){this.tagActive&&(e!=null&&(e instanceof Ke.ContentList?e.AddContent(new Cr.Tag(false)):e.push(new Cr.Tag(false))),this.tagActive=false);}};Ko.InkParser=Q;Q.LatinBasic=dt.CharacterRange.Define("A","z",new ye.CharacterSet().AddRange("[","`"));Q.LatinExtendedA=dt.CharacterRange.Define("\u0100","\u017F");Q.LatinExtendedB=dt.CharacterRange.Define("\u0180","\u024F");Q.Greek=dt.CharacterRange.Define("\u0370","\u03FF",new ye.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));Q.Cyrillic=dt.CharacterRange.Define("\u0400","\u04FF",new ye.CharacterSet().AddRange("\u0482","\u0489"));Q.Armenian=dt.CharacterRange.Define("\u0530","\u058F",new ye.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));Q.Hebrew=dt.CharacterRange.Define("\u0590","\u05FF",new ye.CharacterSet);Q.Arabic=dt.CharacterRange.Define("\u0600","\u06FF",new ye.CharacterSet);Q.Korean=dt.CharacterRange.Define("\uAC00","\uD7AF",new ye.CharacterSet);Q.Latin1Supplement=dt.CharacterRange.Define("\x80","\xFF",new ye.CharacterSet);Q.Chinese=dt.CharacterRange.Define("\u4E00","\u9FFF",new ye.CharacterSet);Q.ListAllCharacterRanges=()=>[Q.LatinBasic,Q.LatinExtendedA,Q.LatinExtendedB,Q.Arabic,Q.Armenian,Q.Cyrillic,Q.Greek,Q.Hebrew,Q.Korean,Q.Latin1Supplement,Q.Chinese];});var iy=C(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.GenerateStoryStats=void 0;var dF=sr(),fF=lr(),pF=Ci(),mF=rd(),gF=ld(),yF=Jt();function CF(n){let e=n.FindAll(yF.Text)(),t=0;for(let u of e){let l=0,c=true;for(let h of u.text)h==" "||h==" "||h==`
51
+ `||h=="\r"?c=true:c&&(l++,c=false);t+=l;}let r=n.FindAll(mF.Knot)(),i=n.FindAll(gF.Stitch)(),a=n.FindAll(dF.Choice)(),s=n.FindAll(pF.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(fF.Divert)();return {words:t,knots:r.length,functions:r.filter(u=>u.isFunction).length,stitches:i.length,gathers:s.length,diverts:o.length-1,choices:a.length}}zo.GenerateStoryStats=CF;});var sy=C(Jo=>{Object.defineProperty(Jo,"__esModule",{value:true});Jo.JsonFileHandler=void 0;var Bd=class{constructor(e){this.fileHierarchy=e,this.ResolveInkFilename=t=>{if(Object.keys(this.fileHierarchy).includes(t))return t;throw new Error(`Cannot locate ${t}. Are you trying a relative import ? This is not yet implemented.`)},this.LoadInkFileContents=t=>{if(Object.keys(this.fileHierarchy).includes(t))return this.fileHierarchy[t];throw new Error(`Cannot open ${t}.`)};}};Jo.JsonFileHandler=Bd;});var oy=C(xe=>{Object.defineProperty(xe,"__esModule",{value:true});xe.Compiler=xe.Story=xe.InkList=xe.JsonFileHandler=xe.StatementLevel=xe.InkParser=xe.CompilerOptions=void 0;var vF=wc(),_F=mg(),Wd=ti(),EF=Ld(),bF=ae(),SF=J(),DF=iy(),wF=wc();Object.defineProperty(xe,"CompilerOptions",{enumerable:true,get:function(){return wF.CompilerOptions}});var AF=Ld();Object.defineProperty(xe,"InkParser",{enumerable:true,get:function(){return AF.InkParser}});var PF=od();Object.defineProperty(xe,"StatementLevel",{enumerable:true,get:function(){return PF.StatementLevel}});var FF=sy();Object.defineProperty(xe,"JsonFileHandler",{enumerable:true,get:function(){return FF.JsonFileHandler}});var ay=Fi();Object.defineProperty(xe,"InkList",{enumerable:true,get:function(){return ay.InkList}});Object.defineProperty(xe,"Story",{enumerable:true,get:function(){return ay.Story}});var Md=class{get errors(){return this._errors}get warnings(){return this._warnings}get authorMessages(){return this._authorMessages}get inputString(){return this._inputString}get options(){return this._options}get parsedStory(){if(!this._parsedStory)throw new Error;return this._parsedStory}get runtimeStory(){if(!this._runtimeStory)throw new Error("Compilation failed.");return this._runtimeStory}get parser(){if(!this._parser)throw new Error;return this._parser}get debugSourceRanges(){return this._debugSourceRanges}constructor(e,t=null){this._errors=[],this._warnings=[],this._authorMessages=[],this._parsedStory=null,this._runtimeStory=null,this._parser=null,this._debugSourceRanges=[],this.Compile=()=>(this._parser=new EF.InkParser(this.inputString,this.options.sourceFilename||null,this.OnError,null,this.options.fileHandler),this._parsedStory=this.parser.ParseStory(),this.errors.length===0?(this.parsedStory.countAllVisits=this.options.countAllVisits,this._runtimeStory=this.parsedStory.ExportRuntime(this.OnError)):this._runtimeStory=null,this.runtimeStory),this.RetrieveDebugSourceForLatestContent=()=>{var r;for(let i of this.runtimeStory.state.outputStream){let a=(0, SF.asOrNull)(i,bF.StringValue);if(a!==null){let s=new _F.DebugSourceRange(((r=a.value)===null||r===void 0?void 0:r.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, DF.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=r=>{let i=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),r>=i&&r<i+s.length)return a;i+=s.length;}return null},this.OnError=(r,i)=>{switch(i){case Wd.ErrorType.Author:this._authorMessages.push(r);break;case Wd.ErrorType.Warning:this._warnings.push(r);break;case Wd.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new vF.CompilerOptions;}};xe.Compiler=Md;});var xn;(i=>(i.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),i.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),i.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),i.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(xn||={});var Sy=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Dy=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,wy=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/,nu={Space_Separator:Sy,ID_Start:Dy,ID_Continue:wy},ue={isSpaceSeparator(n){return typeof n=="string"&&nu.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||nu.ID_Start.test(n))},isIdContinueChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||n==="$"||n==="_"||n==="\u200C"||n==="\u200D"||nu.ID_Continue.test(n))},isDigit(n){return typeof n=="string"&&/[0-9]/.test(n)},isHexDigit(n){return typeof n=="string"&&/[0-9A-Fa-f]/.test(n)}},iu,Ne,Pt,Mi,Rt,at,fe,ou,Sr,Ay=function(e,t){iu=String(e),Ne="start",Pt=[],Mi=0,Rt=1,at=0,fe=void 0,ou=void 0,Sr=void 0;do fe=Py(),xy[Ne]();while(fe.type!=="eof");return typeof t=="function"?su({"":Sr},"",t):Sr};function su(n,e,t){let r=n[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let i=0;i<r.length;i++){let a=String(i),s=su(r,a,t);s===void 0?delete r[a]:Object.defineProperty(r,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let i in r){let a=su(r,i,t);a===void 0?delete r[i]:Object.defineProperty(r,i,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(n,e,r)}var k,N,br,At,B;function Py(){for(k="default",N="",br=false,At=1;;){B=Ft();let n=Qd[k]();if(n)return n}}function Ft(){if(iu[Mi])return String.fromCodePoint(iu.codePointAt(Mi))}function S(){let n=Ft();return n===`
52
+ `?(Rt++,at=0):n?at+=n.length:at++,n&&(Mi+=n.length),n}var Qd={default(){switch(B){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
+ `:case "\r":case "\u2028":case "\u2029":S();return;case "/":S(),k="comment";return;case void 0:return S(),Y("eof")}if(ue.isSpaceSeparator(B)){S();return}return Qd[Ne]()},comment(){switch(B){case "*":S(),k="multiLineComment";return;case "/":S(),k="singleLineComment";return}throw ee(S())},multiLineComment(){switch(B){case "*":S(),k="multiLineCommentAsterisk";return;case void 0:throw ee(S())}S();},multiLineCommentAsterisk(){switch(B){case "*":S();return;case "/":S(),k="default";return;case void 0:throw ee(S())}S(),k="multiLineComment";},singleLineComment(){switch(B){case `
54
+ `:case "\r":case "\u2028":case "\u2029":S(),k="default";return;case void 0:return S(),Y("eof")}S();},value(){switch(B){case "{":case "[":return Y("punctuator",S());case "n":return S(),tn("ull"),Y("null",null);case "t":return S(),tn("rue"),Y("boolean",true);case "f":return S(),tn("alse"),Y("boolean",false);case "-":case "+":S()==="-"&&(At=-1),k="sign";return;case ".":N=S(),k="decimalPointLeading";return;case "0":N=S(),k="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":N=S(),k="decimalInteger";return;case "I":return S(),tn("nfinity"),Y("numeric",1/0);case "N":return S(),tn("aN"),Y("numeric",NaN);case '"':case "'":br=S()==='"',N="",k="string";return}throw ee(S())},identifierNameStartEscape(){if(B!=="u")throw ee(S());S();let n=au();switch(n){case "$":case "_":break;default:if(!ue.isIdStartChar(n))throw Xd();break}N+=n,k="identifierName";},identifierName(){switch(B){case "$":case "_":case "\u200C":case "\u200D":N+=S();return;case "\\":S(),k="identifierNameEscape";return}if(ue.isIdContinueChar(B)){N+=S();return}return Y("identifier",N)},identifierNameEscape(){if(B!=="u")throw ee(S());S();let n=au();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ue.isIdContinueChar(n))throw Xd();break}N+=n,k="identifierName";},sign(){switch(B){case ".":N=S(),k="decimalPointLeading";return;case "0":N=S(),k="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":N=S(),k="decimalInteger";return;case "I":return S(),tn("nfinity"),Y("numeric",At*(1/0));case "N":return S(),tn("aN"),Y("numeric",NaN)}throw ee(S())},zero(){switch(B){case ".":N+=S(),k="decimalPoint";return;case "e":case "E":N+=S(),k="decimalExponent";return;case "x":case "X":N+=S(),k="hexadecimal";return}return Y("numeric",At*0)},decimalInteger(){switch(B){case ".":N+=S(),k="decimalPoint";return;case "e":case "E":N+=S(),k="decimalExponent";return}if(ue.isDigit(B)){N+=S();return}return Y("numeric",At*Number(N))},decimalPointLeading(){if(ue.isDigit(B)){N+=S(),k="decimalFraction";return}throw ee(S())},decimalPoint(){switch(B){case "e":case "E":N+=S(),k="decimalExponent";return}if(ue.isDigit(B)){N+=S(),k="decimalFraction";return}return Y("numeric",At*Number(N))},decimalFraction(){switch(B){case "e":case "E":N+=S(),k="decimalExponent";return}if(ue.isDigit(B)){N+=S();return}return Y("numeric",At*Number(N))},decimalExponent(){switch(B){case "+":case "-":N+=S(),k="decimalExponentSign";return}if(ue.isDigit(B)){N+=S(),k="decimalExponentInteger";return}throw ee(S())},decimalExponentSign(){if(ue.isDigit(B)){N+=S(),k="decimalExponentInteger";return}throw ee(S())},decimalExponentInteger(){if(ue.isDigit(B)){N+=S();return}return Y("numeric",At*Number(N))},hexadecimal(){if(ue.isHexDigit(B)){N+=S(),k="hexadecimalInteger";return}throw ee(S())},hexadecimalInteger(){if(ue.isHexDigit(B)){N+=S();return}return Y("numeric",At*Number(N))},string(){switch(B){case "\\":S(),N+=Fy();return;case '"':if(br)return S(),Y("string",N);N+=S();return;case "'":if(!br)return S(),Y("string",N);N+=S();return;case `
55
+ `:case "\r":throw ee(S());case "\u2028":case "\u2029":Ny(B);break;case void 0:throw ee(S())}N+=S();},start(){switch(B){case "{":case "[":return Y("punctuator",S())}k="value";},beforePropertyName(){switch(B){case "$":case "_":N=S(),k="identifierName";return;case "\\":S(),k="identifierNameStartEscape";return;case "}":return Y("punctuator",S());case '"':case "'":br=S()==='"',k="string";return}if(ue.isIdStartChar(B)){N+=S(),k="identifierName";return}throw ee(S())},afterPropertyName(){if(B===":")return Y("punctuator",S());throw ee(S())},beforePropertyValue(){k="value";},afterPropertyValue(){switch(B){case ",":case "}":return Y("punctuator",S())}throw ee(S())},beforeArrayValue(){if(B==="]")return Y("punctuator",S());k="value";},afterArrayValue(){switch(B){case ",":case "]":return Y("punctuator",S())}throw ee(S())},end(){throw ee(S())}};function Y(n,e){return {type:n,value:e,line:Rt,column:at}}function tn(n){for(let e of n){if(Ft()!==e)throw ee(S());S();}}function Fy(){switch(Ft()){case "b":return S(),"\b";case "f":return S(),"\f";case "n":return S(),`
56
+ `;case "r":return S(),"\r";case "t":return S()," ";case "v":return S(),"\v";case "0":if(S(),ue.isDigit(Ft()))throw ee(S());return "\0";case "x":return S(),Oy();case "u":return S(),au();case `
57
+ `:case "\u2028":case "\u2029":return S(),"";case "\r":return S(),Ft()===`
58
+ `&&S(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw ee(S());case void 0:throw ee(S())}return S()}function Oy(){let n="",e=Ft();if(!ue.isHexDigit(e)||(n+=S(),e=Ft(),!ue.isHexDigit(e)))throw ee(S());return n+=S(),String.fromCodePoint(parseInt(n,16))}function au(){let n="",e=4;for(;e-- >0;){let t=Ft();if(!ue.isHexDigit(t))throw ee(S());n+=S();}return String.fromCodePoint(parseInt(n,16))}var xy={start(){if(fe.type==="eof")throw nn();ru();},beforePropertyName(){switch(fe.type){case "identifier":case "string":ou=fe.value,Ne="afterPropertyName";return;case "punctuator":Wi();return;case "eof":throw nn()}},afterPropertyName(){if(fe.type==="eof")throw nn();Ne="beforePropertyValue";},beforePropertyValue(){if(fe.type==="eof")throw nn();ru();},beforeArrayValue(){if(fe.type==="eof")throw nn();if(fe.type==="punctuator"&&fe.value==="]"){Wi();return}ru();},afterPropertyValue(){if(fe.type==="eof")throw nn();switch(fe.value){case ",":Ne="beforePropertyName";return;case "}":Wi();}},afterArrayValue(){if(fe.type==="eof")throw nn();switch(fe.value){case ",":Ne="beforeArrayValue";return;case "]":Wi();}},end(){}};function ru(){let n;switch(fe.type){case "punctuator":switch(fe.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=fe.value;break}if(Sr===void 0)Sr=n;else {let e=Pt[Pt.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,ou,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")Pt.push(n),Array.isArray(n)?Ne="beforeArrayValue":Ne="beforePropertyName";else {let e=Pt[Pt.length-1];e==null?Ne="end":Array.isArray(e)?Ne="afterArrayValue":Ne="afterPropertyValue";}}function Wi(){Pt.pop();let n=Pt[Pt.length-1];n==null?Ne="end":Array.isArray(n)?Ne="afterArrayValue":Ne="afterPropertyValue";}function ee(n){return Gi(n===void 0?`JSON5: invalid end of input at ${Rt}:${at}`:`JSON5: invalid character '${Yd(n)}' at ${Rt}:${at}`)}function nn(){return Gi(`JSON5: invalid end of input at ${Rt}:${at}`)}function Xd(){return at-=5,Gi(`JSON5: invalid identifier character at ${Rt}:${at}`)}function Ny(n){console.warn(`JSON5: '${Yd(n)}' in strings is not valid ECMAScript; consider escaping`);}function Yd(n){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[n])return e[n];if(n<" "){let t=n.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return n}function Gi(n){let e=new SyntaxError(n);return e.lineNumber=Rt,e.columnNumber=at,e}var Ty=function(e,t,r){let i=[],a="",s,o,u="",l;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(r=t.space,l=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let p of t){let v;typeof p=="string"?v=p:(typeof p=="number"||p instanceof String||p instanceof Number)&&(v=String(p)),v!==void 0&&s.indexOf(v)<0&&s.push(v);}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),c("",{"":e});function c(p,v){let _=v[p];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(p):typeof _.toJSON=="function"&&(_=_.toJSON(p))),o&&(_=o.call(v,p,_)),_ instanceof Number?_=Number(_):_ instanceof String?_=String(_):_ instanceof Boolean&&(_=_.valueOf()),_){case null:return "null";case true:return "true";case false:return "false"}if(typeof _=="string")return h(_);if(typeof _=="number")return String(_);if(typeof _=="object")return Array.isArray(_)?g(_):f(_)}function h(p){let v={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},b="";for(let E=0;E<p.length;E++){let y=p[E];switch(y){case "'":case '"':v[y]++,b+=y;continue;case "\0":if(ue.isDigit(p[E+1])){b+="\\x00";continue}}if(_[y]){b+=_[y];continue}if(y<" "){let D=y.charCodeAt(0).toString(16);b+="\\x"+("00"+D).substring(D.length);continue}b+=y;}let d=l||Object.keys(v).reduce((E,y)=>v[E]<v[y]?E:y);return b=b.replace(new RegExp(d,"g"),_[d]),d+b+d}function f(p){if(i.indexOf(p)>=0)throw TypeError("Converting circular structure to JSON5");i.push(p);let v=a;a=a+u;let _=s||Object.keys(p),b=[];for(let E of _){let y=c(E,p);if(y!==void 0){let D=m(E)+":";u!==""&&(D+=" "),D+=y,b.push(D);}}let d;if(b.length===0)d="{}";else {let E;if(u==="")E=b.join(","),d="{"+E+"}";else {let y=`,
59
+ `+a;E=b.join(y),d=`{
60
+ `+a+E+`,
61
+ `+v+"}";}}return i.pop(),a=v,d}function m(p){if(p.length===0)return h(p);let v=String.fromCodePoint(p.codePointAt(0));if(!ue.isIdStartChar(v))return h(p);for(let _=v.length;_<p.length;_++)if(!ue.isIdContinueChar(String.fromCodePoint(p.codePointAt(_))))return h(p);return p}function g(p){if(i.indexOf(p)>=0)throw TypeError("Converting circular structure to JSON5");i.push(p);let v=a;a=a+u;let _=[];for(let d=0;d<p.length;d++){let E=c(String(d),p);_.push(E!==void 0?E:"null");}let b;if(_.length===0)b="[]";else if(u==="")b="["+_.join(",")+"]";else {let d=`,
62
+ `+a,E=_.join(d);b=`[
63
+ `+a+E+`,
64
+ `+v+"]";}return i.pop(),a=v,b}},Iy={parse:Ay,stringify:Ty},ky=Iy,uu=ky;var tf="\xA7SPACE\xA7",nf="\xA7DOUBLE_QUOTES\xA7",rf="\xA7QUOTES\xA7",sf="SPECIAL_\xA7QUOTES\xA7",af="\xA7CURLY_BRACKETS1\xA7",$y="\xA7INK_VAR\xA7",of="\xA7CURLY_BRACKETS2\xA7",Ui;(b=>{let n=[],e=[];async function t(d,E){for(let y=0;y<n.length;y++)try{let{validation:D}=n[y].opts;if(D instanceof RegExp){if(!D.test(d.join(" ")))continue}else if(D instanceof zod.ZodType&&!D.safeParse(d).success)continue;let w=await n[y].fn(d,E,h);if(w===!0||typeof w=="string")return w}catch{}return false}function r(d,E={name:"custom-command",validation:/^/}){n.unshift({fn:d,opts:E});}b.add=r;function i(){return [...e.map(d=>d.opts),...n.map(d=>d.opts)]}b.info=i;function a(d,E){e.unshift({fn:d,opts:E});}b.addMapper=a;function s(){n.length=0;}b.clear=s;function o(){e.length=0;}b.clearMappers=o;async function u(d,E,y){try{let D=l(d),w=await t(D,y);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await b.run(w,E,y)):c(D,E)}catch(D){throw xn.error("Error parsing ink hashtag-command",d),D}}b.run=u;function l(d,E){if(d=d.replaceAll('\\"',nf),d=d.replaceAll("\\'",rf),d=d.replaceAll("\\`",sf),d=d.replaceAll("\\{",af),d=d.replaceAll("\\}",of),E?.mergeInkVariables){let F;do F=d,d=d.replace(/\{[^{}:]*\}/g,$y);while(d!==F)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(af,"{"),d=d.replaceAll(of,"}");let y=[],D,w="";for(let F=0;F<d.length;F++){let $=d[F];$==='"'||$==="'"||$==="`"?D===void 0?(y.push(w),w="",D=$,w+=$):D===$?(D=void 0,w+=$,y.push(w),w=""):w+=$:w+=$;}return w!==""&&y.push(w),y.forEach((F,$)=>{$%2===1&&(y[$]=F.replaceAll(" ",tf));}),d=y.join(""),y=d.split(" ").filter(F=>F!==""),y=y.map(F=>F.replaceAll(tf," ").replaceAll(nf,'"').replaceAll(rf,"'").replaceAll(sf,"`")),y=g(y),y=y.flatMap(F=>_(F)),y=y.map(F=>F.startsWith('"')&&F.endsWith('"')||F.startsWith("'")&&F.endsWith("'")||F.startsWith("`")&&F.endsWith("`")?F.slice(1,-1):F),y}b.convertTagTolist=l;function c(d,E,y){for(let D of e){let{validation:w}=D.opts,F=false;if(w instanceof RegExp?F=w.test(d.join(" ")):w instanceof zod.ZodType&&(F=w.safeParse(d).success),F)return D.fn(d,E)}y?.silent||xn.error("The operation is not valid",d);}b.convertOperation=c;function h(d){if(d.length===0)return {};if(d.length%2!==0)throw xn.error("The props list must have a pair number of elements",d),new Error("The props list must have a pair number of elements");let E="{";d.forEach((y,D)=>{if(D%2===0)E+=`"${y}": `;else {switch(y){case "null":case "undefined":case "true":case "false":E+=`${y}`;break;default:m(y)?(y=f(y),E+=`"${y}"`):y.startsWith("{")&&y.endsWith("}")?E+=`${y}`:y.startsWith('"')&&y.endsWith('"')?E+=`${y}`:Number.isNaN(parseFloat(y))?E+=`"${y}"`:E+=`${y}`;}D<d.length-1&&(E+=", ");}}),E+="}";try{return uu.parse(E)}catch(y){throw xn.error("Error parsing ink json",E),y}}b.convertListStringToObj=h;function f(d){return d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`")?d.substring(1,d.length-1):d}function m(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function g(d){return p(d).tokens}b.mergeJsonBlocks=g;function p(d){let E=[],y=false;for(let D=0;D<d.length;D++){let w=d[D];if(w!=="{"){E.push(w);continue}let F=v(d,D);if(F===-1){E.push(w);continue}let $=p(d.slice(D+1,F)),X=["{",...$.tokens,"}"],Ee=X.join(" ");if(!$.hasInvalidMatchedBlock)try{uu.parse(Ee),E.push(Ee),D=F;continue}catch{}y=true,E.push(...X),D=F;}return {tokens:E,hasInvalidMatchedBlock:y}}function v(d,E){let y=0;for(let D=E;D<d.length;D++)if(d[D]==="{")y++;else if(d[D]==="}"&&(y--,y===0))return D;return -1}function _(d){if(d==="["||d==="]")return [d];let E=0,y=d.length,D=[];for(;E<y&&d[E]==="[";)D.push("["),E++;let w=[];for(;y>E&&d[y-1]==="]";)w.unshift("]"),y--;let F=d.slice(E,y);return F===""?[...D,...w]:[...D,F,...w]}})(Ui||={});var Kd=Bi(qm()),dy=Bi(pg()),fy=Bi(oy()),py=Bi(ti()),OF=/(?:^|<>)\s*#\s*([^\r\n]+)/g,xF=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,NF=new Set(["DONE","END"]),TF="_|_",uy=new Map;function my(n,e){let t=JSON.stringify([e,n]),r=uy.get(t);if(r)return r;let i=new RegExp(n,e);return uy.set(t,i),i}function Li(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>Li(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>Li(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Li(n,s));if(typeof t.const=="string")return n===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===n);if(t.type!=="string"||typeof t.minLength=="number"&&n.length<t.minLength||typeof t.maxLength=="number"&&n.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!my(t.pattern,"").test(n))return !1}catch{return false}return true}function Zo(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>Zo(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>Zo(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>Zo(n,o));if(t.type!=="array"||typeof t.minItems=="number"&&n.length<t.minItems||typeof t.maxItems=="number"&&n.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(n.length<s.length)return false;for(let o=0;o<s.length;o++)if(!Li(n[o],s[o]))return false;return n.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:n.slice(s.length).every(o=>Li(o,t.items))}function Gd(n,e){if(e.type==="regexp")try{let t=my(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:Zo(n,e.schema)}function Xo(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(Xo);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(Xo);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return Xo(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function ly(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-gy(n,e)/t)}function IF(n,e){if(e&&typeof e=="object"){let t=e;if(typeof t.const=="string")return {weight:2,matched:n===void 0?0:2*ly(n,t.const)};if(Array.isArray(t.enum))return {weight:2,matched:2*(n===void 0?0:Math.max(0,...t.enum.filter(i=>typeof i=="string").map(i=>ly(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function kF(n,e){let t=Array.isArray(e.prefixItems)?e.prefixItems:[],r=Math.min(t.length,n.length),i=0,a=0,s=false;for(let o=0;o<r;o++){let u=IF(n[o],t[o]);i+=u.weight,a+=u.matched,u.weight>1&&(s=true);}return {score:i===0?0:a/i,hasDiscriminant:s}}var $F=.8,cy=new Map;function RF(n){let e=JSON.stringify(n),t=cy.get(e);if(t)return t;let r=new dy.default({strict:false,allErrors:true}).compile(n);return cy.set(e,r),r}function VF(n){if("items"in n)return n;let e=Array.isArray(n.prefixItems)?n.prefixItems.length:0;return {...n,minItems:e,maxItems:e,items:false}}function qF(n,e){let[t]=tu(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return zd(n)}function jF(n){return n.keyword==="const"?`must be "${n.params.allowedValue}"`:n.keyword==="enum"?`must be one of ${(n.params.allowedValues??[]).map(t=>`"${t}"`).join(", ")}`:n.message??"invalid value"}function Ud(n){let e=n.split(/\r?\n/),t=[];for(let r=0;r<e.length;r++){let i=e[r];for(let a of i.matchAll(OF)){let s=(a[1]??"").trim();if(!s)continue;let o=Ui.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function zd(n){return n.keyword==="required"&&typeof n.params?.missingProperty=="string"?n.params.missingProperty:n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"?n.params.additionalProperty:n.instancePath.split("/").pop()||"(root)"}function gy(n,e){let t=n.length+1,r=e.length+1,i=Array.from({length:t},(a,s)=>[s,...Array(r-1).fill(0)]);for(let a=1;a<r;a++)i[0][a]=a;for(let a=1;a<t;a++)for(let s=1;s<r;s++){let o=n[a-1]===e[s-1]?0:1;i[a][s]=Math.min(i[a-1][s]+1,i[a][s-1]+1,i[a-1][s-1]+o);}return i[t-1][r-1]}function LF(n,e){let t,r=1/0;for(let a of e){let s=gy(n,a);s<r&&(r=s,t=a);}let i=Math.max(1,Math.floor(n.length/3));return r<=i?t:void 0}function BF(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&LF(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function tu(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function WF(n,e){let t=n,r,i=a=>{a&&typeof a=="object"&&typeof a.$origin=="string"&&(r=a.$origin);};i(t);for(let a of tu(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function MF(n,e){let t=tu(e);for(let r=t.length;r>=0;r--){let i=t.slice(0,r),a=n;for(let s of i){if(a===null||typeof a!="object"){a=void 0;break}a=a[s];}if(a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.type=="string")return {path:`/${i.map(o=>o.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`,node:a}}}function Yo(n,e,t=new Set){if(!n||typeof n!="object")return n;let r=n.$ref;if(typeof r!="string")return n;let i=r.match(/^#\/definitions\/([^/]+)$/);return !i?.[1]||t.has(i[1])||!(i[1]in e)?{}:(t.add(i[1]),Yo(e[i[1]],e,t))}function eu(n,e){let t=Yo(n,e);if(!t||typeof t!="object")return;let r=t;if(!(r.anyOf||r.oneOf)){if(Array.isArray(r.allOf)){let i={properties:{},required:[]};for(let a of r.allOf){let s=eu(a,e);if(!s)return;Object.assign(i.properties,s.properties),i.required.push(...s.required);}return i}return {properties:r.properties??{},required:r.required??[]}}}function hy(n,e){if(!n||typeof n!="object")return true;let t=n;return "const"in t?t.const===e:Array.isArray(t.enum)?t.enum.includes(e):true}function GF(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=eu(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&hy(o,e.type)&&hy(s.properties.operationType,e.operationType)&&r.push(i);}return r}function UF(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new Kd.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function HF(n,e,t){let r=n.definitions??{},i=Yo(r[e],r);for(let a of tu(t)){let o=eu(i,r)?.properties[a];if(o===void 0)return [];i=Yo(o,r);}return Object.keys(eu(i,r)?.properties??{})}function Qo(n){let e=n.map(o=>o.instancePath),t=o=>e.some(u=>u!==o&&u.startsWith(`${o}/`)),r=n.filter(o=>!t(o.instancePath)),i=new Map;for(let o of r){let u=i.get(o.instancePath)??[];u.push(o),i.set(o.instancePath,u);}let a=[];for(let o of i.values()){let u=o.filter(l=>l.keyword!=="anyOf"&&l.keyword!=="oneOf");a.push(...u.length>0?u:o);}let s=new Set;return a.filter(o=>{let u=`${zd(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function Hd(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:zd(r),message:BF(r,t?.(r)),origin:WF(e,r.instancePath)}))}function KF(n,e,t){let r=n.map(c=>c.instancePath),i=c=>r.some(h=>h!==c&&h.startsWith(`${c}/`)),a=n.filter(c=>!i(c.instancePath)),s=t&&typeof t=="object"?t:void 0,o=new Map,u=[];for(let c of a){let h=s?MF(e,c.instancePath):void 0;if(!h){u.push(c);continue}let f=o.get(h.path);f?f.errors.push(c):o.set(h.path,{node:h.node,errors:[c]});}let l=Hd(Qo(u),e);for(let[c,h]of o){let f=s?GF(s,h.node):[],m=f.length===1?f[0]:void 0;if(!m||!s){l.push(...Hd(Qo(h.errors),e));continue}let p=Qo(UF(s,m,h.node)).map(v=>({...v,instancePath:`${c}${v.instancePath}`}));l.push(...Hd(p,e,v=>HF(s,m,v.instancePath.slice(c.length))));}return l}exports.InkCompiler=void 0;(h=>{function n(f,m={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let g=[];try{return {json:new fy.Compiler(f,{errorHandler:(b,d)=>{let E=b.replace(/^[A-Z]+: line \d+: ?/,""),y=b.match(/line (\d+)/);g.push({message:E,type:d,line:y?Number(y[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:b=>b,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:g}}catch{let v=false,_={...m,textSource:f};return e(g,()=>{v=true;},_),v?n(_.textSource,m):{issues:g}}}h.compile=n;function e(f,m,g){let{functions:p,initialVarsToRemove:v,labelToRemove:_}=g,b=f.find(d=>d.type===py.ErrorType.Error);if(b){if(b.message.includes("Divert target not found")){let d=b.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let E=d[1],y=`
65
65
 
66
- === ${g} ===
66
+ === ${E} ===
67
67
 
68
- -> DONE`;return m.textSource=m.textSource.concat(C),_.push(g),p()}}if(b.message.includes("Unresolved variable")){let E=b.message.match(/Unresolved variable: (\w+)/);if(E?.[1]){let g=E[1],C=`VAR ${g} = ""
68
+ -> DONE`;return g.textSource=g.textSource.concat(y),_.push(E),m()}}if(b.message.includes("Unresolved variable")){let d=b.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let E=d[1],y=`VAR ${E} = ""
69
69
 
70
- `;return m.textSource=C.concat(m.textSource),v.push(g),p()}}if(b.message.includes("Variable could not be found to assign to")){let E=b.message.match(/Variable could not be found to assign to: (\w+)/);if(E?.[1]){let g=E[1],C=`VAR ${g} = ""
70
+ `;return g.textSource=y.concat(g.textSource),v.push(E),m()}}if(b.message.includes("Variable could not be found to assign to")){let d=b.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let E=d[1],y=`VAR ${E} = ""
71
71
 
72
- `;return m.textSource=C.concat(m.textSource),v.push(g),p()}}if(b.message.includes("Variable could not be found to assign to")){let E=b.message.match(/Variable could not be found to assign to: '(\w+)'/);if(E?.[1]){let g=E[1],C=`VAR ${g} = ""
72
+ `;return g.textSource=y.concat(g.textSource),v.push(E),m()}}if(b.message.includes("Variable could not be found to assign to")){let d=b.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let E=d[1],y=`VAR ${E} = ""
73
73
 
74
- `;return m.textSource=C.concat(m.textSource),v.push(g),p()}}if(b.message.includes("Function call target not found")){let E=b.message.match(/Function call target not found: '-> (\w+)'/);if(E?.[1]){let g=E[1],C=`
74
+ `;return g.textSource=y.concat(g.textSource),v.push(E),m()}}if(b.message.includes("Function call target not found")){let d=b.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let E=d[1],y=`
75
75
 
76
- === function ${g}() ===
76
+ === function ${E}() ===
77
77
 
78
78
  ~ return
79
79
 
80
- `;return m.textSource=m.textSource.concat(C),f.push({name:g,args:0}),_.push(g),p()}}if(b.message.includes(" arguments, but got ")){let E=b.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(E?.[1]){let g=E[1],C=parseInt(E[3]||"0",10),S=C>0?Array.from({length:C},(A,$)=>`arg${$+1}`).join(", "):"",w=`
80
+ `;return g.textSource=g.textSource.concat(y),p.push({name:E,args:0}),_.push(E),m()}}if(b.message.includes(" arguments, but got ")){let d=b.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let E=d[1],y=parseInt(d[3]||"0",10),D=y>0?Array.from({length:y},($,X)=>`arg${X+1}`).join(", "):"",w=`
81
81
 
82
- === function ${g}(${S}) ===
82
+ === function ${E}(${D}) ===
83
83
 
84
84
  ~ return
85
85
 
86
- `;m.textSource=m.textSource.replaceAll(`
86
+ `;g.textSource=g.textSource.replaceAll(`
87
87
 
88
- === function ${g}() ===
88
+ === function ${E}() ===
89
89
 
90
90
  ~ return
91
91
 
92
- `,""),m.textSource=m.textSource.concat(w);let O=f.find(A=>A.name===g);return O?O.args=C:(f.push({name:g,args:C}),_.push(g)),p()}}if(b.message.includes("Could not find target for read count")){let E=b.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(E?.[1]){let g=E[1],[C,S]=g.split("."),w=`
92
+ `,""),g.textSource=g.textSource.concat(w);let F=p.find($=>$.name===E);return F?F.args=y:(p.push({name:E,args:y}),_.push(E)),m()}}if(b.message.includes("Could not find target for read count")){let d=b.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let E=d[1],[y,D]=E.split("."),w=`
93
93
 
94
- LIST ${C} = ${S}
94
+ LIST ${y} = ${D}
95
95
 
96
- `;return m.textSource=m.textSource.concat(w),m.initialVarsToRemove.push(C),m.initialVarsToRemove.push(`${C}.${S}`),p()}}if(b.message.includes("variable for increment could not be found")){let E=b.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(E?.[1]){let g=E[1],C=`VAR ${g} = 0
96
+ `;return g.textSource=g.textSource.concat(w),g.initialVarsToRemove.push(y),g.initialVarsToRemove.push(`${y}.${D}`),m()}}if(b.message.includes("variable for increment could not be found")){let d=b.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let E=d[1],y=`VAR ${E} = 0
97
97
 
98
- `;return m.textSource=C.concat(m.textSource),m.initialVarsToRemove.push(g),p()}}return d.forEach(E=>{let g=E.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);g?.[1]&&(E.message=`The function '${g[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:d}}return {issues:d}}h.getErrors=e;function t(d,p){return Md(d).filter(({tokens:m})=>!p.some(({validation:f})=>Wd(m,f)))}h.getUnknownHashtagCommands=t;function r(d,p){let m=p.filter(v=>v.validation.type==="zod");if(m.length===0)return [];let f=[];for(let v of Md(d)){if(p.some(({validation:E})=>Wd(v.tokens,E)))continue;let _;for(let E of m)for(let g of Xo(E.validation.schema)){let{score:C,hasDiscriminant:S}=TF(v.tokens,g);S&&(!_||C>_.score)&&(_={command:E,branch:g,score:C});}if(!_||_.score<IF)continue;let b=kF($F(_.branch));if(!b(v.tokens))for(let E of Qo(b.errors??[]))f.push({line:v.line,command:v.command,handlerName:_.command.name,instancePath:E.instancePath||"(root)",element:RF(E,v.tokens),message:VF(E),score:_.score});}return f}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(d,p){let m=new Set;for(let E of d.matchAll(FF))E[1]&&m.add(E[1]);let f=new Set(p),v=new Set,_=d.split(/\r?\n/),b=[];for(let E=0;E<_.length;E++){let g=(_[E]??"").replace(/\/\/.*$/,"");for(let C of g.matchAll(/->[ \t]+(\w[\w.]*)/g)){let S=C[1];if(!S)continue;let w=S.split(".")[0]??S;OF.has(w)||m.has(w)||f.has(S)||f.has(S.replaceAll(".",xF))||f.has(w)||v.has(S)||(v.add(S),b.push({line:E+1,target:S}));}}return b}h.getUnknownDivertTargets=i;function a(d){return new Ud.default({strict:false,allErrors:true}).compile(d)}h.getSchemaValidator=a;function s(d,p){let m=typeof p=="function"?p:a(p);return m(d)?[]:UF(m.errors??[],d,m.schema)}h.validateAgainstJsonSchema=s;function o(d,p){let m=new Set,f=[];for(let E of p){let g=u(E);g!==void 0?f.push(g):m.add(String(E));}f.sort((E,g)=>g-E);let v=[],_=d.length;for(let E=d.length-1;E>=0;E--)m.has(d[E])&&(v.push({key:d[E],sectionTokens:d.slice(E+1,_)}),_=E);v.reverse();let b=[];for(let E of f)E<0||E>=_||(b.push({key:E,sectionTokens:d.slice(E,_)}),_=E-1);return b.reverse(),[...b,...v]}h.extractKeyedSections=o;function u(d){return typeof d=="number"?Number.isInteger(d)&&d>=0?d:void 0:/^\d+$/.test(d)?Number(d):void 0}function l(d,p){let m=o(d,Object.keys(p)),f=[];for(let{key:v,sectionTokens:_}of m){let b;try{b=Ui.convertListStringToObj(_);}catch(g){f.push({key:v,instancePath:"(root)",element:String(v),message:`could not parse "${v}" section into key/value pairs: ${g instanceof Error?g.message:String(g)}`});continue}let E=s(b,p[v]);f.push(...E.map(g=>({...g,key:v})));}return f}h.validateKeyedJsonSchemas=l;function c(d,p){let m=[];for(let f of Md(d)){let v=p.find(({validation:b})=>Wd(f.tokens,b));if(!v?.keySchemas)continue;let _=l(f.tokens,v.keySchemas);m.push(..._.map(b=>({...b,line:f.line,command:f.command})));}return m}h.getHashtagKeySchemaIssues=c;})(exports.InkCompiler||={});
98
+ `;return g.textSource=y.concat(g.textSource),g.initialVarsToRemove.push(E),m()}}return f.forEach(d=>{let E=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);E?.[1]&&(d.message=`The function '${E[1]}' have optional arguments, but in ink all arguments must be required. Please make sure to provide all the required arguments for the function call.`);}),{issues:f}}return {issues:f}}h.getErrors=e;function t(f,m){return Ud(f).filter(({tokens:g})=>!m.some(({validation:p})=>Gd(g,p)))}h.getUnknownHashtagCommands=t;function r(f,m){let g=m.filter(v=>v.validation.type==="zod");if(g.length===0)return [];let p=[];for(let v of Ud(f)){if(m.some(({validation:d})=>Gd(v.tokens,d)))continue;let _;for(let d of g)for(let E of Xo(d.validation.schema)){let{score:y,hasDiscriminant:D}=kF(v.tokens,E);D&&(!_||y>_.score)&&(_={command:d,branch:E,score:y});}if(!_||_.score<$F)continue;let b=RF(VF(_.branch));if(!b(v.tokens))for(let d of Qo(b.errors??[]))p.push({line:v.line,command:v.command,handlerName:_.command.name,instancePath:d.instancePath||"(root)",element:qF(d,v.tokens),message:jF(d),score:_.score});}return p}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(f,m){let g=new Set;for(let d of f.matchAll(xF))d[1]&&g.add(d[1]);let p=new Set(m),v=new Set,_=f.split(/\r?\n/),b=[];for(let d=0;d<_.length;d++){let E=(_[d]??"").replace(/\/\/.*$/,"");for(let y of E.matchAll(/->[ \t]+(\w[\w.]*)/g)){let D=y[1];if(!D)continue;let w=D.split(".")[0]??D;NF.has(w)||g.has(w)||p.has(D)||p.has(D.replaceAll(".",TF))||p.has(w)||v.has(D)||(v.add(D),b.push({line:d+1,target:D}));}}return b}h.getUnknownDivertTargets=i;function a(f){return new Kd.default({strict:false,allErrors:true}).compile(f)}h.getSchemaValidator=a;function s(f,m){let g=typeof m=="function"?m:a(m);return g(f)?[]:KF(g.errors??[],f,g.schema)}h.validateAgainstJsonSchema=s;function o(f,m){let g=new Set,p=[];for(let d of m){let E=u(d);E!==void 0?p.push(E):g.add(String(d));}p.sort((d,E)=>E-d);let v=[],_=f.length;for(let d=f.length-1;d>=0;d--)g.has(f[d])&&(v.push({key:f[d],sectionTokens:f.slice(d+1,_)}),_=d);v.reverse();let b=[];for(let d of p)d<0||d>=_||(b.push({key:d,sectionTokens:f.slice(d,_)}),_=d-1);return b.reverse(),[...b,...v]}h.extractKeyedSections=o;function u(f){return typeof f=="number"?Number.isInteger(f)&&f>=0?f:void 0:/^\d+$/.test(f)?Number(f):void 0}function l(f,m){let g=o(f,Object.keys(m)),p=[];for(let{key:v,sectionTokens:_}of g){let b;try{b=Ui.convertListStringToObj(_);}catch(E){p.push({key:v,instancePath:"(root)",element:String(v),message:`could not parse "${v}" section into key/value pairs: ${E instanceof Error?E.message:String(E)}`});continue}let d=s(b,m[v]);p.push(...d.map(E=>({...E,key:v})));}return p}h.validateKeyedJsonSchemas=l;function c(f,m){let g=[];for(let p of Ud(f)){let v=m.find(({validation:b})=>Gd(p.tokens,b));if(!v?.keySchemas)continue;let _=l(p.tokens,v.keySchemas);g.push(..._.map(b=>({...b,line:p.line,command:p.command})));}return g}h.getHashtagKeySchemaIssues=c;})(exports.InkCompiler||={});