@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/vite.cjs CHANGED
@@ -1,107 +1,107 @@
1
- 'use strict';var zod=require('zod'),characters=require('@drincs/pixi-vn/characters'),pixiVn=require('@drincs/pixi-vn');require('@drincs/pixi-vn/canvas');var narration=require('@drincs/pixi-vn/narration');require('@drincs/pixi-vn/sound');var storage=require('@drincs/pixi-vn/storage'),hn=require('fs/promises'),ce=require('path'),JF=require('fs'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var hn__default=/*#__PURE__*/_interopDefault(hn);var ce__default=/*#__PURE__*/_interopDefault(ce);var JF__namespace=/*#__PURE__*/_interopNamespace(JF);var Rb=Object.create;var Xp=Object.defineProperty;var $b=Object.getOwnPropertyDescriptor;var Vb=Object.getOwnPropertyNames;var jb=Object.getPrototypeOf,Lb=Object.prototype.hasOwnProperty;var Un=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var w=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qb=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Vb(e))!Lb.call(n,i)&&i!==t&&Xp(n,i,{get:()=>e[i],enumerable:!(r=$b(e,i))||r.enumerable});return n};var wn=(n,e,t)=>(t=n!=null?Rb(jb(n)):{},qb(Xp(t,"default",{value:n,enumerable:true}),n));var Ni=w(ie=>{Object.defineProperty(ie,"__esModule",{value:true});ie.regexpCode=ie.getEsmExportName=ie.getProperty=ie.safeStringify=ie.stringify=ie.strConcat=ie.addCodeArg=ie.str=ie._=ie.nil=ie._Code=ie.Name=ie.IDENTIFIER=ie._CodeOrName=void 0;var Oi=class{};ie._CodeOrName=Oi;ie.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zn=class extends Oi{constructor(e){if(super(),!ie.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}}};ie.Name=Zn;var Dt=class extends Oi{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 Zn&&(t[r.str]=(t[r.str]||0)+1),t),{})}};ie._Code=Dt;ie.nil=new Dt("");function mm(n,...e){let t=[n[0]],r=0;for(;r<e.length;)Ml(t,e[r]),t.push(n[++r]);return new Dt(t)}ie._=mm;var Bl=new Dt("+");function gm(n,...e){let t=[Ti(n[0])],r=0;for(;r<e.length;)t.push(Bl),Ml(t,e[r]),t.push(Bl,Ti(n[++r]));return s_(t),new Dt(t)}ie.str=gm;function Ml(n,e){e instanceof Dt?n.push(...e._items):e instanceof Zn?n.push(e):n.push(u_(e));}ie.addCodeArg=Ml;function s_(n){let e=1;for(;e<n.length-1;){if(n[e]===Bl){let t=a_(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function a_(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof Zn||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 Zn))return `"${n}${e.slice(1)}`}function o_(n,e){return e.emptyStr()?n:n.emptyStr()?e:gm`${n}${e}`}ie.strConcat=o_;function u_(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:Ti(Array.isArray(n)?n.join(","):n)}function l_(n){return new Dt(Ti(n))}ie.stringify=l_;function Ti(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ie.safeStringify=Ti;function c_(n){return typeof n=="string"&&ie.IDENTIFIER.test(n)?new Dt(`.${n}`):mm`[${n}]`}ie.getProperty=c_;function h_(n){if(typeof n=="string"&&ie.IDENTIFIER.test(n))return new Dt(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}ie.getEsmExportName=h_;function d_(n){return new Dt(n.toString())}ie.regexpCode=d_;});var Hl=w(ct=>{Object.defineProperty(ct,"__esModule",{value:true});ct.ValueScope=ct.ValueScopeName=ct.Scope=ct.varKinds=ct.UsedValueState=void 0;var lt=Ni(),Wl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},oa;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(oa||(ct.UsedValueState=oa={}));ct.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var ua=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.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}}};ct.Scope=ua;var la=class extends lt.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, lt._)`.${new lt.Name(t)}[${r}]`;}};ct.ValueScopeName=la;var f_=(0, lt._)`\n`,Gl=class extends ua{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?f_:lt.nil};}get(){return this._scope}name(e){return new la(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, lt._)`${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=lt.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,oa.Started);let c=t(l);if(c){let h=this.opts.es5?ct.varKinds.var:ct.varKinds.const;a=(0, lt._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, lt._)`${a}${c}${this.opts._n}`;else throw new Wl(l);u.set(l,oa.Completed);});}return a}};ct.ValueScope=Gl;});var M=w(U=>{Object.defineProperty(U,"__esModule",{value:true});U.or=U.and=U.not=U.CodeGen=U.operators=U.varKinds=U.ValueScopeName=U.ValueScope=U.Scope=U.Name=U.regexpCode=U.stringify=U.getProperty=U.nil=U.strConcat=U.str=U._=void 0;var te=Ni(),Lt=Hl(),Pn=Ni();Object.defineProperty(U,"_",{enumerable:true,get:function(){return Pn._}});Object.defineProperty(U,"str",{enumerable:true,get:function(){return Pn.str}});Object.defineProperty(U,"strConcat",{enumerable:true,get:function(){return Pn.strConcat}});Object.defineProperty(U,"nil",{enumerable:true,get:function(){return Pn.nil}});Object.defineProperty(U,"getProperty",{enumerable:true,get:function(){return Pn.getProperty}});Object.defineProperty(U,"stringify",{enumerable:true,get:function(){return Pn.stringify}});Object.defineProperty(U,"regexpCode",{enumerable:true,get:function(){return Pn.regexpCode}});Object.defineProperty(U,"Name",{enumerable:true,get:function(){return Pn.Name}});var fa=Hl();Object.defineProperty(U,"Scope",{enumerable:true,get:function(){return fa.Scope}});Object.defineProperty(U,"ValueScope",{enumerable:true,get:function(){return fa.ValueScope}});Object.defineProperty(U,"ValueScopeName",{enumerable:true,get:function(){return fa.ValueScopeName}});Object.defineProperty(U,"varKinds",{enumerable:true,get:function(){return fa.varKinds}});U.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var gn=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Jl=class extends gn{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?Lt.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=Ir(this.rhs,e,t)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},ca=class extends gn{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 te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ir(this.rhs,e,t),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return da(e,this.rhs)}},zl=class extends ca{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},Ul=class extends gn{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},Kl=class extends gn{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},Xl=class extends gn{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},Yl=class extends gn{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=Ir(this.code,e,t),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Fi=class extends gn{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)||(p_(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>nr(e,t.names),{})}},yn=class extends Fi{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},Ql=class extends Fi{},Fr=class extends yn{};Fr.kind="else";var er=class n extends yn{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 Fr(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(ym(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=Ir(this.condition,e,t),this}get names(){let e=super.names;return da(e,this.condition),this.else&&nr(e,this.else.names),e}};er.kind="if";var tr=class extends yn{};tr.kind="for";var Zl=class extends tr{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=Ir(this.iteration,e,t),this}get names(){return nr(super.names,this.iteration.names)}},ec=class extends tr{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?Lt.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=da(super.names,this.from);return da(e,this.to)}},ha=class extends tr{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=Ir(this.iterable,e,t),this}get names(){return nr(super.names,this.iterable.names)}},Ii=class extends yn{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)}};Ii.kind="func";var ki=class extends Fi{render(e){return "return "+super.render(e)}};ki.kind="return";var tc=class extends yn{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&&nr(e,this.catch.names),this.finally&&nr(e,this.finally.names),e}},Ri=class extends yn{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};Ri.kind="catch";var $i=class extends yn{render(e){return "finally"+super.render(e)}};$i.kind="finally";var nc=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
- `:""},this._extScope=e,this._scope=new Lt.Scope({parent:e}),this._nodes=[new Ql];}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 Jl(e,a,r)),a}const(e,t,r){return this._def(Lt.varKinds.const,e,t,r)}let(e,t,r){return this._def(Lt.varKinds.let,e,t,r)}var(e,t,r){return this._def(Lt.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new ca(e,t,r))}add(e,t){return this._leafNode(new zl(e,U.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Yl(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, te.addCodeArg)(t,i));return t.push("}"),new te._Code(t)}if(e,t,r){if(this._blockNode(new er(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 er(e))}else(){return this._elseNode(new Fr)}endIf(){return this._endBlockNode(er,Fr)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Zl(e),t)}forRange(e,t,r,i,a=this.opts.es5?Lt.varKinds.var:Lt.varKinds.let){let s=this._scope.toName(e);return this._for(new ec(a,s,t,r),()=>i(s))}forOf(e,t,r,i=Lt.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof te.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, te._)`${s}.length`,o=>{this.var(a,(0, te._)`${s}[${o}]`),r(a);})}return this._for(new ha("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?Lt.varKinds.var:Lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, te._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new ha("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(tr)}label(e){return this._leafNode(new Ul(e))}break(e){return this._leafNode(new Kl(e))}return(e){let t=new ki;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ki)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new tc;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new Ri(a),t(a);}return r&&(this._currNode=i.finally=new $i,this.code(r)),this._endBlockNode(Ri,$i)}throw(e){return this._leafNode(new Xl(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=te.nil,r,i){return this._blockNode(new Ii(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Ii)}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 er))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;}};U.CodeGen=nc;function nr(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function da(n,e){return e instanceof te._CodeOrName?nr(n,e.names):n}function Ir(n,e,t){if(n instanceof te.Name)return r(n);if(!i(n))return n;return new te._Code(n._items.reduce((a,s)=>(s instanceof te.Name&&(s=r(s)),s instanceof te._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 te._Code&&a._items.some(s=>s instanceof te.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function p_(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function ym(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, te._)`!${rc(n)}`}U.not=ym;var m_=vm(U.operators.AND);function g_(...n){return n.reduce(m_)}U.and=g_;var y_=vm(U.operators.OR);function v_(...n){return n.reduce(y_)}U.or=v_;function vm(n){return (e,t)=>e===te.nil?t:t===te.nil?e:(0, te._)`${rc(e)} ${n} ${rc(t)}`}function rc(n){return n instanceof te.Name?n:(0, te._)`(${n})`}});var Q=w(Y=>{Object.defineProperty(Y,"__esModule",{value:true});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var me=M(),C_=Ni();function b_(n){let e={};for(let t of n)e[t]=true;return e}Y.toHash=b_;function __(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(_m(n,e),!Sm(e,n.self.RULES.all))}Y.alwaysValidSchema=__;function _m(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]||Am(n,`unknown keyword: "${a}"`);}Y.checkUnknownRules=_m;function Sm(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}Y.schemaHasRules=Sm;function S_(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}Y.schemaHasRulesButRef=S_;function E_({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, me._)`${t}`}return (0, me._)`${n}${e}${(0, me.getProperty)(r)}`}Y.schemaRefOrVal=E_;function w_(n){return Em(decodeURIComponent(n))}Y.unescapeFragment=w_;function A_(n){return encodeURIComponent(sc(n))}Y.escapeFragment=A_;function sc(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}Y.escapeJsonPointer=sc;function Em(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}Y.unescapeJsonPointer=Em;function D_(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}Y.eachItem=D_;function Cm({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof me.Name?(a instanceof me.Name?n(i,a,s):e(i,a,s),s):a instanceof me.Name?(e(i,s,a),a):t(a,s);return o===me.Name&&!(u instanceof me.Name)?r(i,u):u}}Y.mergeEvaluated={props:Cm({mergeNames:(n,e,t)=>n.if((0, me._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, me._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, me._)`${t} || {}`).code((0, me._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, me._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, me._)`${t} || {}`),ac(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:wm}),items:Cm({mergeNames:(n,e,t)=>n.if((0, me._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, me._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, me._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, me._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function wm(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, me._)`{}`);return e!==void 0&&ac(n,t,e),t}Y.evaluatedPropsToName=wm;function ac(n,e,t){Object.keys(t).forEach(r=>n.assign((0, me._)`${e}${(0, me.getProperty)(r)}`,true));}Y.setEvaluated=ac;var bm={};function x_(n,e){return n.scopeValue("func",{ref:e,code:bm[e.code]||(bm[e.code]=new C_._Code(e.code))})}Y.useFunc=x_;var ic;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(ic||(Y.Type=ic={}));function P_(n,e,t){if(n instanceof me.Name){let r=e===ic.Num;return t?r?(0, me._)`"[" + ${n} + "]"`:(0, me._)`"['" + ${n} + "']"`:r?(0, me._)`"/" + ${n}`:(0, me._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, me.getProperty)(n).toString():"/"+sc(n)}Y.getErrorPath=P_;function Am(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}Y.checkStrictMode=Am;});var xt=w(oc=>{Object.defineProperty(oc,"__esModule",{value:true});var ze=M(),O_={data:new ze.Name("data"),valCxt:new ze.Name("valCxt"),instancePath:new ze.Name("instancePath"),parentData:new ze.Name("parentData"),parentDataProperty:new ze.Name("parentDataProperty"),rootData:new ze.Name("rootData"),dynamicAnchors:new ze.Name("dynamicAnchors"),vErrors:new ze.Name("vErrors"),errors:new ze.Name("errors"),this:new ze.Name("this"),self:new ze.Name("self"),scope:new ze.Name("scope"),json:new ze.Name("json"),jsonPos:new ze.Name("jsonPos"),jsonLen:new ze.Name("jsonLen"),jsonPart:new ze.Name("jsonPart")};oc.default=O_;});var Vi=w(Ue=>{Object.defineProperty(Ue,"__esModule",{value:true});Ue.extendErrors=Ue.resetErrorsCount=Ue.reportExtraError=Ue.reportError=Ue.keyword$DataError=Ue.keywordError=void 0;var re=M(),pa=Q(),rt=xt();Ue.keywordError={message:({keyword:n})=>(0, re.str)`must pass "${n}" keyword validation`};Ue.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, re.str)`"${n}" keyword must be ${e} ($data)`:(0, re.str)`"${n}" keyword is invalid ($data)`};function T_(n,e=Ue.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=Pm(n,e,t);r??(s||o)?Dm(a,u):xm(i,(0, re._)`[${u}]`);}Ue.reportError=T_;function N_(n,e=Ue.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=Pm(n,e,t);Dm(i,o),a||s||xm(r,rt.default.vErrors);}Ue.reportExtraError=N_;function F_(n,e){n.assign(rt.default.errors,e),n.if((0, re._)`${rt.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, re._)`${rt.default.vErrors}.length`,e),()=>n.assign(rt.default.vErrors,null)));}Ue.resetErrorsCount=F_;function I_({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,rt.default.errors,o=>{n.const(s,(0, re._)`${rt.default.vErrors}[${o}]`),n.if((0, re._)`${s}.instancePath === undefined`,()=>n.assign((0, re._)`${s}.instancePath`,(0, re.strConcat)(rt.default.instancePath,a.errorPath))),n.assign((0, re._)`${s}.schemaPath`,(0, re.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, re._)`${s}.schema`,t),n.assign((0, re._)`${s}.data`,r));});}Ue.extendErrors=I_;function Dm(n,e){let t=n.const("err",e);n.if((0, re._)`${rt.default.vErrors} === null`,()=>n.assign(rt.default.vErrors,(0, re._)`[${t}]`),(0, re._)`${rt.default.vErrors}.push(${t})`),n.code((0, re._)`${rt.default.errors}++`);}function xm(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, re._)`new ${n.ValidationError}(${e})`):(t.assign((0, re._)`${r}.errors`,e),t.return(false));}var rr={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function Pm(n,e,t){let{createErrors:r}=n.it;return r===false?(0, re._)`{}`:k_(n,e,t)}function k_(n,e,t={}){let{gen:r,it:i}=n,a=[R_(i,t),$_(n,t)];return V_(n,e,a),r.object(...a)}function R_({errorPath:n},{instancePath:e}){let t=e?(0, re.str)`${n}${(0, pa.getErrorPath)(e,pa.Type.Str)}`:n;return [rt.default.instancePath,(0, re.strConcat)(rt.default.instancePath,t)]}function $_({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, re.str)`${e}/${n}`;return t&&(i=(0, re.str)`${i}${(0, pa.getErrorPath)(t,pa.Type.Str)}`),[rr.schemaPath,i]}function V_(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([rr.keyword,i],[rr.params,typeof e=="function"?e(n):e||(0, re._)`{}`]),u.messages&&r.push([rr.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([rr.schema,s],[rr.parentSchema,(0, re._)`${c}${h}`],[rt.default.data,a]),l&&r.push([rr.propertyName,l]);}});var Tm=w(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.boolOrEmptySchema=kr.topBoolOrEmptySchema=void 0;var j_=Vi(),L_=M(),q_=xt(),B_={message:"boolean schema is false"};function M_(n){let{gen:e,schema:t,validateName:r}=n;t===false?Om(n,false):typeof t=="object"&&t.$async===true?e.return(q_.default.data):(e.assign((0, L_._)`${r}.errors`,null),e.return(true));}kr.topBoolOrEmptySchema=M_;function W_(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),Om(n)):t.var(e,true);}kr.boolOrEmptySchema=W_;function Om(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, j_.reportError)(i,B_,void 0,e);}});var uc=w(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.getRules=Rr.isJSONType=void 0;var G_=["string","number","integer","boolean","null","object","array"],H_=new Set(G_);function J_(n){return typeof n=="string"&&H_.has(n)}Rr.isJSONType=J_;function z_(){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:{}}}Rr.getRules=z_;});var lc=w(On=>{Object.defineProperty(On,"__esModule",{value:true});On.shouldUseRule=On.shouldUseGroup=On.schemaHasRulesForType=void 0;function U_({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&Nm(n,r)}On.schemaHasRulesForType=U_;function Nm(n,e){return e.rules.some(t=>Fm(n,t))}On.shouldUseGroup=Nm;function Fm(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))}On.shouldUseRule=Fm;});var ji=w(Ke=>{Object.defineProperty(Ke,"__esModule",{value:true});Ke.reportTypeError=Ke.checkDataTypes=Ke.checkDataType=Ke.coerceAndCheckDataType=Ke.getJSONTypes=Ke.getSchemaTypes=Ke.DataType=void 0;var K_=uc(),X_=lc(),Y_=Vi(),G=M(),Im=Q(),$r;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})($r||(Ke.DataType=$r={}));function Q_(n){let e=km(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}Ke.getSchemaTypes=Q_;function km(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(K_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ke.getJSONTypes=km;function Z_(n,e){let{gen:t,data:r,opts:i}=n,a=eS(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, X_.schemaHasRulesForType)(n,e[0]));if(s){let o=hc(e,r,i.strictNumbers,$r.Wrong);t.if(o,()=>{a.length?tS(n,e,a):dc(n);});}return s}Ke.coerceAndCheckDataType=Z_;var Rm=new Set(["string","number","integer","boolean","null"]);function eS(n,e){return e?n.filter(t=>Rm.has(t)||e==="array"&&t==="array"):[]}function tS(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, G._)`typeof ${i}`),o=r.let("coerced",(0, G._)`undefined`);a.coerceTypes==="array"&&r.if((0, G._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, G._)`${i}[0]`).assign(s,(0, G._)`typeof ${i}`).if(hc(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, G._)`${o} !== undefined`);for(let l of t)(Rm.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),dc(n),r.endIf(),r.if((0, G._)`${o} !== undefined`,()=>{r.assign(i,o),nS(n,o);});function u(l){switch(l){case "string":r.elseIf((0, G._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, G._)`"" + ${i}`).elseIf((0, G._)`${i} === null`).assign(o,(0, G._)`""`);return;case "number":r.elseIf((0, G._)`${s} == "boolean" || ${i} === null
1
+ 'use strict';var zod=require('zod'),characters=require('@drincs/pixi-vn/characters'),pixiVn=require('@drincs/pixi-vn');require('@drincs/pixi-vn/canvas');var narration=require('@drincs/pixi-vn/narration');require('@drincs/pixi-vn/sound');var storage=require('@drincs/pixi-vn/storage'),ln=require('fs/promises'),ie=require('path'),KF=require('fs'),url=require('url'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ln__default=/*#__PURE__*/_interopDefault(ln);var ie__default=/*#__PURE__*/_interopDefault(ie);var KF__namespace=/*#__PURE__*/_interopNamespace(KF);var Vb=Object.create;var Zp=Object.defineProperty;var jb=Object.getOwnPropertyDescriptor;var Lb=Object.getOwnPropertyNames;var qb=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty;var Xn=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var S=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Mb=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Lb(e))!Bb.call(n,i)&&i!==t&&Zp(n,i,{get:()=>e[i],enumerable:!(r=jb(e,i))||r.enumerable});return n};var An=(n,e,t)=>(t=n!=null?Vb(qb(n)):{},Mb(Zp(t,"default",{value:n,enumerable:true}),n));var ki=S(re=>{Object.defineProperty(re,"__esModule",{value:true});re.regexpCode=re.getEsmExportName=re.getProperty=re.safeStringify=re.stringify=re.strConcat=re.addCodeArg=re.str=re._=re.nil=re._Code=re.Name=re.IDENTIFIER=re._CodeOrName=void 0;var Fi=class{};re._CodeOrName=Fi;re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var tr=class extends Fi{constructor(e){if(super(),!re.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}}};re.Name=tr;var Dt=class extends Fi{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 tr&&(t[r.str]=(t[r.str]||0)+1),t),{})}};re._Code=Dt;re.nil=new Dt("");function vm(n,...e){let t=[n[0]],r=0;for(;r<e.length;)Gl(t,e[r]),t.push(n[++r]);return new Dt(t)}re._=vm;var Wl=new Dt("+");function Cm(n,...e){let t=[Ii(n[0])],r=0;for(;r<e.length;)t.push(Wl),Gl(t,e[r]),t.push(Wl,Ii(n[++r]));return o_(t),new Dt(t)}re.str=Cm;function Gl(n,e){e instanceof Dt?n.push(...e._items):e instanceof tr?n.push(e):n.push(c_(e));}re.addCodeArg=Gl;function o_(n){let e=1;for(;e<n.length-1;){if(n[e]===Wl){let t=u_(n[e-1],n[e+1]);if(t!==void 0){n.splice(e-1,3,t);continue}n[e++]="+";}e++;}}function u_(n,e){if(e==='""')return n;if(n==='""')return e;if(typeof n=="string")return e instanceof tr||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 tr))return `"${n}${e.slice(1)}`}function l_(n,e){return e.emptyStr()?n:n.emptyStr()?e:Cm`${n}${e}`}re.strConcat=l_;function c_(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:Ii(Array.isArray(n)?n.join(","):n)}function h_(n){return new Dt(Ii(n))}re.stringify=h_;function Ii(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}re.safeStringify=Ii;function d_(n){return typeof n=="string"&&re.IDENTIFIER.test(n)?new Dt(`.${n}`):vm`[${n}]`}re.getProperty=d_;function f_(n){if(typeof n=="string"&&re.IDENTIFIER.test(n))return new Dt(`${n}`);throw new Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}re.getEsmExportName=f_;function p_(n){return new Dt(n.toString())}re.regexpCode=p_;});var zl=S(ct=>{Object.defineProperty(ct,"__esModule",{value:true});ct.ValueScope=ct.ValueScopeName=ct.Scope=ct.varKinds=ct.UsedValueState=void 0;var lt=ki(),Hl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value;}},ua;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed";})(ua||(ct.UsedValueState=ua={}));ct.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var la=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t;}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.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}}};ct.Scope=la;var ca=class extends lt.Name{constructor(e,t){super(t),this.prefix=e;}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=(0, lt._)`.${new lt.Name(t)}[${r}]`;}};ct.ValueScopeName=ca;var m_=(0, lt._)`\n`,Jl=class extends la{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?m_:lt.nil};}get(){return this._scope}name(e){return new ca(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, lt._)`${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=lt.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,ua.Started);let c=t(l);if(c){let h=this.opts.es5?ct.varKinds.var:ct.varKinds.const;a=(0, lt._)`${a}${h} ${l} = ${c};${this.opts._n}`;}else if(c=i?.(l))a=(0, lt._)`${a}${c}${this.opts._n}`;else throw new Hl(l);u.set(l,ua.Completed);});}return a}};ct.ValueScope=Jl;});var M=S(U=>{Object.defineProperty(U,"__esModule",{value:true});U.or=U.and=U.not=U.CodeGen=U.operators=U.varKinds=U.ValueScopeName=U.ValueScope=U.Scope=U.Name=U.regexpCode=U.stringify=U.getProperty=U.nil=U.strConcat=U.str=U._=void 0;var ee=ki(),Lt=zl(),On=ki();Object.defineProperty(U,"_",{enumerable:true,get:function(){return On._}});Object.defineProperty(U,"str",{enumerable:true,get:function(){return On.str}});Object.defineProperty(U,"strConcat",{enumerable:true,get:function(){return On.strConcat}});Object.defineProperty(U,"nil",{enumerable:true,get:function(){return On.nil}});Object.defineProperty(U,"getProperty",{enumerable:true,get:function(){return On.getProperty}});Object.defineProperty(U,"stringify",{enumerable:true,get:function(){return On.stringify}});Object.defineProperty(U,"regexpCode",{enumerable:true,get:function(){return On.regexpCode}});Object.defineProperty(U,"Name",{enumerable:true,get:function(){return On.Name}});var pa=zl();Object.defineProperty(U,"Scope",{enumerable:true,get:function(){return pa.Scope}});Object.defineProperty(U,"ValueScope",{enumerable:true,get:function(){return pa.ValueScope}});Object.defineProperty(U,"ValueScopeName",{enumerable:true,get:function(){return pa.ValueScopeName}});Object.defineProperty(U,"varKinds",{enumerable:true,get:function(){return pa.varKinds}});U.operators={GT:new ee._Code(">"),GTE:new ee._Code(">="),LT:new ee._Code("<"),LTE:new ee._Code("<="),EQ:new ee._Code("==="),NEQ:new ee._Code("!=="),NOT:new ee._Code("!"),OR:new ee._Code("||"),AND:new ee._Code("&&"),ADD:new ee._Code("+")};var mn=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Ul=class extends mn{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r;}render({es5:e,_n:t}){let r=e?Lt.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=Rr(this.rhs,e,t)),this}get names(){return this.rhs instanceof ee._CodeOrName?this.rhs.names:{}}},ha=class extends mn{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 ee.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Rr(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ee.Name?{}:{...this.lhs.names};return fa(e,this.rhs)}},Kl=class extends ha{constructor(e,t,r,i){super(e,r,i),this.op=t;}render({_n:e}){return `${this.lhs} ${this.op}= ${this.rhs};`+e}},Xl=class extends mn{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `${this.label}:`+e}},Yl=class extends mn{constructor(e){super(),this.label=e,this.names={};}render({_n:e}){return `break${this.label?` ${this.label}`:""};`+e}},Ql=class extends mn{constructor(e){super(),this.error=e;}render({_n:e}){return `throw ${this.error};`+e}get names(){return this.error.names}},Zl=class extends mn{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=Rr(this.code,e,t),this}get names(){return this.code instanceof ee._CodeOrName?this.code.names:{}}},Ri=class extends mn{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)||(g_(e,a.names),r.splice(i,1));}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ir(e,t.names),{})}},gn=class extends Ri{render(e){return "{"+e._n+super.render(e)+"}"+e._n}},ec=class extends Ri{},kr=class extends gn{};kr.kind="else";var nr=class n extends gn{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 kr(r):r;}if(t)return e===false?t instanceof n?t:t.nodes:this.nodes.length?this:new n(bm(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=Rr(this.condition,e,t),this}get names(){let e=super.names;return fa(e,this.condition),this.else&&ir(e,this.else.names),e}};nr.kind="if";var rr=class extends gn{};rr.kind="for";var tc=class extends rr{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=Rr(this.iteration,e,t),this}get names(){return ir(super.names,this.iteration.names)}},nc=class extends rr{constructor(e,t,r,i){super(),this.varKind=e,this.name=t,this.from=r,this.to=i;}render(e){let t=e.es5?Lt.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=fa(super.names,this.from);return fa(e,this.to)}},da=class extends rr{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=Rr(this.iterable,e,t),this}get names(){return ir(super.names,this.iterable.names)}},$i=class extends gn{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)}};$i.kind="func";var Vi=class extends Ri{render(e){return "return "+super.render(e)}};Vi.kind="return";var rc=class extends gn{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&&ir(e,this.catch.names),this.finally&&ir(e,this.finally.names),e}},ji=class extends gn{constructor(e){super(),this.error=e;}render(e){return `catch(${this.error})`+super.render(e)}};ji.kind="catch";var Li=class extends gn{render(e){return "finally"+super.render(e)}};Li.kind="finally";var ic=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
2
+ `:""},this._extScope=e,this._scope=new Lt.Scope({parent:e}),this._nodes=[new ec];}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 Ul(e,a,r)),a}const(e,t,r){return this._def(Lt.varKinds.const,e,t,r)}let(e,t,r){return this._def(Lt.varKinds.let,e,t,r)}var(e,t,r){return this._def(Lt.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new ha(e,t,r))}add(e,t){return this._leafNode(new Kl(e,U.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ee.nil&&this._leafNode(new Zl(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, ee.addCodeArg)(t,i));return t.push("}"),new ee._Code(t)}if(e,t,r){if(this._blockNode(new nr(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 nr(e))}else(){return this._elseNode(new kr)}endIf(){return this._endBlockNode(nr,kr)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new tc(e),t)}forRange(e,t,r,i,a=this.opts.es5?Lt.varKinds.var:Lt.varKinds.let){let s=this._scope.toName(e);return this._for(new nc(a,s,t,r),()=>i(s))}forOf(e,t,r,i=Lt.varKinds.const){let a=this._scope.toName(e);if(this.opts.es5){let s=t instanceof ee.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0, ee._)`${s}.length`,o=>{this.var(a,(0, ee._)`${s}[${o}]`),r(a);})}return this._for(new da("of",i,a,t),()=>r(a))}forIn(e,t,r,i=this.opts.es5?Lt.varKinds.var:Lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0, ee._)`Object.keys(${t})`,r);let a=this._scope.toName(e);return this._for(new da("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Xl(e))}break(e){return this._leafNode(new Yl(e))}return(e){let t=new Vi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vi)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new rc;if(this._blockNode(i),this.code(e),t){let a=this.name("e");this._currNode=i.catch=new ji(a),t(a);}return r&&(this._currNode=i.finally=new Li,this.code(r)),this._endBlockNode(ji,Li)}throw(e){return this._leafNode(new Ql(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=ee.nil,r,i){return this._blockNode(new $i(e,t,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode($i)}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 nr))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;}};U.CodeGen=ic;function ir(n,e){for(let t in e)n[t]=(n[t]||0)+(e[t]||0);return n}function fa(n,e){return e instanceof ee._CodeOrName?ir(n,e.names):n}function Rr(n,e,t){if(n instanceof ee.Name)return r(n);if(!i(n))return n;return new ee._Code(n._items.reduce((a,s)=>(s instanceof ee.Name&&(s=r(s)),s instanceof ee._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 ee._Code&&a._items.some(s=>s instanceof ee.Name&&e[s.str]===1&&t[s.str]!==void 0)}}function g_(n,e){for(let t in e)n[t]=(n[t]||0)-(e[t]||0);}function bm(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:(0, ee._)`!${sc(n)}`}U.not=bm;var y_=_m(U.operators.AND);function v_(...n){return n.reduce(y_)}U.and=v_;var C_=_m(U.operators.OR);function b_(...n){return n.reduce(C_)}U.or=b_;function _m(n){return (e,t)=>e===ee.nil?t:t===ee.nil?e:(0, ee._)`${sc(e)} ${n} ${sc(t)}`}function sc(n){return n instanceof ee.Name?n:(0, ee._)`(${n})`}});var Y=S(X=>{Object.defineProperty(X,"__esModule",{value:true});X.checkStrictMode=X.getErrorPath=X.Type=X.useFunc=X.setEvaluated=X.evaluatedPropsToName=X.mergeEvaluated=X.eachItem=X.unescapeJsonPointer=X.escapeJsonPointer=X.escapeFragment=X.unescapeFragment=X.schemaRefOrVal=X.schemaHasRulesButRef=X.schemaHasRules=X.checkUnknownRules=X.alwaysValidSchema=X.toHash=void 0;var me=M(),__=ki();function S_(n){let e={};for(let t of n)e[t]=true;return e}X.toHash=S_;function E_(n,e){return typeof e=="boolean"?e:Object.keys(e).length===0?true:(wm(n,e),!Am(e,n.self.RULES.all))}X.alwaysValidSchema=E_;function wm(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]||Pm(n,`unknown keyword: "${a}"`);}X.checkUnknownRules=wm;function Am(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(e[t])return true;return false}X.schemaHasRules=Am;function w_(n,e){if(typeof n=="boolean")return !n;for(let t in n)if(t!=="$ref"&&e.all[t])return true;return false}X.schemaHasRulesButRef=w_;function A_({topSchemaRef:n,schemaPath:e},t,r,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return (0, me._)`${t}`}return (0, me._)`${n}${e}${(0, me.getProperty)(r)}`}X.schemaRefOrVal=A_;function D_(n){return Dm(decodeURIComponent(n))}X.unescapeFragment=D_;function x_(n){return encodeURIComponent(oc(n))}X.escapeFragment=x_;function oc(n){return typeof n=="number"?`${n}`:n.replace(/~/g,"~0").replace(/\//g,"~1")}X.escapeJsonPointer=oc;function Dm(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}X.unescapeJsonPointer=Dm;function P_(n,e){if(Array.isArray(n))for(let t of n)e(t);else e(n);}X.eachItem=P_;function Sm({mergeNames:n,mergeToName:e,mergeValues:t,resultToName:r}){return (i,a,s,o)=>{let u=s===void 0?a:s instanceof me.Name?(a instanceof me.Name?n(i,a,s):e(i,a,s),s):a instanceof me.Name?(e(i,s,a),a):t(a,s);return o===me.Name&&!(u instanceof me.Name)?r(i,u):u}}X.mergeEvaluated={props:Sm({mergeNames:(n,e,t)=>n.if((0, me._)`${t} !== true && ${e} !== undefined`,()=>{n.if((0, me._)`${e} === true`,()=>n.assign(t,true),()=>n.assign(t,(0, me._)`${t} || {}`).code((0, me._)`Object.assign(${t}, ${e})`));}),mergeToName:(n,e,t)=>n.if((0, me._)`${t} !== true`,()=>{e===true?n.assign(t,true):(n.assign(t,(0, me._)`${t} || {}`),uc(n,t,e));}),mergeValues:(n,e)=>n===true?true:{...n,...e},resultToName:xm}),items:Sm({mergeNames:(n,e,t)=>n.if((0, me._)`${t} !== true && ${e} !== undefined`,()=>n.assign(t,(0, me._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(n,e,t)=>n.if((0, me._)`${t} !== true`,()=>n.assign(t,e===true?true:(0, me._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(n,e)=>n===true?true:Math.max(n,e),resultToName:(n,e)=>n.var("items",e)})};function xm(n,e){if(e===true)return n.var("props",true);let t=n.var("props",(0, me._)`{}`);return e!==void 0&&uc(n,t,e),t}X.evaluatedPropsToName=xm;function uc(n,e,t){Object.keys(t).forEach(r=>n.assign((0, me._)`${e}${(0, me.getProperty)(r)}`,true));}X.setEvaluated=uc;var Em={};function O_(n,e){return n.scopeValue("func",{ref:e,code:Em[e.code]||(Em[e.code]=new __._Code(e.code))})}X.useFunc=O_;var ac;(function(n){n[n.Num=0]="Num",n[n.Str=1]="Str";})(ac||(X.Type=ac={}));function T_(n,e,t){if(n instanceof me.Name){let r=e===ac.Num;return t?r?(0, me._)`"[" + ${n} + "]"`:(0, me._)`"['" + ${n} + "']"`:r?(0, me._)`"/" + ${n}`:(0, me._)`"/" + ${n}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0, me.getProperty)(n).toString():"/"+oc(n)}X.getErrorPath=T_;function Pm(n,e,t=n.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===true)throw new Error(e);n.self.logger.warn(e);}}X.checkStrictMode=Pm;});var xt=S(lc=>{Object.defineProperty(lc,"__esModule",{value:true});var Ue=M(),N_={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};lc.default=N_;});var qi=S(Ke=>{Object.defineProperty(Ke,"__esModule",{value:true});Ke.extendErrors=Ke.resetErrorsCount=Ke.reportExtraError=Ke.reportError=Ke.keyword$DataError=Ke.keywordError=void 0;var ne=M(),ma=Y(),it=xt();Ke.keywordError={message:({keyword:n})=>(0, ne.str)`must pass "${n}" keyword validation`};Ke.keyword$DataError={message:({keyword:n,schemaType:e})=>e?(0, ne.str)`"${n}" keyword must be ${e} ($data)`:(0, ne.str)`"${n}" keyword is invalid ($data)`};function F_(n,e=Ke.keywordError,t,r){let{it:i}=n,{gen:a,compositeRule:s,allErrors:o}=i,u=Nm(n,e,t);r??(s||o)?Om(a,u):Tm(i,(0, ne._)`[${u}]`);}Ke.reportError=F_;function I_(n,e=Ke.keywordError,t){let{it:r}=n,{gen:i,compositeRule:a,allErrors:s}=r,o=Nm(n,e,t);Om(i,o),a||s||Tm(r,it.default.vErrors);}Ke.reportExtraError=I_;function k_(n,e){n.assign(it.default.errors,e),n.if((0, ne._)`${it.default.vErrors} !== null`,()=>n.if(e,()=>n.assign((0, ne._)`${it.default.vErrors}.length`,e),()=>n.assign(it.default.vErrors,null)));}Ke.resetErrorsCount=k_;function R_({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,it.default.errors,o=>{n.const(s,(0, ne._)`${it.default.vErrors}[${o}]`),n.if((0, ne._)`${s}.instancePath === undefined`,()=>n.assign((0, ne._)`${s}.instancePath`,(0, ne.strConcat)(it.default.instancePath,a.errorPath))),n.assign((0, ne._)`${s}.schemaPath`,(0, ne.str)`${a.errSchemaPath}/${e}`),a.opts.verbose&&(n.assign((0, ne._)`${s}.schema`,t),n.assign((0, ne._)`${s}.data`,r));});}Ke.extendErrors=R_;function Om(n,e){let t=n.const("err",e);n.if((0, ne._)`${it.default.vErrors} === null`,()=>n.assign(it.default.vErrors,(0, ne._)`[${t}]`),(0, ne._)`${it.default.vErrors}.push(${t})`),n.code((0, ne._)`${it.default.errors}++`);}function Tm(n,e){let{gen:t,validateName:r,schemaEnv:i}=n;i.$async?t.throw((0, ne._)`new ${n.ValidationError}(${e})`):(t.assign((0, ne._)`${r}.errors`,e),t.return(false));}var sr={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function Nm(n,e,t){let{createErrors:r}=n.it;return r===false?(0, ne._)`{}`:$_(n,e,t)}function $_(n,e,t={}){let{gen:r,it:i}=n,a=[V_(i,t),j_(n,t)];return L_(n,e,a),r.object(...a)}function V_({errorPath:n},{instancePath:e}){let t=e?(0, ne.str)`${n}${(0, ma.getErrorPath)(e,ma.Type.Str)}`:n;return [it.default.instancePath,(0, ne.strConcat)(it.default.instancePath,t)]}function j_({keyword:n,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:r}){let i=r?e:(0, ne.str)`${e}/${n}`;return t&&(i=(0, ne.str)`${i}${(0, ma.getErrorPath)(t,ma.Type.Str)}`),[sr.schemaPath,i]}function L_(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([sr.keyword,i],[sr.params,typeof e=="function"?e(n):e||(0, ne._)`{}`]),u.messages&&r.push([sr.message,typeof t=="function"?t(n):t]),u.verbose&&r.push([sr.schema,s],[sr.parentSchema,(0, ne._)`${c}${h}`],[it.default.data,a]),l&&r.push([sr.propertyName,l]);}});var Im=S($r=>{Object.defineProperty($r,"__esModule",{value:true});$r.boolOrEmptySchema=$r.topBoolOrEmptySchema=void 0;var q_=qi(),B_=M(),M_=xt(),W_={message:"boolean schema is false"};function G_(n){let{gen:e,schema:t,validateName:r}=n;t===false?Fm(n,false):typeof t=="object"&&t.$async===true?e.return(M_.default.data):(e.assign((0, B_._)`${r}.errors`,null),e.return(true));}$r.topBoolOrEmptySchema=G_;function H_(n,e){let{gen:t,schema:r}=n;r===false?(t.var(e,false),Fm(n)):t.var(e,true);}$r.boolOrEmptySchema=H_;function Fm(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, q_.reportError)(i,W_,void 0,e);}});var cc=S(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.getRules=Vr.isJSONType=void 0;var J_=["string","number","integer","boolean","null","object","array"],z_=new Set(J_);function U_(n){return typeof n=="string"&&z_.has(n)}Vr.isJSONType=U_;function K_(){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:{}}}Vr.getRules=K_;});var hc=S(Tn=>{Object.defineProperty(Tn,"__esModule",{value:true});Tn.shouldUseRule=Tn.shouldUseGroup=Tn.schemaHasRulesForType=void 0;function X_({schema:n,self:e},t){let r=e.RULES.types[t];return r&&r!==true&&km(n,r)}Tn.schemaHasRulesForType=X_;function km(n,e){return e.rules.some(t=>Rm(n,t))}Tn.shouldUseGroup=km;function Rm(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))}Tn.shouldUseRule=Rm;});var Bi=S(Xe=>{Object.defineProperty(Xe,"__esModule",{value:true});Xe.reportTypeError=Xe.checkDataTypes=Xe.checkDataType=Xe.coerceAndCheckDataType=Xe.getJSONTypes=Xe.getSchemaTypes=Xe.DataType=void 0;var Y_=cc(),Q_=hc(),Z_=qi(),G=M(),$m=Y(),jr;(function(n){n[n.Correct=0]="Correct",n[n.Wrong=1]="Wrong";})(jr||(Xe.DataType=jr={}));function eS(n){let e=Vm(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}Xe.getSchemaTypes=eS;function Vm(n){let e=Array.isArray(n)?n:n?[n]:[];if(e.every(Y_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Xe.getJSONTypes=Vm;function tS(n,e){let{gen:t,data:r,opts:i}=n,a=nS(e,i.coerceTypes),s=e.length>0&&!(a.length===0&&e.length===1&&(0, Q_.schemaHasRulesForType)(n,e[0]));if(s){let o=fc(e,r,i.strictNumbers,jr.Wrong);t.if(o,()=>{a.length?rS(n,e,a):pc(n);});}return s}Xe.coerceAndCheckDataType=tS;var jm=new Set(["string","number","integer","boolean","null"]);function nS(n,e){return e?n.filter(t=>jm.has(t)||e==="array"&&t==="array"):[]}function rS(n,e,t){let{gen:r,data:i,opts:a}=n,s=r.let("dataType",(0, G._)`typeof ${i}`),o=r.let("coerced",(0, G._)`undefined`);a.coerceTypes==="array"&&r.if((0, G._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0, G._)`${i}[0]`).assign(s,(0, G._)`typeof ${i}`).if(fc(e,i,a.strictNumbers),()=>r.assign(o,i))),r.if((0, G._)`${o} !== undefined`);for(let l of t)(jm.has(l)||l==="array"&&a.coerceTypes==="array")&&u(l);r.else(),pc(n),r.endIf(),r.if((0, G._)`${o} !== undefined`,()=>{r.assign(i,o),iS(n,o);});function u(l){switch(l){case "string":r.elseIf((0, G._)`${s} == "number" || ${s} == "boolean"`).assign(o,(0, G._)`"" + ${i}`).elseIf((0, G._)`${i} === null`).assign(o,(0, G._)`""`);return;case "number":r.elseIf((0, G._)`${s} == "boolean" || ${i} === null
3
3
  || (${s} == "string" && ${i} && ${i} == +${i})`).assign(o,(0, G._)`+${i}`);return;case "integer":r.elseIf((0, G._)`${s} === "boolean" || ${i} === null
4
4
  || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(o,(0, G._)`+${i}`);return;case "boolean":r.elseIf((0, G._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(o,false).elseIf((0, G._)`${i} === "true" || ${i} === 1`).assign(o,true);return;case "null":r.elseIf((0, G._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(o,null);return;case "array":r.elseIf((0, G._)`${s} === "string" || ${s} === "number"
5
- || ${s} === "boolean" || ${i} === null`).assign(o,(0, G._)`[${i}]`);}}}function nS({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, G._)`${e} !== undefined`,()=>n.assign((0, G._)`${e}[${t}]`,r));}function cc(n,e,t,r=$r.Correct){let i=r===$r.Correct?G.operators.EQ:G.operators.NEQ,a;switch(n){case "null":return (0, G._)`${e} ${i} null`;case "array":a=(0, G._)`Array.isArray(${e})`;break;case "object":a=(0, G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, G._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, G._)`typeof ${e} ${i} ${n}`}return r===$r.Correct?a:(0, G.not)(a);function s(o=G.nil){return (0, G.and)((0, G._)`typeof ${e} == "number"`,o,t?(0, G._)`isFinite(${e})`:G.nil)}}Ke.checkDataType=cc;function hc(n,e,t,r){if(n.length===1)return cc(n[0],e,t,r);let i,a=(0, Im.toHash)(n);if(a.array&&a.object){let s=(0, G._)`typeof ${e} != "object"`;i=a.null?s:(0, G._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=G.nil;a.number&&delete a.integer;for(let s in a)i=(0, G.and)(i,cc(s,e,t,r));return i}Ke.checkDataTypes=hc;var rS={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, G._)`{type: ${n}}`:(0, G._)`{type: ${e}}`};function dc(n){let e=iS(n);(0, Y_.reportError)(e,rS);}Ke.reportTypeError=dc;function iS(n){let{gen:e,data:t,schema:r}=n,i=(0, Im.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var Vm=w(ma=>{Object.defineProperty(ma,"__esModule",{value:true});ma.assignDefaults=void 0;var Vr=M(),sS=Q();function aS(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)$m(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>$m(n,a,i.default));}ma.assignDefaults=aS;function $m(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, Vr._)`${a}${(0, Vr.getProperty)(e)}`;if(i){(0, sS.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, Vr._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, Vr._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, Vr._)`${o} = ${(0, Vr.stringify)(t)}`);}});var Pt=w(de=>{Object.defineProperty(de,"__esModule",{value:true});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var Ee=M(),fc=Q(),Tn=xt(),oS=Q();function uS(n,e){let{gen:t,data:r,it:i}=n;t.if(mc(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, Ee._)`${e}`},true),n.error();});}de.checkReportMissingProp=uS;function lS({gen:n,data:e,it:{opts:t}},r,i){return (0, Ee.or)(...r.map(a=>(0, Ee.and)(mc(n,e,a,t.ownProperties),(0, Ee._)`${i} = ${a}`)))}de.checkMissingProp=lS;function cS(n,e){n.setParams({missingProperty:e},true),n.error();}de.reportMissingProp=cS;function jm(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, Ee._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=jm;function pc(n,e,t){return (0, Ee._)`${jm(n)}.call(${e}, ${t})`}de.isOwnProperty=pc;function hS(n,e,t,r){let i=(0, Ee._)`${e}${(0, Ee.getProperty)(t)} !== undefined`;return r?(0, Ee._)`${i} && ${pc(n,e,t)}`:i}de.propertyInData=hS;function mc(n,e,t,r){let i=(0, Ee._)`${e}${(0, Ee.getProperty)(t)} === undefined`;return r?(0, Ee.or)(i,(0, Ee.not)(pc(n,e,t))):i}de.noPropertyInData=mc;function Lm(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=Lm;function dS(n,e){return Lm(e).filter(t=>!(0, fc.alwaysValidSchema)(n,e[t]))}de.schemaProperties=dS;function fS({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, Ee._)`${n}, ${e}, ${r}${i}`:e,h=[[Tn.default.instancePath,(0, Ee.strConcat)(Tn.default.instancePath,a)],[Tn.default.parentData,s.parentData],[Tn.default.parentDataProperty,s.parentDataProperty],[Tn.default.rootData,Tn.default.rootData]];s.opts.dynamicRef&&h.push([Tn.default.dynamicAnchors,Tn.default.dynamicAnchors]);let d=(0, Ee._)`${c}, ${t.object(...h)}`;return u!==Ee.nil?(0, Ee._)`${o}.call(${u}, ${d})`:(0, Ee._)`${o}(${d})`}de.callValidateCode=fS;var pS=(0, Ee._)`new RegExp`;function mS({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, Ee._)`${i.code==="new RegExp"?pS:(0, oS.useFunc)(n,i)}(${t}, ${r})`})}de.usePattern=mS;function gS(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, Ee._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:fc.Type.Num},a),e.if((0, Ee.not)(a),o);});}}de.validateArray=gS;function yS(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, fc.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, Ee._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, Ee.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}de.validateUnion=yS;});var Mm=w(Yt=>{Object.defineProperty(Yt,"__esModule",{value:true});Yt.validateKeywordUsage=Yt.validSchemaType=Yt.funcKeywordCode=Yt.macroKeywordCode=void 0;var it=M(),ir=xt(),vS=Pt(),CS=Vi();function bS(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=Bm(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:it.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}Yt.macroKeywordCode=bS;function _S(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;ES(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=Bm(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)m(),e.modifying&&qm(n),b(()=>n.error());else {let _=e.async?g():f();e.modifying&&qm(n),b(()=>SS(n,_));}}function g(){let _=r.let("ruleErrs",null);return r.try(()=>m((0, it._)`await `),y=>r.assign(h,false).if((0, it._)`${y} instanceof ${u.ValidationError}`,()=>r.assign(_,(0, it._)`${y}.errors`),()=>r.throw(y))),_}function f(){let _=(0, it._)`${c}.errors`;return r.assign(_,null),m(it.nil),_}function m(_=e.async?(0, it._)`await `:it.nil){let y=u.opts.passContext?ir.default.this:ir.default.self,p=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, it._)`${_}${(0, vS.callValidateCode)(n,c,y,p)}`,e.modifying);}function b(_){var y;r.if((0, it.not)((y=e.valid)!==null&&y!==void 0?y:h),_);}}Yt.funcKeywordCode=_S;function qm(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, it._)`${r.parentData}[${r.parentDataProperty}]`));}function SS(n,e){let{gen:t}=n;t.if((0, it._)`Array.isArray(${e})`,()=>{t.assign(ir.default.vErrors,(0, it._)`${ir.default.vErrors} === null ? ${e} : ${ir.default.vErrors}.concat(${e})`).assign(ir.default.errors,(0, it._)`${ir.default.vErrors}.length`),(0, CS.extendErrors)(n);},()=>n.error());}function ES({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function Bm(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, it.stringify)(t)})}function wS(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")}Yt.validSchemaType=wS;function AS({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)}}Yt.validateKeywordUsage=AS;});var Gm=w(Nn=>{Object.defineProperty(Nn,"__esModule",{value:true});Nn.extendSubschemaMode=Nn.extendSubschemaData=Nn.getSubschema=void 0;var Qt=M(),Wm=Q();function DS(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, Qt._)`${n.schemaPath}${(0, Qt.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, Qt._)`${n.schemaPath}${(0, Qt.getProperty)(e)}${(0, Qt.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, Wm.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')}Nn.getSubschema=DS;function xS(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, Qt._)`${e.data}${(0, Qt.getProperty)(t)}`,true);u(d),n.errorPath=(0, Qt.str)`${l}${(0, Wm.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, Qt._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof Qt.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];}}Nn.extendSubschemaData=xS;function PS(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;}Nn.extendSubschemaMode=PS;});var gc=w((j$,Hm)=>{Hm.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 zm=w((L$,Jm)=>{var Fn=Jm.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(){};ga(e,r,i,n,"",n);};Fn.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};Fn.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};Fn.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};Fn.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 ga(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 Fn.arrayKeywords)for(var d=0;d<h.length;d++)ga(n,e,t,h[d],i+"/"+c+"/"+d,a,i,c,r,d);}else if(c in Fn.propsKeywords){if(h&&typeof h=="object")for(var g in h)ga(n,e,t,h[g],i+"/"+c+"/"+OS(g),a,i,c,r,g);}else (c in Fn.keywords||n.allKeys&&!(c in Fn.skipKeywords))&&ga(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function OS(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var Li=w(ht=>{Object.defineProperty(ht,"__esModule",{value:true});ht.getSchemaRefs=ht.resolveUrl=ht.normalizeId=ht._getFullPath=ht.getFullPath=ht.inlineRef=void 0;var TS=Q(),NS=gc(),FS=zm(),IS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kS(n,e=true){return typeof n=="boolean"?true:e===true?!yc(n):e?Um(n)<=e:false}ht.inlineRef=kS;var RS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yc(n){for(let e in n){if(RS.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(yc)||typeof t=="object"&&yc(t))return true}return false}function Um(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!IS.has(t)&&(typeof n[t]=="object"&&(0, TS.eachItem)(n[t],r=>e+=Um(r)),e===1/0))return 1/0}return e}function Km(n,e="",t){t!==false&&(e=jr(e));let r=n.parse(e);return Xm(n,r)}ht.getFullPath=Km;function Xm(n,e){return n.serialize(e).split("#")[0]+"#"}ht._getFullPath=Xm;var $S=/#\/?$/;function jr(n){return n?n.replace($S,""):""}ht.normalizeId=jr;function VS(n,e,t){return t=jr(t),n.resolve(e,t)}ht.resolveUrl=VS;var jS=/^[a-z_][-a-z0-9._]*$/i;function LS(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=jr(n[t]||e),a={"":i},s=Km(r,i,false),o={},u=new Set;return FS(n,{allKeys:true},(h,d,g,f)=>{if(f===void 0)return;let m=s+d,b=a[f];typeof h[t]=="string"&&(b=_.call(this,h[t])),y.call(this,h.$anchor),y.call(this,h.$dynamicAnchor),a[d]=b;function _(p){let v=this.opts.uriResolver.resolve;if(p=jr(b?v(b,p):p),u.has(p))throw c(p);u.add(p);let C=this.refs[p];return typeof C=="string"&&(C=this.refs[C]),typeof C=="object"?l(h,C.schema,p):p!==jr(m)&&(p[0]==="#"?(l(h,o[p],p),o[p]=h):this.refs[p]=m),p}function y(p){if(typeof p=="string"){if(!jS.test(p))throw new Error(`invalid anchor "${p}"`);_.call(this,`#${p}`);}}}),o;function l(h,d,g){if(d!==void 0&&!NS(h,d))throw c(g)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}ht.getSchemaRefs=LS;});var Lr=w(In=>{Object.defineProperty(In,"__esModule",{value:true});In.getData=In.KeywordCxt=In.validateFunctionCode=void 0;var tg=Tm(),Ym=ji(),Cc=lc(),ya=ji(),qS=Vm(),Bi=Mm(),vc=Gm(),$=M(),q=xt(),BS=Li(),vn=Q(),qi=Vi();function MS(n){if(ig(n)&&(sg(n),rg(n))){HS(n);return}ng(n,()=>(0, tg.topBoolOrEmptySchema)(n));}In.validateFunctionCode=MS;function ng({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, $._)`${q.default.data}, ${q.default.valCxt}`,r.$async,()=>{n.code((0, $._)`"use strict"; ${Qm(t,i)}`),GS(n,i),n.code(a);}):n.func(e,(0, $._)`${q.default.data}, ${WS(i)}`,r.$async,()=>n.code(Qm(t,i)).code(a));}function WS(n){return (0, $._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${n.dynamicRef?(0, $._)`, ${q.default.dynamicAnchors}={}`:$.nil}}={}`}function GS(n,e){n.if(q.default.valCxt,()=>{n.var(q.default.instancePath,(0, $._)`${q.default.valCxt}.${q.default.instancePath}`),n.var(q.default.parentData,(0, $._)`${q.default.valCxt}.${q.default.parentData}`),n.var(q.default.parentDataProperty,(0, $._)`${q.default.valCxt}.${q.default.parentDataProperty}`),n.var(q.default.rootData,(0, $._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&n.var(q.default.dynamicAnchors,(0, $._)`${q.default.valCxt}.${q.default.dynamicAnchors}`);},()=>{n.var(q.default.instancePath,(0, $._)`""`),n.var(q.default.parentData,(0, $._)`undefined`),n.var(q.default.parentDataProperty,(0, $._)`undefined`),n.var(q.default.rootData,q.default.data),e.dynamicRef&&n.var(q.default.dynamicAnchors,(0, $._)`{}`);});}function HS(n){let{schema:e,opts:t,gen:r}=n;ng(n,()=>{t.$comment&&e.$comment&&og(n),XS(n),r.let(q.default.vErrors,null),r.let(q.default.errors,0),t.unevaluated&&JS(n),ag(n),ZS(n);});}function JS(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, $._)`${t}.evaluated`),e.if((0, $._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, $._)`${n.evaluated}.props`,(0, $._)`undefined`)),e.if((0, $._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, $._)`${n.evaluated}.items`,(0, $._)`undefined`));}function Qm(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, $._)`/*# sourceURL=${t} */`:$.nil}function zS(n,e){if(ig(n)&&(sg(n),rg(n))){US(n,e);return}(0, tg.boolOrEmptySchema)(n,e);}function rg({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 ig(n){return typeof n.schema!="boolean"}function US(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&og(n),YS(n),QS(n);let a=r.const("_errs",q.default.errors);ag(n,a),r.var(e,(0, $._)`${a} === ${q.default.errors}`);}function sg(n){(0, vn.checkUnknownRules)(n),KS(n);}function ag(n,e){if(n.opts.jtd)return Zm(n,[],false,e);let t=(0, Ym.getSchemaTypes)(n.schema),r=(0, Ym.coerceAndCheckDataType)(n,t);Zm(n,t,!r,e);}function KS(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, vn.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function XS(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, vn.checkStrictMode)(n,"default is ignored in the schema root");}function YS(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, BS.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function QS(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function og({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, $._)`${q.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, $.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, $._)`${q.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function ZS(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, $._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0, $._)`new ${i}(${q.default.vErrors})`)):(e.assign((0, $._)`${r}.errors`,q.default.vErrors),a.unevaluated&&eE(n),e.return((0, $._)`${q.default.errors} === 0`));}function eE({gen:n,evaluated:e,props:t,items:r}){t instanceof $.Name&&n.assign((0, $._)`${e}.props`,t),r instanceof $.Name&&n.assign((0, $._)`${e}.items`,r);}function Zm(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, vn.schemaHasRulesButRef)(a,c))){i.block(()=>lg(n,"$ref",c.all.$ref.definition));return}u.jtd||tE(n,e),i.block(()=>{for(let d of c.rules)h(d);h(c.post);});function h(d){(0, Cc.shouldUseGroup)(a,d)&&(d.type?(i.if((0, ya.checkDataType)(d.type,s,u.strictNumbers)),eg(n,d),e.length===1&&e[0]===d.type&&t&&(i.else(),(0, ya.reportTypeError)(n)),i.endIf()):eg(n,d),o||i.if((0, $._)`${q.default.errors} === ${r||0}`));}}function eg(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, qS.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, Cc.shouldUseRule)(r,a)&&lg(n,a.keyword,a.definition,e.type);});}function tE(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(nE(n,e),n.opts.allowUnionTypes||rE(n,e),iE(n,n.dataTypes));}function nE(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{ug(n.dataTypes,t)||bc(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),aE(n,e);}}function rE(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&bc(n,"use allowUnionTypes to allow union type keyword");}function iE(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, Cc.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>sE(e,s))&&bc(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function sE(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function ug(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function aE(n,e){let t=[];for(let r of n.dataTypes)ug(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function bc(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, vn.checkStrictMode)(n,e,n.opts.strictTypes);}var va=class{constructor(e,t,r){if((0, Bi.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, vn.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",cg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, Bi.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",q.default.errors));}result(e,t,r){this.failResult((0, $.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, $.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, $._)`${t} !== undefined && (${(0, $.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?qi.reportExtraError:qi.reportError)(this,this.def.error,t);}$dataError(){(0, qi.reportError)(this,this.def.$dataError||qi.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, qi.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=$.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=$.nil,t=$.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, $.or)((0, $._)`${i} === undefined`,t)),e!==$.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==$.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, $.or)(s(),o());function s(){if(r.length){if(!(t instanceof $.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, $._)`${(0, ya.checkDataTypes)(u,t,a.opts.strictNumbers,ya.DataType.Wrong)}`}return $.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, $._)`!${u}(${t})`}return $.nil}}subschema(e,t){let r=(0, vc.getSubschema)(this.it,e);(0, vc.extendSubschemaData)(r,this.it,e),(0, vc.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return zS(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=vn.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=vn.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,$.Name)),true}};In.KeywordCxt=va;function lg(n,e,t,r){let i=new va(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, Bi.funcKeywordCode)(i,t):"macro"in t?(0, Bi.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, Bi.funcKeywordCode)(i,t);}var oE=/^\/(?:[^~]|~0|~1)*$/,uE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cg(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return q.default.rootData;if(n[0]==="/"){if(!oE.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=q.default.rootData;}else {let l=uE.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}${(0, $.getProperty)((0, vn.unescapeJsonPointer)(l))}`,s=(0, $._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}In.getData=cg;});var Mi=w(Sc=>{Object.defineProperty(Sc,"__esModule",{value:true});var _c=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};Sc.default=_c;});var qr=w(Ac=>{Object.defineProperty(Ac,"__esModule",{value:true});var Ec=Li(),wc=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Ec.resolveUrl)(e,t,r),this.missingSchema=(0, Ec.normalizeId)((0, Ec.getFullPath)(e,this.missingRef));}};Ac.default=wc;});var Wi=w(Ot=>{Object.defineProperty(Ot,"__esModule",{value:true});Ot.resolveSchema=Ot.getCompilingSchema=Ot.resolveRef=Ot.compileSchema=Ot.SchemaEnv=void 0;var qt=M(),lE=Mi(),sr=xt(),Bt=Li(),hg=Q(),cE=Lr(),Br=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, Bt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};Ot.SchemaEnv=Br;function xc(n){let e=dg.call(this,n);if(e)return e;let t=(0, Bt.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new qt.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:lE.default,code:(0, qt._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:sr.default.data,parentData:sr.default.parentData,parentDataProperty:sr.default.parentDataProperty,dataNames:[sr.default.data],dataPathArr:[qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, qt.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:qt.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, qt._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,cE.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs(sr.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let g=new Function(`${sr.default.self}`,`${sr.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:g}),g.errors=null,g.schema=n.schema,g.schemaEnv=n,n.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;g.evaluated={props:f instanceof qt.Name?void 0:f,items:m instanceof qt.Name?void 0:m,dynamicProps:f instanceof qt.Name,dynamicItems:m instanceof qt.Name},g.source&&(g.source.evaluated=(0,qt.stringify)(g.evaluated));}return n.validate=g,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);}}Ot.compileSchema=xc;function hE(n,e,t){var r;t=(0, Bt.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=pE.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 Br({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=dE.call(this,a)}Ot.resolveRef=hE;function dE(n){return (0, Bt.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:xc.call(this,n)}function dg(n){for(let e of this._compilations)if(fE(e,n))return e}Ot.getCompilingSchema=dg;function fE(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function pE(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ca.call(this,n,e)}function Ca(n,e){let t=this.opts.uriResolver.parse(e),r=(0, Bt._getFullPath)(this.opts.uriResolver,t),i=(0, Bt.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return Dc.call(this,t,n);let a=(0, Bt.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=Ca.call(this,n,s);return typeof o?.schema!="object"?void 0:Dc.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||xc.call(this,s),a===(0, Bt.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, Bt.resolveUrl)(this.opts.uriResolver,i,l)),new Br({schema:o,schemaId:u,root:n,baseId:i})}return Dc.call(this,t,s)}}Ot.resolveSchema=Ca;var mE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Dc(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, hg.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!mE.has(o)&&l&&(e=(0, Bt.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, hg.schemaHasRulesButRef)(t,this.RULES)){let o=(0, Bt.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=Ca.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new Br({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var fg=w((H$,gE)=>{gE.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 Ic=w((J$,bg)=>{var yE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Oc=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),ar=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Tc=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),mg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Nc=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),vE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),dt=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)dt[e]="%"+n[e>>4]+n[e&15];}function Xe(n){return n<2048?dt[192|n>>6]+dt[128|n&63]:n<65536?dt[224|n>>12]+dt[128|n>>6&63]+dt[128|n&63]:dt[240|n>>18]+dt[128|n>>12&63]+dt[128|n>>6&63]+dt[128|n&63]}function CE(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 bE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),_E=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),SE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),EE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wE(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!SE(n[e])){if(n[e]==="%"&&e+2<n.length&&ar(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function pg(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 AE(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||!Oc(u))return;a+=2;continue}if(!bE(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:pg(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 pg(s)}function Pc(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&&_E(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(DE(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),!wE(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=AE(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function DE(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function xE(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 PE={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},OE=/[@/?#:]/g,TE=/[@/?#]/g;function gg(n,e){let t=e?TE:OE;return t.lastIndex=0,n.replace(t,r=>PE[r])}function yg(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(ar(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&Tc(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function NE(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(ar(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&Tc(s)?e+=s:e+="%"+a,t+=2;continue}}if(mg(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Cg(i)?r:dt[i];else if(i<55296||i>57343)e+=Xe(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Xe(65536+(i-55296<<10)+(a-56320)),t++):e+=Xe(65533);}else e+=Xe(65533);}}return e}function FE(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(ar(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),mg(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=dt[s];else if(s<55296||s>57343)t+=Xe(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=Xe(65536+(s-55296<<10)+(o-56320)),i++):t+=Xe(65533);}else t+=Xe(65533);}}return t}function Fc(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(ar(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=dt[a];else if(a<55296||a>57343)t+=Xe(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=Xe(65536+(a-55296<<10)+(s-56320)),r++):t+=Xe(65533);}else t+=Xe(65533);}}return t}function vg(n){return Fc(n,vE)}function IE(n){return Fc(n,Nc)}function kE(n){return Fc(n,Nc)}function Cg(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 RE(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(ar(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));Tc(s)?e+=s:e+="%"+a,t+=2;continue}}if(Nc(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Cg(i)?r:dt[i];else if(i<55296||i>57343)e+=Xe(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Xe(65536+(i-55296<<10)+(a-56320)),t++):e+=Xe(65533);}else e+=Xe(65533);}}return e}function $E(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(ar(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function VE(n){let e=[];if(n.userinfo!==void 0&&(e.push(vg(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Oc(t)){let r=Pc(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=yg(t,true),r=Pc(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=gg(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}bg.exports={nonSimpleDomain:EE,recomposeAuthority:VE,reescapeHostDelimiters:gg,normalizePercentEncoding:yg,normalizePathEncoding:NE,serializePathEncoding:FE,normalizeQueryFragmentEncoding:RE,encodeUserinfo:vg,encodeQuery:IE,encodeFragment:kE,escapePreservingEscapes:$E,removeDotSegments:xE,isIPv4:Oc,isUUID:yE,normalizeIPv6:Pc,stringArrayToHexStripped:CE};});var Ag=w((z$,wg)=>{var{isUUID:jE}=Ic(),LE=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,qE=["http","https","ws","wss","urn","urn:uuid"];function BE(n){return qE.indexOf(n)!==-1}function kc(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 _g(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function Sg(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 ME(n){return n.secure=kc(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function WE(n){if((n.port===(kc(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 GE(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(LE);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=Rc(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function HE(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=Rc(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 JE(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!jE(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function zE(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var Eg={scheme:"http",domainHost:true,parse:_g,serialize:Sg},UE={scheme:"https",domainHost:Eg.domainHost,parse:_g,serialize:Sg},ba={scheme:"ws",domainHost:true,parse:ME,serialize:WE},KE={scheme:"wss",domainHost:ba.domainHost,parse:ba.parse,serialize:ba.serialize},XE={scheme:"urn",parse:GE,serialize:HE,skipNormalize:true},YE={scheme:"urn:uuid",parse:JE,serialize:zE,skipNormalize:true},_a={http:Eg,https:UE,ws:ba,wss:KE,urn:XE,"urn:uuid":YE};Object.setPrototypeOf(_a,null);function Rc(n){return n&&(_a[n]||_a[n.toLowerCase()])||void 0}wg.exports={wsIsSecure:kc,SCHEMES:_a,isValidSchemeName:BE,getSchemeHandler:Rc};});var Lg=w((U$,wa)=>{var{normalizeIPv6:Tg,removeDotSegments:Hi,recomposeAuthority:QE,normalizePercentEncoding:Ng,normalizePathEncoding:ZE,serializePathEncoding:Dg,normalizeQueryFragmentEncoding:xg,encodeQuery:ew,encodeFragment:tw,reescapeHostDelimiters:nw,isIPv4:Fg,nonSimpleDomain:rw}=Ic(),{SCHEMES:Ig,getSchemeHandler:$c}=Ag(),kg=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Rg="URI scheme is malformed.";function Pg(n){let e=unescape(String(n));if(!kg.test(e))throw new TypeError(Rg);return e}function iw(n,e){return typeof n=="string"?n=dw(n,e):typeof n=="object"&&(n=Ea(or(n,e),e)),n}function sw(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}=Sa(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:d,malformedSchemeSpecific:g,malformedHost:f,malformedScheme:m}=Sa(e,r);if(a||h||s||d||o||g||u||f||l||m)throw new Error(i.error||c.error||"URI is malformed.");let b=$g(i,c,r,true),_=$c(t&&t.scheme||b.scheme),y=b.host,p=y!==void 0&&y!==""&&(Fg(y)||Tg(y).isIPV6);Vg(b,t||{},_,p);let v=y&&y.indexOf("%")!==-1&&!/\P{ASCII}/u.test(y);if(b.error&&!v)throw new Error(b.error);return r.skipEscape=true,or(b,r)}function $g(n,e,t,r){let i={};return r||(n=Ea(or(n,t),t),e=Ea(or(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=Hi(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=Hi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Hi(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=Hi(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 aw(n,e,t){let r=Og(n,t),i=Og(e,t);return r!==void 0&&i!==void 0&&r===i}function or(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=Pg(t.scheme));let a=$c(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=Ng(t.path):t.path=Dg(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=Pg(t.scheme),i.push(t.scheme,":"));let u=QE(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=Hi(l)),o&&(l=Dg(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",ew(t.query)),t.fragment!==void 0&&i.push("#",tw(t.fragment)),i.join("")}var ow=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,uw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,lw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function cw(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 Gi(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 hw(n){let e=n[4];return Gi(n[3])||e!==void 0&&!(e[0]==="["&&e[e.length-1]==="]")&&Gi(e)||Gi(n[6])||Gi(n[7])||Gi(n[8])}function Vg(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&n.host[0]!=="["&&(e.domainHost||t&&t.domainHost)&&r===false&&rw(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 Sa(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(uw);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let d=n.match(lw);if(d!==null){let f=d[1],m=f.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):f.length!==m.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let g=n.match(ow);if(g){if(r.scheme=g[1],r.userinfo=g[3],r.host=g[4],r.port=parseInt(g[5],10),r.path=g[6]||"",r.query=g[7],r.fragment=g[8],r.scheme!==void 0){let b=unescape(r.scheme);kg.test(b)?r.scheme=b.toLowerCase():(r.error=r.error||Rg,l=true);}a=hw(g),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=g[5]);let f=cw(r,g);if(f!==void 0&&(r.error=r.error||f,i=true),r.host)if(Fg(r.host)===false){let _=r.host[0]==="["&&r.host[r.host.length-1]==="]",y=Tg(r.host);c=y.isIPV6||y.isIPVFuture===true,u=_&&y.error===true,r.host=c?y.host:y.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 m=$c(t.scheme||r.scheme);if(o=Vg(r,t,m,c),!m||m&&!m.skipNormalize){if(n.indexOf("%")!==-1&&r.host!==void 0&&!u){let b=c?r.host:Ng(r.host,true);r.host=nw(b,c);}r.path&&(r.path=ZE(r.path)),r.query&&(r.query=xg(r.query)),r.fragment&&(r.fragment=xg(r.fragment));}m&&m.parse&&(m.parse(r,t),m===Ig.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 Ea(n,e){return Sa(n,e).parsed}function dw(n,e){return jg(n,e).normalized}function jg(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=Sa(n,e);return {normalized:r||i||a||s||o?n:or(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function Og(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:or(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=jg(t,e);return i||a||s||o||u?void 0:r}var Vc={SCHEMES:Ig,normalize:iw,resolve:sw,resolveComponent:$g,equal:aw,serialize:or,parse:Ea};wa.exports=Vc;wa.exports.default=Vc;wa.exports.fastUri=Vc;});var Bg=w(jc=>{Object.defineProperty(jc,"__esModule",{value:true});var qg=Lg();qg.code='require("ajv/dist/runtime/uri").default';jc.default=qg;});var Bc=w(Ge=>{Object.defineProperty(Ge,"__esModule",{value:true});Ge.CodeGen=Ge.Name=Ge.nil=Ge.stringify=Ge.str=Ge._=Ge.KeywordCxt=void 0;var fw=Lr();Object.defineProperty(Ge,"KeywordCxt",{enumerable:true,get:function(){return fw.KeywordCxt}});var Mr=M();Object.defineProperty(Ge,"_",{enumerable:true,get:function(){return Mr._}});Object.defineProperty(Ge,"str",{enumerable:true,get:function(){return Mr.str}});Object.defineProperty(Ge,"stringify",{enumerable:true,get:function(){return Mr.stringify}});Object.defineProperty(Ge,"nil",{enumerable:true,get:function(){return Mr.nil}});Object.defineProperty(Ge,"Name",{enumerable:true,get:function(){return Mr.Name}});Object.defineProperty(Ge,"CodeGen",{enumerable:true,get:function(){return Mr.CodeGen}});var pw=Mi(),Jg=qr(),mw=uc(),Ji=Wi(),gw=M(),zi=Li(),Aa=ji(),qc=Q(),Mg=fg(),yw=Bg(),zg=(n,e)=>new RegExp(n,e);zg.code="new RegExp";var vw=["removeAdditional","useDefaults","coerceTypes"],Cw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bw={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."},_w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wg=200;function Sw(n){var e,t,r,i,a,s,o,u,l,c,h,d,g,f,m,b,_,y,p,v,C,S,D,O,A;let E=n.strict,F=(e=n.code)===null||e===void 0?void 0:e.optimize,R=F===true||F===void 0?1:F||0,k=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:zg,x=(i=n.uriResolver)!==null&&i!==void 0?i:yw.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:E)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:E)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:E)!==null&&c!==void 0?c:"log",strictTuples:(d=(h=n.strictTuples)!==null&&h!==void 0?h:E)!==null&&d!==void 0?d:"log",strictRequired:(f=(g=n.strictRequired)!==null&&g!==void 0?g:E)!==null&&f!==void 0?f:false,code:n.code?{...n.code,optimize:R,regExp:k}:{optimize:R,regExp:k},loopRequired:(m=n.loopRequired)!==null&&m!==void 0?m:Wg,loopEnum:(b=n.loopEnum)!==null&&b!==void 0?b:Wg,meta:(_=n.meta)!==null&&_!==void 0?_:true,messages:(y=n.messages)!==null&&y!==void 0?y:true,inlineRefs:(p=n.inlineRefs)!==null&&p!==void 0?p:true,schemaId:(v=n.schemaId)!==null&&v!==void 0?v:"$id",addUsedSchema:(C=n.addUsedSchema)!==null&&C!==void 0?C:true,validateSchema:(S=n.validateSchema)!==null&&S!==void 0?S:true,validateFormats:(D=n.validateFormats)!==null&&D!==void 0?D:true,unicodeRegExp:(O=n.unicodeRegExp)!==null&&O!==void 0?O:true,int32range:(A=n.int32range)!==null&&A!==void 0?A:true,uriResolver:x}}var Ui=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,...Sw(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new gw.ValueScope({scope:{},prefixes:Cw,es5:t,lines:r}),this.logger=Pw(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, mw.getRules)(),Gg.call(this,bw,e,"NOT SUPPORTED"),Gg.call(this,_w,e,"DEPRECATED","warn"),this._metaOpts=Dw.call(this),e.formats&&ww.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Aw.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ew.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=Mg;r==="id"&&(i={...Mg},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 Jg.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, zi.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=Hg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new Ji.SchemaEnv({schema:{},schemaId:r});if(t=Ji.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=Hg.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, zi.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(Tw.call(this,r,t),!t)return (0, qc.eachItem)(r,a=>Lc.call(this,a)),this;Fw.call(this,t);let i={...t,type:(0, Aa.getJSONTypes)(t.type),schemaType:(0, Aa.getJSONTypes)(t.schemaType)};return (0, qc.eachItem)(r,i.type.length===0?a=>Lc.call(this,a,i):a=>i.type.forEach(s=>Lc.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]=Ug(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, zi.normalizeId)(s||r);let l=zi.getSchemaRefs.call(this,e,r);return u=new Ji.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):Ji.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{Ji.compileSchema.call(this,e);}finally{this.opts=t;}}};Ui.ValidationError=pw.default;Ui.MissingRefError=Jg.default;Ge.default=Ui;function Gg(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 Hg(n){return n=(0, zi.normalizeId)(n),this.schemas[n]||this.refs[n]}function Ew(){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 ww(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function Aw(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 Dw(){let n={...this.opts};for(let e of vw)delete n[e];return n}var xw={log(){},warn(){},error(){}};function Pw(n){if(n===false)return xw;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 Ow=/^[a-z_$][a-z0-9_$:-]*$/i;function Tw(n,e){let{RULES:t}=this;if((0, qc.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Ow.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 Lc(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, Aa.getJSONTypes)(e.type),schemaType:(0, Aa.getJSONTypes)(e.schemaType)}};e.before?Nw.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 Nw(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 Fw(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=Ug(e)),n.validateSchema=this.compile(e,true));}var Iw={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ug(n){return {anyOf:[n,Iw]}}});var Kg=w(Mc=>{Object.defineProperty(Mc,"__esModule",{value:true});var kw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Mc.default=kw;});var Pa=w(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.callRef=ur.getValidate=void 0;var Rw=qr(),Xg=Pt(),ft=M(),Wr=xt(),Yg=Wi(),Da=Q(),$w={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=Yg.resolveRef.call(u,l,i,t);if(c===void 0)throw new Rw.default(r.opts.uriResolver,i,t);if(c instanceof Yg.SchemaEnv)return d(c);return g(c);function h(){if(a===l)return xa(n,s,a,a.$async);let f=e.scopeValue("root",{ref:l});return xa(n,(0, ft._)`${f}.validate`,l,l.$async)}function d(f){let m=Qg(n,f);xa(n,m,f,f.$async);}function g(f){let m=e.scopeValue("schema",o.code.source===true?{ref:f,code:(0, ft.stringify)(f)}:{ref:f}),b=e.name("valid"),_=n.subschema({schema:f,dataTypes:[],schemaPath:ft.nil,topSchemaRef:m,errSchemaPath:t},b);n.mergeEvaluated(_),n.ok(b);}}};function Qg(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, ft._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ur.getValidate=Qg;function xa(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?Wr.default.this:ft.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let f=i.let("valid");i.try(()=>{i.code((0, ft._)`await ${(0, Xg.callValidateCode)(n,e,l)}`),g(e),s||i.assign(f,true);},m=>{i.if((0, ft._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),d(m),s||i.assign(f,false);}),n.ok(f);}function h(){n.result((0, Xg.callValidateCode)(n,e,l),()=>g(e),()=>d(e));}function d(f){let m=(0, ft._)`${f}.errors`;i.assign(Wr.default.vErrors,(0, ft._)`${Wr.default.vErrors} === null ? ${m} : ${Wr.default.vErrors}.concat(${m})`),i.assign(Wr.default.errors,(0, ft._)`${Wr.default.vErrors}.length`);}function g(f){var m;if(!a.opts.unevaluated)return;let b=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==true)if(b&&!b.dynamicProps)b.props!==void 0&&(a.props=Da.mergeEvaluated.props(i,b.props,a.props));else {let _=i.var("props",(0, ft._)`${f}.evaluated.props`);a.props=Da.mergeEvaluated.props(i,_,a.props,ft.Name);}if(a.items!==true)if(b&&!b.dynamicItems)b.items!==void 0&&(a.items=Da.mergeEvaluated.items(i,b.items,a.items));else {let _=i.var("items",(0, ft._)`${f}.evaluated.items`);a.items=Da.mergeEvaluated.items(i,_,a.items,ft.Name);}}}ur.callRef=xa;ur.default=$w;});var Gc=w(Wc=>{Object.defineProperty(Wc,"__esModule",{value:true});var Vw=Kg(),jw=Pa(),Lw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Vw.default,jw.default];Wc.default=Lw;});var Zg=w(Hc=>{Object.defineProperty(Hc,"__esModule",{value:true});var Oa=M(),kn=Oa.operators,Ta={maximum:{okStr:"<=",ok:kn.LTE,fail:kn.GT},minimum:{okStr:">=",ok:kn.GTE,fail:kn.LT},exclusiveMaximum:{okStr:"<",ok:kn.LT,fail:kn.GTE},exclusiveMinimum:{okStr:">",ok:kn.GT,fail:kn.LTE}},qw={message:({keyword:n,schemaCode:e})=>(0, Oa.str)`must be ${Ta[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, Oa._)`{comparison: ${Ta[n].okStr}, limit: ${e}}`},Bw={keyword:Object.keys(Ta),type:"number",schemaType:"number",$data:true,error:qw,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, Oa._)`${t} ${Ta[e].fail} ${r} || isNaN(${t})`);}};Hc.default=Bw;});var ey=w(Jc=>{Object.defineProperty(Jc,"__esModule",{value:true});var Ki=M(),Mw={message:({schemaCode:n})=>(0, Ki.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, Ki._)`{multipleOf: ${n}}`},Ww={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:Mw,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, Ki._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, Ki._)`${s} !== parseInt(${s})`;n.fail$data((0, Ki._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};Jc.default=Ww;});var ny=w(zc=>{Object.defineProperty(zc,"__esModule",{value:true});function ty(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}zc.default=ty;ty.code='require("ajv/dist/runtime/ucs2length").default';});var ry=w(Uc=>{Object.defineProperty(Uc,"__esModule",{value:true});var lr=M(),Gw=Q(),Hw=ny(),Jw={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, lr.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, lr._)`{limit: ${n}}`},zw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:Jw,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?lr.operators.GT:lr.operators.LT,s=i.opts.unicode===false?(0, lr._)`${t}.length`:(0, lr._)`${(0, Gw.useFunc)(n.gen,Hw.default)}(${t})`;n.fail$data((0, lr._)`${s} ${a} ${r}`);}};Uc.default=zw;});var iy=w(Kc=>{Object.defineProperty(Kc,"__esModule",{value:true});var Uw=Pt(),Kw=Q(),Gr=M(),Xw={message:({schemaCode:n})=>(0, Gr.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, Gr._)`{pattern: ${n}}`},Yw={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:Xw,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, Gr._)`new RegExp`:(0, Kw.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, Gr._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, Gr._)`!${c}`);}else {let u=(0, Uw.usePattern)(n,i);n.fail$data((0, Gr._)`!${u}.test(${t})`);}}};Kc.default=Yw;});var sy=w(Xc=>{Object.defineProperty(Xc,"__esModule",{value:true});var Xi=M(),Qw={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Xi.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Xi._)`{limit: ${n}}`},Zw={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:Qw,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Xi.operators.GT:Xi.operators.LT;n.fail$data((0, Xi._)`Object.keys(${t}).length ${i} ${r}`);}};Xc.default=Zw;});var ay=w(Yc=>{Object.defineProperty(Yc,"__esModule",{value:true});var Yi=Pt(),Qi=M(),eA=Q(),tA={message:({params:{missingProperty:n}})=>(0, Qi.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, Qi._)`{missingProperty: ${n}}`},nA={keyword:"required",type:"object",schemaType:"array",$data:true,error:tA,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 g=n.parentSchema.properties,{definedProperties:f}=n.it;for(let m of t)if(g?.[m]===void 0&&!f.has(m)){let b=s.schemaEnv.baseId+s.errSchemaPath,_=`required property "${m}" is not defined at "${b}" (strictRequired)`;(0, eA.checkStrictMode)(s,_,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(Qi.nil,h);else for(let g of t)(0, Yi.checkReportMissingProp)(n,g);}function c(){let g=e.let("missing");if(u||a){let f=e.let("valid",true);n.block$data(f,()=>d(g,f)),n.ok(f);}else e.if((0, Yi.checkMissingProp)(n,t,g)),(0, Yi.reportMissingProp)(n,g),e.else();}function h(){e.forOf("prop",r,g=>{n.setParams({missingProperty:g}),e.if((0, Yi.noPropertyInData)(e,i,g,o.ownProperties),()=>n.error());});}function d(g,f){n.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(f,(0, Yi.propertyInData)(e,i,g,o.ownProperties)),e.if((0, Qi.not)(f),()=>{n.error(),e.break();});},Qi.nil);}}};Yc.default=nA;});var oy=w(Qc=>{Object.defineProperty(Qc,"__esModule",{value:true});var Zi=M(),rA={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, Zi.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, Zi._)`{limit: ${n}}`},iA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:rA,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?Zi.operators.GT:Zi.operators.LT;n.fail$data((0, Zi._)`${t}.length ${i} ${r}`);}};Qc.default=iA;});var Na=w(Zc=>{Object.defineProperty(Zc,"__esModule",{value:true});var uy=gc();uy.code='require("ajv/dist/runtime/equal").default';Zc.default=uy;});var ly=w(th=>{Object.defineProperty(th,"__esModule",{value:true});var eh=ji(),He=M(),sA=Q(),aA=Na(),oA={message:({params:{i:n,j:e}})=>(0, He.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, He._)`{i: ${n}, j: ${e}}`},uA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:oA,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, eh.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, He._)`${s} === false`),n.ok(u);function c(){let f=e.let("i",(0, He._)`${t}.length`),m=e.let("j");n.setParams({i:f,j:m}),e.assign(u,true),e.if((0, He._)`${f} > 1`,()=>(h()?d:g)(f,m));}function h(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function d(f,m){let b=e.name("item"),_=(0, eh.checkDataTypes)(l,b,o.opts.strictNumbers,eh.DataType.Wrong),y=e.const("indices",(0, He._)`{}`);e.for((0, He._)`;${f}--;`,()=>{e.let(b,(0, He._)`${t}[${f}]`),e.if(_,(0, He._)`continue`),l.length>1&&e.if((0, He._)`typeof ${b} == "string"`,(0, He._)`${b} += "_"`),e.if((0, He._)`typeof ${y}[${b}] == "number"`,()=>{e.assign(m,(0, He._)`${y}[${b}]`),n.error(),e.assign(u,false).break();}).code((0, He._)`${y}[${b}] = ${f}`);});}function g(f,m){let b=(0, sA.useFunc)(e,aA.default),_=e.name("outer");e.label(_).for((0, He._)`;${f}--;`,()=>e.for((0, He._)`${m} = ${f}; ${m}--;`,()=>e.if((0, He._)`${b}(${t}[${f}], ${t}[${m}])`,()=>{n.error(),e.assign(u,false).break(_);})));}}};th.default=uA;});var cy=w(rh=>{Object.defineProperty(rh,"__esModule",{value:true});var nh=M(),lA=Q(),cA=Na(),hA={message:"must be equal to constant",params:({schemaCode:n})=>(0, nh._)`{allowedValue: ${n}}`},dA={keyword:"const",$data:true,error:hA,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, nh._)`!${(0, lA.useFunc)(e,cA.default)}(${t}, ${i})`):n.fail((0, nh._)`${a} !== ${t}`);}};rh.default=dA;});var hy=w(ih=>{Object.defineProperty(ih,"__esModule",{value:true});var es=M(),fA=Q(),pA=Na(),mA={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, es._)`{allowedValues: ${n}}`},gA={keyword:"enum",schemaType:"array",$data:true,error:mA,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, fA.useFunc)(e,pA.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 g=e.const("vSchema",a);c=(0, es.or)(...i.map((f,m)=>d(g,m)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,g=>e.if((0, es._)`${l()}(${t}, ${g})`,()=>e.assign(c,true).break()));}function d(g,f){let m=i[f];return typeof m=="object"&&m!==null?(0, es._)`${l()}(${t}, ${g}[${f}])`:(0, es._)`${t} === ${m}`}}};ih.default=gA;});var ah=w(sh=>{Object.defineProperty(sh,"__esModule",{value:true});var yA=Zg(),vA=ey(),CA=ry(),bA=iy(),_A=sy(),SA=ay(),EA=oy(),wA=ly(),AA=cy(),DA=hy(),xA=[yA.default,vA.default,CA.default,bA.default,_A.default,SA.default,EA.default,wA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},AA.default,DA.default];sh.default=xA;});var uh=w(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.validateAdditionalItems=void 0;var cr=M(),oh=Q(),PA={message:({params:{len:n}})=>(0, cr.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, cr._)`{limit: ${n}}`},OA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PA,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, oh.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}dy(n,r);}};function dy(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, cr._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, cr._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, oh.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, cr._)`${o} <= ${e.length}`);t.if((0, cr.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:oh.Type.Num},l),s.allErrors||t.if((0, cr.not)(l),()=>t.break());});}}ts.validateAdditionalItems=dy;ts.default=OA;});var lh=w(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.validateTuple=void 0;var fy=M(),Fa=Q(),TA=Pt(),NA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return py(n,"additionalItems",e);t.items=true,!(0, Fa.alwaysValidSchema)(t,e)&&n.ok((0, TA.validateArray)(n));}};function py(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=Fa.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, fy._)`${a}.length`);t.forEach((h,d)=>{(0, Fa.alwaysValidSchema)(o,h)||(r.if((0, fy._)`${l} > ${d}`,()=>n.subschema({keyword:s,schemaProp:d,dataProp:d},u)),n.ok(u));});function c(h){let{opts:d,errSchemaPath:g}=o,f=t.length,m=f===h.minItems&&(f===h.maxItems||h[e]===false);if(d.strictTuples&&!m){let b=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0, Fa.checkStrictMode)(o,b,d.strictTuples);}}}ns.validateTuple=py;ns.default=NA;});var my=w(ch=>{Object.defineProperty(ch,"__esModule",{value:true});var FA=lh(),IA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, FA.validateTuple)(n,"items")};ch.default=IA;});var yy=w(hh=>{Object.defineProperty(hh,"__esModule",{value:true});var gy=M(),kA=Q(),RA=Pt(),$A=uh(),VA={message:({params:{len:n}})=>(0, gy.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, gy._)`{limit: ${n}}`},jA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:VA,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, kA.alwaysValidSchema)(r,e)&&(i?(0, $A.validateAdditionalItems)(n,i):n.ok((0, RA.validateArray)(n)));}};hh.default=jA;});var vy=w(dh=>{Object.defineProperty(dh,"__esModule",{value:true});var Tt=M(),Ia=Q(),LA={message:({params:{min:n,max:e}})=>e===void 0?(0, Tt.str)`must contain at least ${n} valid item(s)`:(0, Tt.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, Tt._)`{minContains: ${n}}`:(0, Tt._)`{minContains: ${n}, maxContains: ${e}}`},qA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:LA,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, Tt._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, Ia.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, Ia.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, Ia.alwaysValidSchema)(a,t)){let m=(0, Tt._)`${c} >= ${s}`;o!==void 0&&(m=(0, Tt._)`${m} && ${c} <= ${o}`),n.pass(m);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?g(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, Tt._)`${i}.length > 0`,d)):(e.let(h,false),d()),n.result(h,()=>n.reset());function d(){let m=e.name("_valid"),b=e.let("count",0);g(m,()=>e.if(m,()=>f(b)));}function g(m,b){e.forRange("i",0,c,_=>{n.subschema({keyword:"contains",dataProp:_,dataPropType:Ia.Type.Num,compositeRule:true},m),b();});}function f(m){e.code((0, Tt._)`${m}++`),o===void 0?e.if((0, Tt._)`${m} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, Tt._)`${m} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, Tt._)`${m} >= ${s}`,()=>e.assign(h,true)));}}};dh.default=qA;});var ka=w(Zt=>{Object.defineProperty(Zt,"__esModule",{value:true});Zt.validateSchemaDeps=Zt.validatePropertyDeps=Zt.error=void 0;var fh=M(),BA=Q(),rs=Pt();Zt.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, fh.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, fh._)`{property: ${n},
5
+ || ${s} === "boolean" || ${i} === null`).assign(o,(0, G._)`[${i}]`);}}}function iS({gen:n,parentData:e,parentDataProperty:t},r){n.if((0, G._)`${e} !== undefined`,()=>n.assign((0, G._)`${e}[${t}]`,r));}function dc(n,e,t,r=jr.Correct){let i=r===jr.Correct?G.operators.EQ:G.operators.NEQ,a;switch(n){case "null":return (0, G._)`${e} ${i} null`;case "array":a=(0, G._)`Array.isArray(${e})`;break;case "object":a=(0, G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case "integer":a=s((0, G._)`!(${e} % 1) && !isNaN(${e})`);break;case "number":a=s();break;default:return (0, G._)`typeof ${e} ${i} ${n}`}return r===jr.Correct?a:(0, G.not)(a);function s(o=G.nil){return (0, G.and)((0, G._)`typeof ${e} == "number"`,o,t?(0, G._)`isFinite(${e})`:G.nil)}}Xe.checkDataType=dc;function fc(n,e,t,r){if(n.length===1)return dc(n[0],e,t,r);let i,a=(0, $m.toHash)(n);if(a.array&&a.object){let s=(0, G._)`typeof ${e} != "object"`;i=a.null?s:(0, G._)`!${e} || ${s}`,delete a.null,delete a.array,delete a.object;}else i=G.nil;a.number&&delete a.integer;for(let s in a)i=(0, G.and)(i,dc(s,e,t,r));return i}Xe.checkDataTypes=fc;var sS={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:e})=>typeof n=="string"?(0, G._)`{type: ${n}}`:(0, G._)`{type: ${e}}`};function pc(n){let e=aS(n);(0, Z_.reportError)(e,sS);}Xe.reportTypeError=pc;function aS(n){let{gen:e,data:t,schema:r}=n,i=(0, $m.schemaRefOrVal)(n,r,"type");return {gen:e,keyword:"type",data:t,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:n}}});var qm=S(ga=>{Object.defineProperty(ga,"__esModule",{value:true});ga.assignDefaults=void 0;var Lr=M(),oS=Y();function uS(n,e){let{properties:t,items:r}=n.schema;if(e==="object"&&t)for(let i in t)Lm(n,i,t[i].default);else e==="array"&&Array.isArray(r)&&r.forEach((i,a)=>Lm(n,a,i.default));}ga.assignDefaults=uS;function Lm(n,e,t){let{gen:r,compositeRule:i,data:a,opts:s}=n;if(t===void 0)return;let o=(0, Lr._)`${a}${(0, Lr.getProperty)(e)}`;if(i){(0, oS.checkStrictMode)(n,`default is ignored for: ${o}`);return}let u=(0, Lr._)`${o} === undefined`;s.useDefaults==="empty"&&(u=(0, Lr._)`${u} || ${o} === null || ${o} === ""`),r.if(u,(0, Lr._)`${o} = ${(0, Lr.stringify)(t)}`);}});var Pt=S(de=>{Object.defineProperty(de,"__esModule",{value:true});de.validateUnion=de.validateArray=de.usePattern=de.callValidateCode=de.schemaProperties=de.allSchemaProperties=de.noPropertyInData=de.propertyInData=de.isOwnProperty=de.hasPropFunc=de.reportMissingProp=de.checkMissingProp=de.checkReportMissingProp=void 0;var Ee=M(),mc=Y(),Nn=xt(),lS=Y();function cS(n,e){let{gen:t,data:r,it:i}=n;t.if(yc(t,r,e,i.opts.ownProperties),()=>{n.setParams({missingProperty:(0, Ee._)`${e}`},true),n.error();});}de.checkReportMissingProp=cS;function hS({gen:n,data:e,it:{opts:t}},r,i){return (0, Ee.or)(...r.map(a=>(0, Ee.and)(yc(n,e,a,t.ownProperties),(0, Ee._)`${i} = ${a}`)))}de.checkMissingProp=hS;function dS(n,e){n.setParams({missingProperty:e},true),n.error();}de.reportMissingProp=dS;function Bm(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, Ee._)`Object.prototype.hasOwnProperty`})}de.hasPropFunc=Bm;function gc(n,e,t){return (0, Ee._)`${Bm(n)}.call(${e}, ${t})`}de.isOwnProperty=gc;function fS(n,e,t,r){let i=(0, Ee._)`${e}${(0, Ee.getProperty)(t)} !== undefined`;return r?(0, Ee._)`${i} && ${gc(n,e,t)}`:i}de.propertyInData=fS;function yc(n,e,t,r){let i=(0, Ee._)`${e}${(0, Ee.getProperty)(t)} === undefined`;return r?(0, Ee.or)(i,(0, Ee.not)(gc(n,e,t))):i}de.noPropertyInData=yc;function Mm(n){return n?Object.keys(n).filter(e=>e!=="__proto__"):[]}de.allSchemaProperties=Mm;function pS(n,e){return Mm(e).filter(t=>!(0, mc.alwaysValidSchema)(n,e[t]))}de.schemaProperties=pS;function mS({schemaCode:n,data:e,it:{gen:t,topSchemaRef:r,schemaPath:i,errorPath:a},it:s},o,u,l){let c=l?(0, Ee._)`${n}, ${e}, ${r}${i}`:e,h=[[Nn.default.instancePath,(0, Ee.strConcat)(Nn.default.instancePath,a)],[Nn.default.parentData,s.parentData],[Nn.default.parentDataProperty,s.parentDataProperty],[Nn.default.rootData,Nn.default.rootData]];s.opts.dynamicRef&&h.push([Nn.default.dynamicAnchors,Nn.default.dynamicAnchors]);let f=(0, Ee._)`${c}, ${t.object(...h)}`;return u!==Ee.nil?(0, Ee._)`${o}.call(${u}, ${f})`:(0, Ee._)`${o}(${f})`}de.callValidateCode=mS;var gS=(0, Ee._)`new RegExp`;function yS({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, Ee._)`${i.code==="new RegExp"?gS:(0, lS.useFunc)(n,i)}(${t}, ${r})`})}de.usePattern=yS;function vS(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, Ee._)`${t}.length`);e.forRange("i",0,u,l=>{n.subschema({keyword:r,dataProp:l,dataPropType:mc.Type.Num},a),e.if((0, Ee.not)(a),o);});}}de.validateArray=vS;function CS(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, mc.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, Ee._)`${s} || ${o}`),n.mergeValidEvaluated(c,o)||e.if((0, Ee.not)(s));})),n.result(s,()=>n.reset(),()=>n.error(true));}de.validateUnion=CS;});var Hm=S(Kt=>{Object.defineProperty(Kt,"__esModule",{value:true});Kt.validateKeywordUsage=Kt.validSchemaType=Kt.funcKeywordCode=Kt.macroKeywordCode=void 0;var st=M(),ar=xt(),bS=Pt(),_S=qi();function SS(n,e){let{gen:t,keyword:r,schema:i,parentSchema:a,it:s}=n,o=e.macro.call(s.self,i,a,s),u=Gm(t,r,o);s.opts.validateSchema!==false&&s.self.validateSchema(o,true);let l=t.name("valid");n.subschema({schema:o,schemaPath:st.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:u,compositeRule:true},l),n.pass(l,()=>n.error(true));}Kt.macroKeywordCode=SS;function ES(n,e){var t;let{gen:r,keyword:i,schema:a,parentSchema:s,$data:o,it:u}=n;AS(u,e);let l=!o&&e.compile?e.compile.call(u.self,a,s,u):e.validate,c=Gm(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)m(),e.modifying&&Wm(n),C(()=>n.error());else {let b=e.async?g():p();e.modifying&&Wm(n),C(()=>wS(n,b));}}function g(){let b=r.let("ruleErrs",null);return r.try(()=>m((0, st._)`await `),y=>r.assign(h,false).if((0, st._)`${y} instanceof ${u.ValidationError}`,()=>r.assign(b,(0, st._)`${y}.errors`),()=>r.throw(y))),b}function p(){let b=(0, st._)`${c}.errors`;return r.assign(b,null),m(st.nil),b}function m(b=e.async?(0, st._)`await `:st.nil){let y=u.opts.passContext?ar.default.this:ar.default.self,d=!("compile"in e&&!o||e.schema===false);r.assign(h,(0, st._)`${b}${(0, bS.callValidateCode)(n,c,y,d)}`,e.modifying);}function C(b){var y;r.if((0, st.not)((y=e.valid)!==null&&y!==void 0?y:h),b);}}Kt.funcKeywordCode=ES;function Wm(n){let{gen:e,data:t,it:r}=n;e.if(r.parentData,()=>e.assign(t,(0, st._)`${r.parentData}[${r.parentDataProperty}]`));}function wS(n,e){let{gen:t}=n;t.if((0, st._)`Array.isArray(${e})`,()=>{t.assign(ar.default.vErrors,(0, st._)`${ar.default.vErrors} === null ? ${e} : ${ar.default.vErrors}.concat(${e})`).assign(ar.default.errors,(0, st._)`${ar.default.vErrors}.length`),(0, _S.extendErrors)(n);},()=>n.error());}function AS({schemaEnv:n},e){if(e.async&&!n.$async)throw new Error("async keyword in sync schema")}function Gm(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, st.stringify)(t)})}function DS(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")}Kt.validSchemaType=DS;function xS({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)}}Kt.validateKeywordUsage=xS;});var zm=S(Fn=>{Object.defineProperty(Fn,"__esModule",{value:true});Fn.extendSubschemaMode=Fn.extendSubschemaData=Fn.getSubschema=void 0;var Xt=M(),Jm=Y();function PS(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, Xt._)`${n.schemaPath}${(0, Xt.getProperty)(e)}`,errSchemaPath:`${n.errSchemaPath}/${e}`}:{schema:o[t],schemaPath:(0, Xt._)`${n.schemaPath}${(0, Xt.getProperty)(e)}${(0, Xt.getProperty)(t)}`,errSchemaPath:`${n.errSchemaPath}/${e}/${(0, Jm.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')}Fn.getSubschema=PS;function OS(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, Xt._)`${e.data}${(0, Xt.getProperty)(t)}`,true);u(f),n.errorPath=(0, Xt.str)`${l}${(0, Jm.getErrorPath)(t,r,h.jsPropertySyntax)}`,n.parentDataProperty=(0, Xt._)`${t}`,n.dataPathArr=[...c,n.parentDataProperty];}if(i!==void 0){let l=i instanceof Xt.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];}}Fn.extendSubschemaData=OS;function TS(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;}Fn.extendSubschemaMode=TS;});var vc=S((B$,Um)=>{Um.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 Xm=S((M$,Km)=>{var In=Km.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(){};ya(e,r,i,n,"",n);};In.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};In.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};In.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};In.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 ya(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 In.arrayKeywords)for(var f=0;f<h.length;f++)ya(n,e,t,h[f],i+"/"+c+"/"+f,a,i,c,r,f);}else if(c in In.propsKeywords){if(h&&typeof h=="object")for(var g in h)ya(n,e,t,h[g],i+"/"+c+"/"+NS(g),a,i,c,r,g);}else (c in In.keywords||n.allKeys&&!(c in In.skipKeywords))&&ya(n,e,t,h,i+"/"+c,a,i,c,r);}t(r,i,a,s,o,u,l);}}function NS(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}});var Mi=S(ht=>{Object.defineProperty(ht,"__esModule",{value:true});ht.getSchemaRefs=ht.resolveUrl=ht.normalizeId=ht._getFullPath=ht.getFullPath=ht.inlineRef=void 0;var FS=Y(),IS=vc(),kS=Xm(),RS=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function $S(n,e=true){return typeof n=="boolean"?true:e===true?!Cc(n):e?Ym(n)<=e:false}ht.inlineRef=$S;var VS=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Cc(n){for(let e in n){if(VS.has(e))return true;let t=n[e];if(Array.isArray(t)&&t.some(Cc)||typeof t=="object"&&Cc(t))return true}return false}function Ym(n){let e=0;for(let t in n){if(t==="$ref")return 1/0;if(e++,!RS.has(t)&&(typeof n[t]=="object"&&(0, FS.eachItem)(n[t],r=>e+=Ym(r)),e===1/0))return 1/0}return e}function Qm(n,e="",t){t!==false&&(e=qr(e));let r=n.parse(e);return Zm(n,r)}ht.getFullPath=Qm;function Zm(n,e){return n.serialize(e).split("#")[0]+"#"}ht._getFullPath=Zm;var jS=/#\/?$/;function qr(n){return n?n.replace(jS,""):""}ht.normalizeId=qr;function LS(n,e,t){return t=qr(t),n.resolve(e,t)}ht.resolveUrl=LS;var qS=/^[a-z_][-a-z0-9._]*$/i;function BS(n,e){if(typeof n=="boolean")return {};let{schemaId:t,uriResolver:r}=this.opts,i=qr(n[t]||e),a={"":i},s=Qm(r,i,false),o={},u=new Set;return kS(n,{allKeys:true},(h,f,g,p)=>{if(p===void 0)return;let m=s+f,C=a[p];typeof h[t]=="string"&&(C=b.call(this,h[t])),y.call(this,h.$anchor),y.call(this,h.$dynamicAnchor),a[f]=C;function b(d){let _=this.opts.uriResolver.resolve;if(d=qr(C?_(C,d):d),u.has(d))throw c(d);u.add(d);let v=this.refs[d];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(h,v.schema,d):d!==qr(m)&&(d[0]==="#"?(l(h,o[d],d),o[d]=h):this.refs[d]=m),d}function y(d){if(typeof d=="string"){if(!qS.test(d))throw new Error(`invalid anchor "${d}"`);b.call(this,`#${d}`);}}}),o;function l(h,f,g){if(f!==void 0&&!IS(h,f))throw c(g)}function c(h){return new Error(`reference "${h}" resolves to more than one schema`)}}ht.getSchemaRefs=BS;});var Br=S(kn=>{Object.defineProperty(kn,"__esModule",{value:true});kn.getData=kn.KeywordCxt=kn.validateFunctionCode=void 0;var ig=Im(),eg=Bi(),_c=hc(),va=Bi(),MS=qm(),Gi=Hm(),bc=zm(),$=M(),q=xt(),WS=Mi(),yn=Y(),Wi=qi();function GS(n){if(og(n)&&(ug(n),ag(n))){zS(n);return}sg(n,()=>(0, ig.topBoolOrEmptySchema)(n));}kn.validateFunctionCode=GS;function sg({gen:n,validateName:e,schema:t,schemaEnv:r,opts:i},a){i.code.es5?n.func(e,(0, $._)`${q.default.data}, ${q.default.valCxt}`,r.$async,()=>{n.code((0, $._)`"use strict"; ${tg(t,i)}`),JS(n,i),n.code(a);}):n.func(e,(0, $._)`${q.default.data}, ${HS(i)}`,r.$async,()=>n.code(tg(t,i)).code(a));}function HS(n){return (0, $._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${n.dynamicRef?(0, $._)`, ${q.default.dynamicAnchors}={}`:$.nil}}={}`}function JS(n,e){n.if(q.default.valCxt,()=>{n.var(q.default.instancePath,(0, $._)`${q.default.valCxt}.${q.default.instancePath}`),n.var(q.default.parentData,(0, $._)`${q.default.valCxt}.${q.default.parentData}`),n.var(q.default.parentDataProperty,(0, $._)`${q.default.valCxt}.${q.default.parentDataProperty}`),n.var(q.default.rootData,(0, $._)`${q.default.valCxt}.${q.default.rootData}`),e.dynamicRef&&n.var(q.default.dynamicAnchors,(0, $._)`${q.default.valCxt}.${q.default.dynamicAnchors}`);},()=>{n.var(q.default.instancePath,(0, $._)`""`),n.var(q.default.parentData,(0, $._)`undefined`),n.var(q.default.parentDataProperty,(0, $._)`undefined`),n.var(q.default.rootData,q.default.data),e.dynamicRef&&n.var(q.default.dynamicAnchors,(0, $._)`{}`);});}function zS(n){let{schema:e,opts:t,gen:r}=n;sg(n,()=>{t.$comment&&e.$comment&&cg(n),QS(n),r.let(q.default.vErrors,null),r.let(q.default.errors,0),t.unevaluated&&US(n),lg(n),tE(n);});}function US(n){let{gen:e,validateName:t}=n;n.evaluated=e.const("evaluated",(0, $._)`${t}.evaluated`),e.if((0, $._)`${n.evaluated}.dynamicProps`,()=>e.assign((0, $._)`${n.evaluated}.props`,(0, $._)`undefined`)),e.if((0, $._)`${n.evaluated}.dynamicItems`,()=>e.assign((0, $._)`${n.evaluated}.items`,(0, $._)`undefined`));}function tg(n,e){let t=typeof n=="object"&&n[e.schemaId];return t&&(e.code.source||e.code.process)?(0, $._)`/*# sourceURL=${t} */`:$.nil}function KS(n,e){if(og(n)&&(ug(n),ag(n))){XS(n,e);return}(0, ig.boolOrEmptySchema)(n,e);}function ag({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 og(n){return typeof n.schema!="boolean"}function XS(n,e){let{schema:t,gen:r,opts:i}=n;i.$comment&&t.$comment&&cg(n),ZS(n),eE(n);let a=r.const("_errs",q.default.errors);lg(n,a),r.var(e,(0, $._)`${a} === ${q.default.errors}`);}function ug(n){(0, yn.checkUnknownRules)(n),YS(n);}function lg(n,e){if(n.opts.jtd)return ng(n,[],false,e);let t=(0, eg.getSchemaTypes)(n.schema),r=(0, eg.coerceAndCheckDataType)(n,t);ng(n,t,!r,e);}function YS(n){let{schema:e,errSchemaPath:t,opts:r,self:i}=n;e.$ref&&r.ignoreKeywordsWithRef&&(0, yn.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`);}function QS(n){let{schema:e,opts:t}=n;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0, yn.checkStrictMode)(n,"default is ignored in the schema root");}function ZS(n){let e=n.schema[n.opts.schemaId];e&&(n.baseId=(0, WS.resolveUrl)(n.opts.uriResolver,n.baseId,e));}function eE(n){if(n.schema.$async&&!n.schemaEnv.$async)throw new Error("async schema in sync schema")}function cg({gen:n,schemaEnv:e,schema:t,errSchemaPath:r,opts:i}){let a=t.$comment;if(i.$comment===true)n.code((0, $._)`${q.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let s=(0, $.str)`${r}/$comment`,o=n.scopeValue("root",{ref:e.root});n.code((0, $._)`${q.default.self}.opts.$comment(${a}, ${s}, ${o}.schema)`);}}function tE(n){let{gen:e,schemaEnv:t,validateName:r,ValidationError:i,opts:a}=n;t.$async?e.if((0, $._)`${q.default.errors} === 0`,()=>e.return(q.default.data),()=>e.throw((0, $._)`new ${i}(${q.default.vErrors})`)):(e.assign((0, $._)`${r}.errors`,q.default.vErrors),a.unevaluated&&nE(n),e.return((0, $._)`${q.default.errors} === 0`));}function nE({gen:n,evaluated:e,props:t,items:r}){t instanceof $.Name&&n.assign((0, $._)`${e}.props`,t),r instanceof $.Name&&n.assign((0, $._)`${e}.items`,r);}function ng(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, yn.schemaHasRulesButRef)(a,c))){i.block(()=>dg(n,"$ref",c.all.$ref.definition));return}u.jtd||rE(n,e),i.block(()=>{for(let f of c.rules)h(f);h(c.post);});function h(f){(0, _c.shouldUseGroup)(a,f)&&(f.type?(i.if((0, va.checkDataType)(f.type,s,u.strictNumbers)),rg(n,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0, va.reportTypeError)(n)),i.endIf()):rg(n,f),o||i.if((0, $._)`${q.default.errors} === ${r||0}`));}}function rg(n,e){let{gen:t,schema:r,opts:{useDefaults:i}}=n;i&&(0, MS.assignDefaults)(n,e.type),t.block(()=>{for(let a of e.rules)(0, _c.shouldUseRule)(r,a)&&dg(n,a.keyword,a.definition,e.type);});}function rE(n,e){n.schemaEnv.meta||!n.opts.strictTypes||(iE(n,e),n.opts.allowUnionTypes||sE(n,e),aE(n,n.dataTypes));}function iE(n,e){if(e.length){if(!n.dataTypes.length){n.dataTypes=e;return}e.forEach(t=>{hg(n.dataTypes,t)||Sc(n,`type "${t}" not allowed by context "${n.dataTypes.join(",")}"`);}),uE(n,e);}}function sE(n,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Sc(n,"use allowUnionTypes to allow union type keyword");}function aE(n,e){let t=n.self.RULES.all;for(let r in t){let i=t[r];if(typeof i=="object"&&(0, _c.shouldUseRule)(n.schema,i)){let{type:a}=i.definition;a.length&&!a.some(s=>oE(e,s))&&Sc(n,`missing type "${a.join(",")}" for keyword "${r}"`);}}}function oE(n,e){return n.includes(e)||e==="number"&&n.includes("integer")}function hg(n,e){return n.includes(e)||e==="integer"&&n.includes("number")}function uE(n,e){let t=[];for(let r of n.dataTypes)hg(e,r)?t.push(r):e.includes("integer")&&r==="number"&&t.push("integer");n.dataTypes=t;}function Sc(n,e){let t=n.schemaEnv.baseId+n.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0, yn.checkStrictMode)(n,e,n.opts.strictTypes);}var Ca=class{constructor(e,t,r){if((0, Gi.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, yn.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",fg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0, Gi.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",q.default.errors));}result(e,t,r){this.failResult((0, $.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, $.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, $._)`${t} !== undefined && (${(0, $.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?Wi.reportExtraError:Wi.reportError)(this,this.def.error,t);}$dataError(){(0, Wi.reportError)(this,this.def.$dataError||Wi.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, Wi.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=$.nil){this.gen.block(()=>{this.check$data(e,r),t();});}check$data(e=$.nil,t=$.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:a,def:s}=this;r.if((0, $.or)((0, $._)`${i} === undefined`,t)),e!==$.nil&&r.assign(e,true),(a.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==$.nil&&r.assign(e,false)),r.else();}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:a}=this;return (0, $.or)(s(),o());function s(){if(r.length){if(!(t instanceof $.Name))throw new Error("ajv implementation error");let u=Array.isArray(r)?r:[r];return (0, $._)`${(0, va.checkDataTypes)(u,t,a.opts.strictNumbers,va.DataType.Wrong)}`}return $.nil}function o(){if(i.validateSchema){let u=e.scopeValue("validate$data",{ref:i.validateSchema});return (0, $._)`!${u}(${t})`}return $.nil}}subschema(e,t){let r=(0, bc.getSubschema)(this.it,e);(0, bc.extendSubschemaData)(r,this.it,e),(0, bc.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return KS(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==true&&e.props!==void 0&&(r.props=yn.mergeEvaluated.props(i,e.props,r.props,t)),r.items!==true&&e.items!==void 0&&(r.items=yn.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,$.Name)),true}};kn.KeywordCxt=Ca;function dg(n,e,t,r){let i=new Ca(n,t,e);"code"in t?t.code(i,r):i.$data&&t.validate?(0, Gi.funcKeywordCode)(i,t):"macro"in t?(0, Gi.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0, Gi.funcKeywordCode)(i,t);}var lE=/^\/(?:[^~]|~0|~1)*$/,cE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fg(n,{dataLevel:e,dataNames:t,dataPathArr:r}){let i,a;if(n==="")return q.default.rootData;if(n[0]==="/"){if(!lE.test(n))throw new Error(`Invalid JSON-pointer: ${n}`);i=n,a=q.default.rootData;}else {let l=cE.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}${(0, $.getProperty)((0, yn.unescapeJsonPointer)(l))}`,s=(0, $._)`${s} && ${a}`);return s;function u(l,c){return `Cannot access ${l} ${c} levels up, current level is ${e}`}}kn.getData=fg;});var Hi=S(wc=>{Object.defineProperty(wc,"__esModule",{value:true});var Ec=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=true;}};wc.default=Ec;});var Mr=S(xc=>{Object.defineProperty(xc,"__esModule",{value:true});var Ac=Mi(),Dc=class extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0, Ac.resolveUrl)(e,t,r),this.missingSchema=(0, Ac.normalizeId)((0, Ac.getFullPath)(e,this.missingRef));}};xc.default=Dc;});var Ji=S(Ot=>{Object.defineProperty(Ot,"__esModule",{value:true});Ot.resolveSchema=Ot.getCompilingSchema=Ot.resolveRef=Ot.compileSchema=Ot.SchemaEnv=void 0;var qt=M(),hE=Hi(),or=xt(),Bt=Mi(),pg=Y(),dE=Br(),Wr=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, Bt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={};}};Ot.SchemaEnv=Wr;function Oc(n){let e=mg.call(this,n);if(e)return e;let t=(0, Bt.getFullPath)(this.opts.uriResolver,n.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:a}=this.opts,s=new qt.CodeGen(this.scope,{es5:r,lines:i,ownProperties:a}),o;n.$async&&(o=s.scopeValue("Error",{ref:hE.default,code:(0, qt._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");n.validateName=u;let l={gen:s,allErrors:this.opts.allErrors,data:or.default.data,parentData:or.default.parentData,parentDataProperty:or.default.parentDataProperty,dataNames:[or.default.data],dataPathArr:[qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===true?{ref:n.schema,code:(0, qt.stringify)(n.schema)}:{ref:n.schema}),validateName:u,ValidationError:o,schema:n.schema,schemaEnv:n,rootId:t,baseId:n.baseId||t,schemaPath:qt.nil,errSchemaPath:n.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, qt._)`""`,opts:this.opts,self:this},c;try{this._compilations.add(n),(0,dE.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let h=s.toString();c=`${s.scopeRefs(or.default.scope)}return ${h}`,this.opts.code.process&&(c=this.opts.code.process(c,n));let g=new Function(`${or.default.self}`,`${or.default.scope}`,c)(this,this.scope.get());if(this.scope.value(u,{ref:g}),g.errors=null,g.schema=n.schema,g.schemaEnv=n,n.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:u,validateCode:h,scopeValues:s._values}),this.opts.unevaluated){let{props:p,items:m}=l;g.evaluated={props:p instanceof qt.Name?void 0:p,items:m instanceof qt.Name?void 0:m,dynamicProps:p instanceof qt.Name,dynamicItems:m instanceof qt.Name},g.source&&(g.source.evaluated=(0,qt.stringify)(g.evaluated));}return n.validate=g,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);}}Ot.compileSchema=Oc;function fE(n,e,t){var r;t=(0, Bt.resolveUrl)(this.opts.uriResolver,e,t);let i=n.refs[t];if(i)return i;let a=gE.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 Wr({schema:s,schemaId:o,root:n,baseId:e}));}if(a!==void 0)return n.refs[t]=pE.call(this,a)}Ot.resolveRef=fE;function pE(n){return (0, Bt.inlineRef)(n.schema,this.opts.inlineRefs)?n.schema:n.validate?n:Oc.call(this,n)}function mg(n){for(let e of this._compilations)if(mE(e,n))return e}Ot.getCompilingSchema=mg;function mE(n,e){return n.schema===e.schema&&n.root===e.root&&n.baseId===e.baseId}function gE(n,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||ba.call(this,n,e)}function ba(n,e){let t=this.opts.uriResolver.parse(e),r=(0, Bt._getFullPath)(this.opts.uriResolver,t),i=(0, Bt.getFullPath)(this.opts.uriResolver,n.baseId,void 0);if(Object.keys(n.schema).length>0&&r===i)return Pc.call(this,t,n);let a=(0, Bt.normalizeId)(r),s=this.refs[a]||this.schemas[a];if(typeof s=="string"){let o=ba.call(this,n,s);return typeof o?.schema!="object"?void 0:Pc.call(this,t,o)}if(typeof s?.schema=="object"){if(s.validate||Oc.call(this,s),a===(0, Bt.normalizeId)(e)){let{schema:o}=s,{schemaId:u}=this.opts,l=o[u];return l&&(i=(0, Bt.resolveUrl)(this.opts.uriResolver,i,l)),new Wr({schema:o,schemaId:u,root:n,baseId:i})}return Pc.call(this,t,s)}}Ot.resolveSchema=ba;var yE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Pc(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, pg.unescapeFragment)(o)];if(u===void 0)return;t=u;let l=typeof t=="object"&&t[this.opts.schemaId];!yE.has(o)&&l&&(e=(0, Bt.resolveUrl)(this.opts.uriResolver,e,l));}let a;if(typeof t!="boolean"&&t.$ref&&!(0, pg.schemaHasRulesButRef)(t,this.RULES)){let o=(0, Bt.resolveUrl)(this.opts.uriResolver,e,t.$ref);a=ba.call(this,r,o);}let{schemaId:s}=this.opts;if(a=a||new Wr({schema:t,schemaId:s,root:r,baseId:e}),a.schema!==a.root.schema)return a}});var gg=S((U$,vE)=>{vE.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 Rc=S((K$,Eg)=>{var CE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Nc=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),bE=RegExp.prototype.test.bind(/^\d*$/u),ur=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Fc=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),vg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Ic=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),_E=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),dt=new Array(256);{let n="0123456789ABCDEF";for(let e=0;e<256;e++)dt[e]="%"+n[e>>4]+n[e&15];}function Ye(n){return n<2048?dt[192|n>>6]+dt[128|n&63]:n<65536?dt[224|n>>12]+dt[128|n>>6&63]+dt[128|n&63]:dt[240|n>>18]+dt[128|n>>12&63]+dt[128|n>>6&63]+dt[128|n&63]}function SE(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 EE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),wE=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),AE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),DE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function xE(n){if(n.length===0)return false;for(let e=0;e<n.length;e++)if(!AE(n[e])){if(n[e]==="%"&&e+2<n.length&&ur(n.slice(e+1,e+3))){e+=2;continue}return false}return true}function yg(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 PE(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||!Nc(u))return;a+=2;continue}if(!EE(u))return;i[o]=parseInt(u,16).toString(16),a++;}if(e===-1)return a!==8?void 0:yg(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 yg(s)}function Tc(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&&wE(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:false,isIPVFuture:true};if(OE(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),!xE(i))return {host:n,isIPV6:false,error:true};r=r.slice(0,a);}let s=PE(r);return s===void 0?{host:n,isIPV6:false,error:true}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:true}}function OE(n,e){let t=0;for(let r=0;r<n.length;r++)n[r]===e&&t++;return t}function TE(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 NE={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},FE=/[@/?#:]/g,IE=/[@/?#]/g;function Cg(n,e){let t=e?IE:FE;return t.lastIndex=0,n.replace(t,r=>NE[r])}function bg(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(ur(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));e&&Fc(s)?t+=s:t+="%"+a,r+=2;continue}}t+=n[r];}return t}function kE(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(ur(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));s!=="."&&Fc(s)?e+=s:e+="%"+a,t+=2;continue}}if(vg(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Sg(i)?r:dt[i];else if(i<55296||i>57343)e+=Ye(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Ye(65536+(i-55296<<10)+(a-56320)),t++):e+=Ye(65533);}else e+=Ye(65533);}}return e}function RE(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(ur(s)){t+="%"+s.toUpperCase(),i+=2;continue}}if(a==="/"&&(r=false),vg(a)&&(a!==":"||!r))t+=a;else {let s=n.charCodeAt(i);if(s<128)t+=dt[s];else if(s<55296||s>57343)t+=Ye(s);else if(s<=56319&&i+1<n.length){let o=n.charCodeAt(i+1);o>=56320&&o<=57343?(t+=Ye(65536+(s-55296<<10)+(o-56320)),i++):t+=Ye(65533);}else t+=Ye(65533);}}return t}function kc(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(ur(a)){t+="%"+a.toUpperCase(),r+=2;continue}}if(e(i))t+=i;else {let a=n.charCodeAt(r);if(a<128)t+=dt[a];else if(a<55296||a>57343)t+=Ye(a);else if(a<=56319&&r+1<n.length){let s=n.charCodeAt(r+1);s>=56320&&s<=57343?(t+=Ye(65536+(a-55296<<10)+(s-56320)),r++):t+=Ye(65533);}else t+=Ye(65533);}}return t}function _g(n){return kc(n,_E)}function $E(n){return kc(n,Ic)}function VE(n){return kc(n,Ic)}function Sg(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 jE(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(ur(i)){let a=i.toUpperCase(),s=String.fromCharCode(parseInt(a,16));Fc(s)?e+=s:e+="%"+a,t+=2;continue}}if(Ic(r))e+=r;else {let i=n.charCodeAt(t);if(i<128)e+=Sg(i)?r:dt[i];else if(i<55296||i>57343)e+=Ye(i);else if(i<=56319&&t+1<n.length){let a=n.charCodeAt(t+1);a>=56320&&a<=57343?(e+=Ye(65536+(i-55296<<10)+(a-56320)),t++):e+=Ye(65533);}else e+=Ye(65533);}}return e}function LE(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(ur(r)){e+="%"+r.toUpperCase(),t+=2;continue}}e+=escape(n[t]);}return e}function qE(n){let e=[];if(n.userinfo!==void 0&&(e.push(_g(n.userinfo)),e.push("@")),n.host!==void 0){let t=n.host;if(!Nc(t)){let r=Tc(t);r.isIPV6!==true&&r.isIPVFuture!==true&&(t=bg(t,true),r=Tc(t)),r.isIPV6===true||r.isIPVFuture===true?t=`[${r.escapedHost}]`:t=Cg(t,false);}e.push(t);}if(typeof n.port=="number"||typeof n.port=="string"){let t=String(n.port);if(!bE(t))throw new TypeError("URI port is malformed.");e.push(":"),e.push(t);}return e.length?e.join(""):void 0}Eg.exports={nonSimpleDomain:DE,recomposeAuthority:qE,reescapeHostDelimiters:Cg,normalizePercentEncoding:bg,normalizePathEncoding:kE,serializePathEncoding:RE,normalizeQueryFragmentEncoding:jE,encodeUserinfo:_g,encodeQuery:$E,encodeFragment:VE,escapePreservingEscapes:LE,removeDotSegments:TE,isIPv4:Nc,isUUID:CE,normalizeIPv6:Tc,stringArrayToHexStripped:SE};});var Pg=S((X$,xg)=>{var{isUUID:BE}=Rc(),ME=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,WE=["http","https","ws","wss","urn","urn:uuid"];function GE(n){return WE.indexOf(n)!==-1}function $c(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 wg(n){return n.host||(n.error=n.error||"HTTP URIs must have a host."),n}function Ag(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 HE(n){return n.secure=$c(n),n.resourceName=(n.path||"/")+(n.query?"?"+n.query:""),n.path=void 0,n.query=void 0,n}function JE(n){if((n.port===($c(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 zE(n,e){if(!n.path)return n.error="URN can not be parsed",n;let t=n.path.match(ME);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=Vc(i);n.path=void 0,a&&(n=a.parse(n,e));}else n.error=n.error||"URN can not be parsed.";return n}function UE(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=Vc(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 KE(n,e){let t=n;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!BE(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function XE(n){let e=n;return e.nss=(n.uuid||"").toLowerCase(),e}var Dg={scheme:"http",domainHost:true,parse:wg,serialize:Ag},YE={scheme:"https",domainHost:Dg.domainHost,parse:wg,serialize:Ag},_a={scheme:"ws",domainHost:true,parse:HE,serialize:JE},QE={scheme:"wss",domainHost:_a.domainHost,parse:_a.parse,serialize:_a.serialize},ZE={scheme:"urn",parse:zE,serialize:UE,skipNormalize:true},ew={scheme:"urn:uuid",parse:KE,serialize:XE,skipNormalize:true},Sa={http:Dg,https:YE,ws:_a,wss:QE,urn:ZE,"urn:uuid":ew};Object.setPrototypeOf(Sa,null);function Vc(n){return n&&(Sa[n]||Sa[n.toLowerCase()])||void 0}xg.exports={wsIsSecure:$c,SCHEMES:Sa,isValidSchemeName:GE,getSchemeHandler:Vc};});var Bg=S((Y$,Aa)=>{var{normalizeIPv6:Ig,removeDotSegments:Ui,recomposeAuthority:tw,normalizePercentEncoding:jc,normalizePathEncoding:nw,serializePathEncoding:Og,normalizeQueryFragmentEncoding:Tg,encodeQuery:rw,encodeFragment:iw,reescapeHostDelimiters:sw,isIPv4:kg,nonSimpleDomain:aw}=Rc(),{SCHEMES:Rg,getSchemeHandler:Lc}=Pg(),$g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Vg="URI scheme is malformed.";function Ng(n){let e=unescape(String(n));if(!$g.test(e))throw new TypeError(Vg);return e}function ow(n,e){return typeof n=="string"?n=mw(n,e):typeof n=="object"&&(n=wa(lr(n,e),e)),n}function uw(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}=Ea(n,r),{parsed:c,malformedAuthorityOrPort:h,malformedPercentEncoding:f,malformedSchemeSpecific:g,malformedHost:p,malformedScheme:m}=Ea(e,r);if(a||h||s||f||o||g||u||p||l||m)throw new Error(i.error||c.error||"URI is malformed.");let C=jg(i,c,r,true),b=Lc(t&&t.scheme||C.scheme),y=C.host,d=y!==void 0&&y!==""&&(kg(y)||Ig(y).isIPV6);Lg(C,t||{},b,d);let _=y&&y.indexOf("%")!==-1&&!/\P{ASCII}/u.test(y);if(C.error&&!_)throw new Error(C.error);return r.skipEscape=true,lr(C,r)}function jg(n,e,t,r){let i={};return r||(n=wa(lr(n,t),t),e=wa(lr(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=Ui(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=Ui(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Ui(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=Ui(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 lw(n,e,t){let r=Fg(n,t),i=Fg(e,t);return r!==void 0&&i!==void 0&&r===i}function lr(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=Ng(t.scheme));let a=Lc(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=jc(t.path):t.path=Og(t.path,o)),r.reference!=="suffix"&&t.scheme&&(t.scheme=Ng(t.scheme),i.push(t.scheme,":"));let u=tw(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=Ui(l)),o&&(l=Og(l,true)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l);}return t.query!==void 0&&i.push("?",rw(t.query)),t.fragment!==void 0&&i.push("#",iw(t.fragment)),i.join("")}var cw=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,hw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,dw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function fw(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 zi(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 qc(n){return n[0]==="["&&n[n.length-1]==="]"}function pw(n){let e=n[4];return zi(n[3])||e!==void 0&&!qc(e)&&zi(e)||zi(n[6])||zi(n[7])||zi(n[8])}function Lg(n,e,t,r){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&n.host&&!qc(n.host)&&(e.domainHost||t&&t.domainHost)&&r===false&&aw(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 Ea(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(hw);h!==null&&h[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=true);let f=n.match(dw);if(f!==null){let p=f[1],m=p.replace(/[\t\n\r]/g,"");m.length>=2&&(m.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=true):p.length!==m.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=true));}let g=n.match(cw);if(g){if(r.scheme=g[1],r.userinfo=g[3],r.host=g[4],r.port=parseInt(g[5],10),r.path=g[6]||"",r.query=g[7],r.fragment=g[8],r.scheme!==void 0){let C=unescape(r.scheme);$g.test(C)?r.scheme=C.toLowerCase():(r.error=r.error||Vg,l=true);}a=pw(g),a&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=g[5]);let p=fw(r,g);if(p!==void 0&&(r.error=r.error||p,i=true),r.host)if(kg(r.host)===false){let b=qc(r.host),y=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,d=Ig(r.host);c=d.isIPV6||d.isIPVFuture===true,u=y&&(!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 m=Lc(t.scheme||r.scheme);if(u||(o=Lg(r,t,m,c)),n.indexOf("%")!==-1&&r.host!==void 0&&!u){let C=c?r.host:jc(r.host,true);c||(C=jc(C.toLowerCase())),r.host=sw(C,c);}(!m||m&&!m.skipNormalize)&&(r.path&&(r.path=nw(r.path)),r.query&&(r.query=Tg(r.query)),r.fragment&&(r.fragment=Tg(r.fragment))),m&&m.parse&&(m.parse(r,t),m===Rg.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 wa(n,e){return Ea(n,e).parsed}function mw(n,e){return qg(n,e).normalized}function qg(n,e){let{parsed:t,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}=Ea(n,e);return {normalized:r||i||a||s||o?n:lr(t,e),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:s,malformedScheme:o}}function Fg(n,e){if(typeof n!="string"&&typeof n!="object")return;let t;try{t=typeof n=="string"?n:lr(n,e);}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:u}=qg(t,e);return i||a||s||o||u?void 0:r}var Bc={SCHEMES:Rg,normalize:ow,resolve:uw,resolveComponent:jg,equal:lw,serialize:lr,parse:wa};Aa.exports=Bc;Aa.exports.default=Bc;Aa.exports.fastUri=Bc;});var Wg=S(Mc=>{Object.defineProperty(Mc,"__esModule",{value:true});var Mg=Bg();Mg.code='require("ajv/dist/runtime/uri").default';Mc.default=Mg;});var Hc=S(He=>{Object.defineProperty(He,"__esModule",{value:true});He.CodeGen=He.Name=He.nil=He.stringify=He.str=He._=He.KeywordCxt=void 0;var gw=Br();Object.defineProperty(He,"KeywordCxt",{enumerable:true,get:function(){return gw.KeywordCxt}});var Gr=M();Object.defineProperty(He,"_",{enumerable:true,get:function(){return Gr._}});Object.defineProperty(He,"str",{enumerable:true,get:function(){return Gr.str}});Object.defineProperty(He,"stringify",{enumerable:true,get:function(){return Gr.stringify}});Object.defineProperty(He,"nil",{enumerable:true,get:function(){return Gr.nil}});Object.defineProperty(He,"Name",{enumerable:true,get:function(){return Gr.Name}});Object.defineProperty(He,"CodeGen",{enumerable:true,get:function(){return Gr.CodeGen}});var yw=Hi(),Ug=Mr(),vw=cc(),Ki=Ji(),Cw=M(),Xi=Mi(),Da=Bi(),Gc=Y(),Gg=gg(),bw=Wg(),Kg=(n,e)=>new RegExp(n,e);Kg.code="new RegExp";var _w=["removeAdditional","useDefaults","coerceTypes"],Sw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Ew={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."},ww={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Hg=200;function Aw(n){var e,t,r,i,a,s,o,u,l,c,h,f,g,p,m,C,b,y,d,_,v,w,D,O,P;let E=n.strict,F=(e=n.code)===null||e===void 0?void 0:e.optimize,R=F===true||F===void 0?1:F||0,k=(r=(t=n.code)===null||t===void 0?void 0:t.regExp)!==null&&r!==void 0?r:Kg,A=(i=n.uriResolver)!==null&&i!==void 0?i:bw.default;return {strictSchema:(s=(a=n.strictSchema)!==null&&a!==void 0?a:E)!==null&&s!==void 0?s:true,strictNumbers:(u=(o=n.strictNumbers)!==null&&o!==void 0?o:E)!==null&&u!==void 0?u:true,strictTypes:(c=(l=n.strictTypes)!==null&&l!==void 0?l:E)!==null&&c!==void 0?c:"log",strictTuples:(f=(h=n.strictTuples)!==null&&h!==void 0?h:E)!==null&&f!==void 0?f:"log",strictRequired:(p=(g=n.strictRequired)!==null&&g!==void 0?g:E)!==null&&p!==void 0?p:false,code:n.code?{...n.code,optimize:R,regExp:k}:{optimize:R,regExp:k},loopRequired:(m=n.loopRequired)!==null&&m!==void 0?m:Hg,loopEnum:(C=n.loopEnum)!==null&&C!==void 0?C:Hg,meta:(b=n.meta)!==null&&b!==void 0?b:true,messages:(y=n.messages)!==null&&y!==void 0?y:true,inlineRefs:(d=n.inlineRefs)!==null&&d!==void 0?d:true,schemaId:(_=n.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(v=n.addUsedSchema)!==null&&v!==void 0?v:true,validateSchema:(w=n.validateSchema)!==null&&w!==void 0?w:true,validateFormats:(D=n.validateFormats)!==null&&D!==void 0?D:true,unicodeRegExp:(O=n.unicodeRegExp)!==null&&O!==void 0?O:true,int32range:(P=n.int32range)!==null&&P!==void 0?P:true,uriResolver:A}}var Yi=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,...Aw(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new Cw.ValueScope({scope:{},prefixes:Sw,es5:t,lines:r}),this.logger=Nw(e.logger);let i=e.validateFormats;e.validateFormats=false,this.RULES=(0, vw.getRules)(),Jg.call(this,Ew,e,"NOT SUPPORTED"),Jg.call(this,ww,e,"DEPRECATED","warn"),this._metaOpts=Ow.call(this),e.formats&&xw.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Pw.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Dw.call(this),e.validateFormats=i;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=Gg;r==="id"&&(i={...Gg},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 Ug.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, Xi.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=zg.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new Ki.SchemaEnv({schema:{},schemaId:r});if(t=Ki.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=zg.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, Xi.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(Iw.call(this,r,t),!t)return (0, Gc.eachItem)(r,a=>Wc.call(this,a)),this;Rw.call(this,t);let i={...t,type:(0, Da.getJSONTypes)(t.type),schemaType:(0, Da.getJSONTypes)(t.schemaType)};return (0, Gc.eachItem)(r,i.type.length===0?a=>Wc.call(this,a,i):a=>i.type.forEach(s=>Wc.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]=Xg(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, Xi.normalizeId)(s||r);let l=Xi.getSchemaRefs.call(this,e,r);return u=new Ki.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):Ki.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{Ki.compileSchema.call(this,e);}finally{this.opts=t;}}};Yi.ValidationError=yw.default;Yi.MissingRefError=Ug.default;He.default=Yi;function Jg(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 zg(n){return n=(0, Xi.normalizeId)(n),this.schemas[n]||this.refs[n]}function Dw(){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 xw(){for(let n in this.opts.formats){let e=this.opts.formats[n];e&&this.addFormat(n,e);}}function Pw(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 Ow(){let n={...this.opts};for(let e of _w)delete n[e];return n}var Tw={log(){},warn(){},error(){}};function Nw(n){if(n===false)return Tw;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 Fw=/^[a-z_$][a-z0-9_$:-]*$/i;function Iw(n,e){let{RULES:t}=this;if((0, Gc.eachItem)(n,r=>{if(t.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Fw.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 Wc(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, Da.getJSONTypes)(e.type),schemaType:(0, Da.getJSONTypes)(e.schemaType)}};e.before?kw.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 kw(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 Rw(n){let{metaSchema:e}=n;e!==void 0&&(n.$data&&this.opts.$data&&(e=Xg(e)),n.validateSchema=this.compile(e,true));}var $w={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xg(n){return {anyOf:[n,$w]}}});var Yg=S(Jc=>{Object.defineProperty(Jc,"__esModule",{value:true});var Vw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Jc.default=Vw;});var Oa=S(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.callRef=cr.getValidate=void 0;var jw=Mr(),Qg=Pt(),ft=M(),Hr=xt(),Zg=Ji(),xa=Y(),Lw={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=Zg.resolveRef.call(u,l,i,t);if(c===void 0)throw new jw.default(r.opts.uriResolver,i,t);if(c instanceof Zg.SchemaEnv)return f(c);return g(c);function h(){if(a===l)return Pa(n,s,a,a.$async);let p=e.scopeValue("root",{ref:l});return Pa(n,(0, ft._)`${p}.validate`,l,l.$async)}function f(p){let m=ey(n,p);Pa(n,m,p,p.$async);}function g(p){let m=e.scopeValue("schema",o.code.source===true?{ref:p,code:(0, ft.stringify)(p)}:{ref:p}),C=e.name("valid"),b=n.subschema({schema:p,dataTypes:[],schemaPath:ft.nil,topSchemaRef:m,errSchemaPath:t},C);n.mergeEvaluated(b),n.ok(C);}}};function ey(n,e){let{gen:t}=n;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0, ft._)`${t.scopeValue("wrapper",{ref:e})}.validate`}cr.getValidate=ey;function Pa(n,e,t,r){let{gen:i,it:a}=n,{allErrors:s,schemaEnv:o,opts:u}=a,l=u.passContext?Hr.default.this:ft.nil;r?c():h();function c(){if(!o.$async)throw new Error("async schema referenced by sync schema");let p=i.let("valid");i.try(()=>{i.code((0, ft._)`await ${(0, Qg.callValidateCode)(n,e,l)}`),g(e),s||i.assign(p,true);},m=>{i.if((0, ft._)`!(${m} instanceof ${a.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(p,false);}),n.ok(p);}function h(){n.result((0, Qg.callValidateCode)(n,e,l),()=>g(e),()=>f(e));}function f(p){let m=(0, ft._)`${p}.errors`;i.assign(Hr.default.vErrors,(0, ft._)`${Hr.default.vErrors} === null ? ${m} : ${Hr.default.vErrors}.concat(${m})`),i.assign(Hr.default.errors,(0, ft._)`${Hr.default.vErrors}.length`);}function g(p){var m;if(!a.opts.unevaluated)return;let C=(m=t?.validate)===null||m===void 0?void 0:m.evaluated;if(a.props!==true)if(C&&!C.dynamicProps)C.props!==void 0&&(a.props=xa.mergeEvaluated.props(i,C.props,a.props));else {let b=i.var("props",(0, ft._)`${p}.evaluated.props`);a.props=xa.mergeEvaluated.props(i,b,a.props,ft.Name);}if(a.items!==true)if(C&&!C.dynamicItems)C.items!==void 0&&(a.items=xa.mergeEvaluated.items(i,C.items,a.items));else {let b=i.var("items",(0, ft._)`${p}.evaluated.items`);a.items=xa.mergeEvaluated.items(i,b,a.items,ft.Name);}}}cr.callRef=Pa;cr.default=Lw;});var Uc=S(zc=>{Object.defineProperty(zc,"__esModule",{value:true});var qw=Yg(),Bw=Oa(),Mw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qw.default,Bw.default];zc.default=Mw;});var ty=S(Kc=>{Object.defineProperty(Kc,"__esModule",{value:true});var Ta=M(),Rn=Ta.operators,Na={maximum:{okStr:"<=",ok:Rn.LTE,fail:Rn.GT},minimum:{okStr:">=",ok:Rn.GTE,fail:Rn.LT},exclusiveMaximum:{okStr:"<",ok:Rn.LT,fail:Rn.GTE},exclusiveMinimum:{okStr:">",ok:Rn.GT,fail:Rn.LTE}},Ww={message:({keyword:n,schemaCode:e})=>(0, Ta.str)`must be ${Na[n].okStr} ${e}`,params:({keyword:n,schemaCode:e})=>(0, Ta._)`{comparison: ${Na[n].okStr}, limit: ${e}}`},Gw={keyword:Object.keys(Na),type:"number",schemaType:"number",$data:true,error:Ww,code(n){let{keyword:e,data:t,schemaCode:r}=n;n.fail$data((0, Ta._)`${t} ${Na[e].fail} ${r} || isNaN(${t})`);}};Kc.default=Gw;});var ny=S(Xc=>{Object.defineProperty(Xc,"__esModule",{value:true});var Qi=M(),Hw={message:({schemaCode:n})=>(0, Qi.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0, Qi._)`{multipleOf: ${n}}`},Jw={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:Hw,code(n){let{gen:e,data:t,schemaCode:r,it:i}=n,a=i.opts.multipleOfPrecision,s=e.let("res"),o=a?(0, Qi._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${a}`:(0, Qi._)`${s} !== parseInt(${s})`;n.fail$data((0, Qi._)`(${r} === 0 || (${s} = ${t}/${r}, ${o}))`);}};Xc.default=Jw;});var iy=S(Yc=>{Object.defineProperty(Yc,"__esModule",{value:true});function ry(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}Yc.default=ry;ry.code='require("ajv/dist/runtime/ucs2length").default';});var sy=S(Qc=>{Object.defineProperty(Qc,"__esModule",{value:true});var hr=M(),zw=Y(),Uw=iy(),Kw={message({keyword:n,schemaCode:e}){let t=n==="maxLength"?"more":"fewer";return (0, hr.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:n})=>(0, hr._)`{limit: ${n}}`},Xw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:Kw,code(n){let{keyword:e,data:t,schemaCode:r,it:i}=n,a=e==="maxLength"?hr.operators.GT:hr.operators.LT,s=i.opts.unicode===false?(0, hr._)`${t}.length`:(0, hr._)`${(0, zw.useFunc)(n.gen,Uw.default)}(${t})`;n.fail$data((0, hr._)`${s} ${a} ${r}`);}};Qc.default=Xw;});var ay=S(Zc=>{Object.defineProperty(Zc,"__esModule",{value:true});var Yw=Pt(),Qw=Y(),Jr=M(),Zw={message:({schemaCode:n})=>(0, Jr.str)`must match pattern "${n}"`,params:({schemaCode:n})=>(0, Jr._)`{pattern: ${n}}`},eA={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:Zw,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, Jr._)`new RegExp`:(0, Qw.useFunc)(e,u),c=e.let("valid");e.try(()=>e.assign(c,(0, Jr._)`${l}(${a}, ${o}).test(${t})`),()=>e.assign(c,false)),n.fail$data((0, Jr._)`!${c}`);}else {let u=(0, Yw.usePattern)(n,i);n.fail$data((0, Jr._)`!${u}.test(${t})`);}}};Zc.default=eA;});var oy=S(eh=>{Object.defineProperty(eh,"__esModule",{value:true});var Zi=M(),tA={message({keyword:n,schemaCode:e}){let t=n==="maxProperties"?"more":"fewer";return (0, Zi.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:n})=>(0, Zi._)`{limit: ${n}}`},nA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:tA,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxProperties"?Zi.operators.GT:Zi.operators.LT;n.fail$data((0, Zi._)`Object.keys(${t}).length ${i} ${r}`);}};eh.default=nA;});var uy=S(th=>{Object.defineProperty(th,"__esModule",{value:true});var es=Pt(),ts=M(),rA=Y(),iA={message:({params:{missingProperty:n}})=>(0, ts.str)`must have required property '${n}'`,params:({params:{missingProperty:n}})=>(0, ts._)`{missingProperty: ${n}}`},sA={keyword:"required",type:"object",schemaType:"array",$data:true,error:iA,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 g=n.parentSchema.properties,{definedProperties:p}=n.it;for(let m of t)if(g?.[m]===void 0&&!p.has(m)){let C=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${m}" is not defined at "${C}" (strictRequired)`;(0, rA.checkStrictMode)(s,b,s.opts.strictRequired);}}function l(){if(u||a)n.block$data(ts.nil,h);else for(let g of t)(0, es.checkReportMissingProp)(n,g);}function c(){let g=e.let("missing");if(u||a){let p=e.let("valid",true);n.block$data(p,()=>f(g,p)),n.ok(p);}else e.if((0, es.checkMissingProp)(n,t,g)),(0, es.reportMissingProp)(n,g),e.else();}function h(){e.forOf("prop",r,g=>{n.setParams({missingProperty:g}),e.if((0, es.noPropertyInData)(e,i,g,o.ownProperties),()=>n.error());});}function f(g,p){n.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(p,(0, es.propertyInData)(e,i,g,o.ownProperties)),e.if((0, ts.not)(p),()=>{n.error(),e.break();});},ts.nil);}}};th.default=sA;});var ly=S(nh=>{Object.defineProperty(nh,"__esModule",{value:true});var ns=M(),aA={message({keyword:n,schemaCode:e}){let t=n==="maxItems"?"more":"fewer";return (0, ns.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:n})=>(0, ns._)`{limit: ${n}}`},oA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:aA,code(n){let{keyword:e,data:t,schemaCode:r}=n,i=e==="maxItems"?ns.operators.GT:ns.operators.LT;n.fail$data((0, ns._)`${t}.length ${i} ${r}`);}};nh.default=oA;});var Fa=S(rh=>{Object.defineProperty(rh,"__esModule",{value:true});var cy=vc();cy.code='require("ajv/dist/runtime/equal").default';rh.default=cy;});var hy=S(sh=>{Object.defineProperty(sh,"__esModule",{value:true});var ih=Bi(),Je=M(),uA=Y(),lA=Fa(),cA={message:({params:{i:n,j:e}})=>(0, Je.str)`must NOT have duplicate items (items ## ${e} and ${n} are identical)`,params:({params:{i:n,j:e}})=>(0, Je._)`{i: ${n}, j: ${e}}`},hA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:cA,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, ih.getSchemaTypes)(a.items):[];n.block$data(u,c,(0, Je._)`${s} === false`),n.ok(u);function c(){let p=e.let("i",(0, Je._)`${t}.length`),m=e.let("j");n.setParams({i:p,j:m}),e.assign(u,true),e.if((0, Je._)`${p} > 1`,()=>(h()?f:g)(p,m));}function h(){return l.length>0&&!l.some(p=>p==="object"||p==="array")}function f(p,m){let C=e.name("item"),b=(0, ih.checkDataTypes)(l,C,o.opts.strictNumbers,ih.DataType.Wrong),y=e.const("indices",(0, Je._)`{}`);e.for((0, Je._)`;${p}--;`,()=>{e.let(C,(0, Je._)`${t}[${p}]`),e.if(b,(0, Je._)`continue`),l.length>1&&e.if((0, Je._)`typeof ${C} == "string"`,(0, Je._)`${C} += "_"`),e.if((0, Je._)`typeof ${y}[${C}] == "number"`,()=>{e.assign(m,(0, Je._)`${y}[${C}]`),n.error(),e.assign(u,false).break();}).code((0, Je._)`${y}[${C}] = ${p}`);});}function g(p,m){let C=(0, uA.useFunc)(e,lA.default),b=e.name("outer");e.label(b).for((0, Je._)`;${p}--;`,()=>e.for((0, Je._)`${m} = ${p}; ${m}--;`,()=>e.if((0, Je._)`${C}(${t}[${p}], ${t}[${m}])`,()=>{n.error(),e.assign(u,false).break(b);})));}}};sh.default=hA;});var dy=S(oh=>{Object.defineProperty(oh,"__esModule",{value:true});var ah=M(),dA=Y(),fA=Fa(),pA={message:"must be equal to constant",params:({schemaCode:n})=>(0, ah._)`{allowedValue: ${n}}`},mA={keyword:"const",$data:true,error:pA,code(n){let{gen:e,data:t,$data:r,schemaCode:i,schema:a}=n;r||a&&typeof a=="object"?n.fail$data((0, ah._)`!${(0, dA.useFunc)(e,fA.default)}(${t}, ${i})`):n.fail((0, ah._)`${a} !== ${t}`);}};oh.default=mA;});var fy=S(uh=>{Object.defineProperty(uh,"__esModule",{value:true});var rs=M(),gA=Y(),yA=Fa(),vA={message:"must be equal to one of the allowed values",params:({schemaCode:n})=>(0, rs._)`{allowedValues: ${n}}`},CA={keyword:"enum",schemaType:"array",$data:true,error:vA,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, gA.useFunc)(e,yA.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 g=e.const("vSchema",a);c=(0, rs.or)(...i.map((p,m)=>f(g,m)));}n.pass(c);function h(){e.assign(c,false),e.forOf("v",a,g=>e.if((0, rs._)`${l()}(${t}, ${g})`,()=>e.assign(c,true).break()));}function f(g,p){let m=i[p];return typeof m=="object"&&m!==null?(0, rs._)`${l()}(${t}, ${g}[${p}])`:(0, rs._)`${t} === ${m}`}}};uh.default=CA;});var ch=S(lh=>{Object.defineProperty(lh,"__esModule",{value:true});var bA=ty(),_A=ny(),SA=sy(),EA=ay(),wA=oy(),AA=uy(),DA=ly(),xA=hy(),PA=dy(),OA=fy(),TA=[bA.default,_A.default,SA.default,EA.default,wA.default,AA.default,DA.default,xA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},PA.default,OA.default];lh.default=TA;});var dh=S(is=>{Object.defineProperty(is,"__esModule",{value:true});is.validateAdditionalItems=void 0;var dr=M(),hh=Y(),NA={message:({params:{len:n}})=>(0, dr.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, dr._)`{limit: ${n}}`},FA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:NA,code(n){let{parentSchema:e,it:t}=n,{items:r}=e;if(!Array.isArray(r)){(0, hh.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}py(n,r);}};function py(n,e){let{gen:t,schema:r,data:i,keyword:a,it:s}=n;s.items=true;let o=t.const("len",(0, dr._)`${i}.length`);if(r===false)n.setParams({len:e.length}),n.pass((0, dr._)`${o} <= ${e.length}`);else if(typeof r=="object"&&!(0, hh.alwaysValidSchema)(s,r)){let l=t.var("valid",(0, dr._)`${o} <= ${e.length}`);t.if((0, dr.not)(l),()=>u(l)),n.ok(l);}function u(l){t.forRange("i",e.length,o,c=>{n.subschema({keyword:a,dataProp:c,dataPropType:hh.Type.Num},l),s.allErrors||t.if((0, dr.not)(l),()=>t.break());});}}is.validateAdditionalItems=py;is.default=FA;});var fh=S(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.validateTuple=void 0;var my=M(),Ia=Y(),IA=Pt(),kA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(n){let{schema:e,it:t}=n;if(Array.isArray(e))return gy(n,"additionalItems",e);t.items=true,!(0, Ia.alwaysValidSchema)(t,e)&&n.ok((0, IA.validateArray)(n));}};function gy(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=Ia.mergeEvaluated.items(r,t.length,o.items));let u=r.name("valid"),l=r.const("len",(0, my._)`${a}.length`);t.forEach((h,f)=>{(0, Ia.alwaysValidSchema)(o,h)||(r.if((0, my._)`${l} > ${f}`,()=>n.subschema({keyword:s,schemaProp:f,dataProp:f},u)),n.ok(u));});function c(h){let{opts:f,errSchemaPath:g}=o,p=t.length,m=p===h.minItems&&(p===h.maxItems||h[e]===false);if(f.strictTuples&&!m){let C=`"${s}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0, Ia.checkStrictMode)(o,C,f.strictTuples);}}}ss.validateTuple=gy;ss.default=kA;});var yy=S(ph=>{Object.defineProperty(ph,"__esModule",{value:true});var RA=fh(),$A={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0, RA.validateTuple)(n,"items")};ph.default=$A;});var Cy=S(mh=>{Object.defineProperty(mh,"__esModule",{value:true});var vy=M(),VA=Y(),jA=Pt(),LA=dh(),qA={message:({params:{len:n}})=>(0, vy.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, vy._)`{limit: ${n}}`},BA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qA,code(n){let{schema:e,parentSchema:t,it:r}=n,{prefixItems:i}=t;r.items=true,!(0, VA.alwaysValidSchema)(r,e)&&(i?(0, LA.validateAdditionalItems)(n,i):n.ok((0, jA.validateArray)(n)));}};mh.default=BA;});var by=S(gh=>{Object.defineProperty(gh,"__esModule",{value:true});var Tt=M(),ka=Y(),MA={message:({params:{min:n,max:e}})=>e===void 0?(0, Tt.str)`must contain at least ${n} valid item(s)`:(0, Tt.str)`must contain at least ${n} and no more than ${e} valid item(s)`,params:({params:{min:n,max:e}})=>e===void 0?(0, Tt._)`{minContains: ${n}}`:(0, Tt._)`{minContains: ${n}, maxContains: ${e}}`},WA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:MA,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, Tt._)`${i}.length`);if(n.setParams({min:s,max:o}),o===void 0&&s===0){(0, ka.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(o!==void 0&&s>o){(0, ka.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),n.fail();return}if((0, ka.alwaysValidSchema)(a,t)){let m=(0, Tt._)`${c} >= ${s}`;o!==void 0&&(m=(0, Tt._)`${m} && ${c} <= ${o}`),n.pass(m);return}a.items=true;let h=e.name("valid");o===void 0&&s===1?g(h,()=>e.if(h,()=>e.break())):s===0?(e.let(h,true),o!==void 0&&e.if((0, Tt._)`${i}.length > 0`,f)):(e.let(h,false),f()),n.result(h,()=>n.reset());function f(){let m=e.name("_valid"),C=e.let("count",0);g(m,()=>e.if(m,()=>p(C)));}function g(m,C){e.forRange("i",0,c,b=>{n.subschema({keyword:"contains",dataProp:b,dataPropType:ka.Type.Num,compositeRule:true},m),C();});}function p(m){e.code((0, Tt._)`${m}++`),o===void 0?e.if((0, Tt._)`${m} >= ${s}`,()=>e.assign(h,true).break()):(e.if((0, Tt._)`${m} > ${o}`,()=>e.assign(h,false).break()),s===1?e.assign(h,true):e.if((0, Tt._)`${m} >= ${s}`,()=>e.assign(h,true)));}}};gh.default=WA;});var Ra=S(Yt=>{Object.defineProperty(Yt,"__esModule",{value:true});Yt.validateSchemaDeps=Yt.validatePropertyDeps=Yt.error=void 0;var yh=M(),GA=Y(),as=Pt();Yt.error={message:({params:{property:n,depsCount:e,deps:t}})=>{let r=e===1?"property":"properties";return (0, yh.str)`must have ${r} ${t} when property ${n} is present`},params:({params:{property:n,depsCount:e,deps:t,missingProperty:r}})=>(0, yh._)`{property: ${n},
6
6
  missingProperty: ${r},
7
7
  depsCount: ${e},
8
- deps: ${t}}`};var MA={keyword:"dependencies",type:"object",schemaType:"object",error:Zt.error,code(n){let[e,t]=WA(n);Cy(n,e),by(n,t);}};function WA({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 Cy(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, rs.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, rs.checkReportMissingProp)(n,l);}):(t.if((0, fh._)`${u} && (${(0, rs.checkMissingProp)(n,o,a)})`),(0, rs.reportMissingProp)(n,a),t.else());}}Zt.validatePropertyDeps=Cy;function by(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, BA.alwaysValidSchema)(a,e[o])||(t.if((0, rs.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));}Zt.validateSchemaDeps=by;Zt.default=MA;});var Sy=w(ph=>{Object.defineProperty(ph,"__esModule",{value:true});var _y=M(),GA=Q(),HA={message:"property name must be valid",params:({params:n})=>(0, _y._)`{propertyName: ${n.propertyName}}`},JA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:HA,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, GA.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, _y.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};ph.default=JA;});var gh=w(mh=>{Object.defineProperty(mh,"__esModule",{value:true});var Ra=Pt(),Mt=M(),zA=xt(),$a=Q(),UA={message:"must NOT have additional properties",params:({params:n})=>(0, Mt._)`{additionalProperty: ${n.additionalProperty}}`},KA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:UA,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, $a.alwaysValidSchema)(s,t))return;let l=(0, Ra.allSchemaProperties)(r.properties),c=(0, Ra.allSchemaProperties)(r.patternProperties);h(),n.ok((0, Mt._)`${a} === ${zA.default.errors}`);function h(){e.forIn("key",i,b=>{!l.length&&!c.length?f(b):e.if(d(b),()=>f(b));});}function d(b){let _;if(l.length>8){let y=(0, $a.schemaRefOrVal)(s,r.properties,"properties");_=(0, Ra.isOwnProperty)(e,y,b);}else l.length?_=(0, Mt.or)(...l.map(y=>(0, Mt._)`${b} === ${y}`)):_=Mt.nil;return c.length&&(_=(0, Mt.or)(_,...c.map(y=>(0, Mt._)`${(0, Ra.usePattern)(n,y)}.test(${b})`))),(0, Mt.not)(_)}function g(b){e.code((0, Mt._)`delete ${i}[${b}]`);}function f(b){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){g(b);return}if(t===false){n.setParams({additionalProperty:b}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, $a.alwaysValidSchema)(s,t)){let _=e.name("valid");u.removeAdditional==="failing"?(m(b,_,false),e.if((0, Mt.not)(_),()=>{n.reset(),g(b);})):(m(b,_),o||e.if((0, Mt.not)(_),()=>e.break()));}}function m(b,_,y){let p={keyword:"additionalProperties",dataProp:b,dataPropType:$a.Type.Str};y===false&&Object.assign(p,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(p,_);}}};mh.default=KA;});var Ay=w(vh=>{Object.defineProperty(vh,"__esModule",{value:true});var XA=Lr(),Ey=Pt(),yh=Q(),wy=gh(),YA={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&&wy.default.code(new XA.KeywordCxt(a,wy.default,"additionalProperties"));let s=(0, Ey.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=yh.mergeEvaluated.props(e,(0, yh.toHash)(s),a.props));let o=s.filter(h=>!(0, yh.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, Ey.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);}}};vh.default=YA;});var Oy=w(Ch=>{Object.defineProperty(Ch,"__esModule",{value:true});var Dy=Pt(),Va=M(),xy=Q(),Py=Q(),QA={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, Dy.allSchemaProperties)(t),u=o.filter(m=>(0, xy.alwaysValidSchema)(a,t[m]));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 Va.Name)&&(a.props=(0, Py.evaluatedPropsToName)(e,a.props));let{props:h}=a;d();function d(){for(let m of o)l&&g(m),a.allErrors?f(m):(e.var(c,true),f(m),e.if(c));}function g(m){for(let b in l)new RegExp(m).test(b)&&(0, xy.checkStrictMode)(a,`property ${b} matches pattern ${m} (use allowMatchingProperties)`);}function f(m){e.forIn("key",r,b=>{e.if((0, Va._)`${(0, Dy.usePattern)(n,m)}.test(${b})`,()=>{let _=u.includes(m);_||n.subschema({keyword:"patternProperties",schemaProp:m,dataProp:b,dataPropType:Py.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, Va._)`${h}[${b}]`,true):!_&&!a.allErrors&&e.if((0, Va.not)(c),()=>e.break());});});}}};Ch.default=QA;});var Ty=w(bh=>{Object.defineProperty(bh,"__esModule",{value:true});var ZA=Q(),eD={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, ZA.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"}};bh.default=eD;});var Ny=w(_h=>{Object.defineProperty(_h,"__esModule",{value:true});var tD=Pt(),nD={keyword:"anyOf",schemaType:"array",trackErrors:true,code:tD.validateUnion,error:{message:"must match a schema in anyOf"}};_h.default=nD;});var Fy=w(Sh=>{Object.defineProperty(Sh,"__esModule",{value:true});var ja=M(),rD=Q(),iD={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, ja._)`{passingSchemas: ${n.passing}}`},sD={keyword:"oneOf",schemaType:"array",trackErrors:true,error:iD,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, rD.alwaysValidSchema)(i,c)?e.var(u,true):d=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, ja._)`${u} && ${s}`).assign(s,false).assign(o,(0, ja._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),d&&n.mergeEvaluated(d,ja.Name);});});}}};Sh.default=sD;});var Iy=w(Eh=>{Object.defineProperty(Eh,"__esModule",{value:true});var aD=Q(),oD={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, aD.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};Eh.default=oD;});var $y=w(wh=>{Object.defineProperty(wh,"__esModule",{value:true});var La=M(),Ry=Q(),uD={message:({params:n})=>(0, La.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, La._)`{failingKeyword: ${n.ifClause}}`},lD={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:uD,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, Ry.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=ky(r,"then"),a=ky(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, La.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, La._)`${c}`):n.setParams({ifClause:c});}}}};function ky(n,e){let t=n.schema[e];return t!==void 0&&!(0, Ry.alwaysValidSchema)(n,t)}wh.default=lD;});var Vy=w(Ah=>{Object.defineProperty(Ah,"__esModule",{value:true});var cD=Q(),hD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, cD.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Ah.default=hD;});var xh=w(Dh=>{Object.defineProperty(Dh,"__esModule",{value:true});var dD=uh(),fD=my(),pD=lh(),mD=yy(),gD=vy(),yD=ka(),vD=Sy(),CD=gh(),bD=Ay(),_D=Oy(),SD=Ty(),ED=Ny(),wD=Fy(),AD=Iy(),DD=$y(),xD=Vy();function PD(n=false){let e=[SD.default,ED.default,wD.default,AD.default,DD.default,xD.default,vD.default,CD.default,yD.default,bD.default,_D.default];return n?e.push(fD.default,mD.default):e.push(dD.default,pD.default),e.push(gD.default),e}Dh.default=PD;});var jy=w(Ph=>{Object.defineProperty(Ph,"__esModule",{value:true});var Fe=M(),OD={message:({schemaCode:n})=>(0, Fe.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, Fe._)`{format: ${n}}`},TD={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:OD,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():g();function d(){let f=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),m=t.const("fDef",(0, Fe._)`${f}[${s}]`),b=t.let("fType"),_=t.let("format");t.if((0, Fe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(b,(0, Fe._)`${m}.type || "string"`).assign(_,(0, Fe._)`${m}.validate`),()=>t.assign(b,(0, Fe._)`"string"`).assign(_,m)),n.fail$data((0, Fe.or)(y(),p()));function y(){return u.strictSchema===false?Fe.nil:(0, Fe._)`${s} && !${_}`}function p(){let v=c.$async?(0, Fe._)`(${m}.async ? await ${_}(${r}) : ${_}(${r}))`:(0, Fe._)`${_}(${r})`,C=(0, Fe._)`(typeof ${_} == "function" ? ${v} : ${_}.test(${r}))`;return (0, Fe._)`${_} && ${_} !== true && ${b} === ${e} && !${C}`}}function g(){let f=h.formats[a];if(!f){y();return}if(f===true)return;let[m,b,_]=p(f);m===e&&n.pass(v());function y(){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 p(C){let S=C instanceof RegExp?(0, Fe.regexpCode)(C):u.code.formats?(0, Fe._)`${u.code.formats}${(0, Fe.getProperty)(a)}`:void 0,D=t.scopeValue("formats",{key:a,ref:C,code:S});return typeof C=="object"&&!(C instanceof RegExp)?[C.type||"string",C.validate,(0, Fe._)`${D}.validate`]:["string",C,D]}function v(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!c.$async)throw new Error("async format in sync schema");return (0, Fe._)`await ${_}(${r})`}return typeof b=="function"?(0, Fe._)`${_}(${r})`:(0, Fe._)`${_}.test(${r})`}}}};Ph.default=TD;});var Th=w(Oh=>{Object.defineProperty(Oh,"__esModule",{value:true});var ND=jy(),FD=[ND.default];Oh.default=FD;});var Nh=w(Hr=>{Object.defineProperty(Hr,"__esModule",{value:true});Hr.contentVocabulary=Hr.metadataVocabulary=void 0;Hr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Hr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var qy=w(Fh=>{Object.defineProperty(Fh,"__esModule",{value:true});var ID=Gc(),kD=ah(),RD=xh(),$D=Th(),Ly=Nh(),VD=[ID.default,kD.default,(0, RD.default)(),$D.default,Ly.metadataVocabulary,Ly.contentVocabulary];Fh.default=VD;});var My=w(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.DiscrError=void 0;var By;(function(n){n.Tag="tag",n.Mapping="mapping";})(By||(qa.DiscrError=By={}));});var Rh=w(kh=>{Object.defineProperty(kh,"__esModule",{value:true});var Jr=M(),Ih=My(),Wy=Wi(),jD=qr(),LD=Q(),qD={message:({params:{discrError:n,tagName:e}})=>n===Ih.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Jr._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},BD={keyword:"discriminator",type:"object",schemaType:"object",error:qD,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, Jr._)`${t}${(0, Jr.getProperty)(o)}`);e.if((0, Jr._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:Ih.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let g=d();e.if(false);for(let f in g)e.elseIf((0, Jr._)`${l} === ${f}`),e.assign(u,h(g[f]));e.else(),n.error(false,{discrError:Ih.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(g){let f=e.name("valid"),m=n.subschema({keyword:"oneOf",schemaProp:g},f);return n.mergeEvaluated(m,Jr.Name),f}function d(){var g;let f={},m=_(i),b=true;for(let v=0;v<s.length;v++){let C=s[v];if(C?.$ref&&!(0, LD.schemaHasRulesButRef)(C,a.self.RULES)){let D=C.$ref;if(C=Wy.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,D),C instanceof Wy.SchemaEnv&&(C=C.schema),C===void 0)throw new jD.default(a.opts.uriResolver,a.baseId,D)}let S=(g=C?.properties)===null||g===void 0?void 0:g[o];if(typeof S!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);b=b&&(m||_(C)),y(S,v);}if(!b)throw new Error(`discriminator: "${o}" must be required`);return f;function _({required:v}){return Array.isArray(v)&&v.includes(o)}function y(v,C){if(v.const)p(v.const,C);else if(v.enum)for(let S of v.enum)p(S,C);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function p(v,C){if(typeof v!="string"||v in f)throw new Error(`discriminator: "${o}" values must be unique strings`);f[v]=C;}}}};kh.default=BD;});var Gy=w(($V,MD)=>{MD.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 Jy=w((we,$h)=>{Object.defineProperty(we,"__esModule",{value:true});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv=void 0;var WD=Bc(),GD=qy(),HD=Rh(),Hy=Gy(),JD=["/properties"],Ba="http://json-schema.org/draft-07/schema",zr=class extends WD.default{_addVocabularies(){super._addVocabularies(),GD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(HD.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Hy,JD):Hy;this.addMetaSchema(e,Ba,false),this.refs["http://json-schema.org/schema"]=Ba;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ba)?Ba:void 0)}};we.Ajv=zr;$h.exports=we=zr;$h.exports.Ajv=zr;Object.defineProperty(we,"__esModule",{value:true});we.default=zr;var zD=Lr();Object.defineProperty(we,"KeywordCxt",{enumerable:true,get:function(){return zD.KeywordCxt}});var Ur=M();Object.defineProperty(we,"_",{enumerable:true,get:function(){return Ur._}});Object.defineProperty(we,"str",{enumerable:true,get:function(){return Ur.str}});Object.defineProperty(we,"stringify",{enumerable:true,get:function(){return Ur.stringify}});Object.defineProperty(we,"nil",{enumerable:true,get:function(){return Ur.nil}});Object.defineProperty(we,"Name",{enumerable:true,get:function(){return Ur.Name}});Object.defineProperty(we,"CodeGen",{enumerable:true,get:function(){return Ur.CodeGen}});var UD=Mi();Object.defineProperty(we,"ValidationError",{enumerable:true,get:function(){return UD.default}});var KD=qr();Object.defineProperty(we,"MissingRefError",{enumerable:true,get:function(){return KD.default}});});var jh=w(is=>{Object.defineProperty(is,"__esModule",{value:true});is.dynamicAnchor=void 0;var Vh=M(),XD=xt(),zy=Wi(),YD=Pa(),QD={keyword:"$dynamicAnchor",schemaType:"string",code:n=>Uy(n,n.schema)};function Uy(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, Vh._)`${XD.default.dynamicAnchors}${(0, Vh.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:ZD(n);t.if((0, Vh._)`!${i}`,()=>t.assign(i,a));}is.dynamicAnchor=Uy;function ZD(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 zy.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return zy.compileSchema.call(r,l),(0, YD.getValidate)(n,l)}is.default=QD;});var Lh=w(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.dynamicRef=void 0;var Ky=M(),ex=xt(),Xy=Pa(),tx={keyword:"$dynamicRef",schemaType:"string",code:n=>Yy(n,n.schema)};function Yy(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, Ky._)`${ex.default.dynamicAnchors}${(0, Ky.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, Xy.callRef)(n,u),t.let(l,true);}):()=>(0, Xy.callRef)(n,u)}}ss.dynamicRef=Yy;ss.default=tx;});var Qy=w(qh=>{Object.defineProperty(qh,"__esModule",{value:true});var nx=jh(),rx=Q(),ix={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, nx.dynamicAnchor)(n,""):(0, rx.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};qh.default=ix;});var Zy=w(Bh=>{Object.defineProperty(Bh,"__esModule",{value:true});var sx=Lh(),ax={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, sx.dynamicRef)(n,n.schema)};Bh.default=ax;});var ev=w(Mh=>{Object.defineProperty(Mh,"__esModule",{value:true});var ox=jh(),ux=Lh(),lx=Qy(),cx=Zy(),hx=[ox.default,ux.default,lx.default,cx.default];Mh.default=hx;});var nv=w(Wh=>{Object.defineProperty(Wh,"__esModule",{value:true});var tv=ka(),dx={keyword:"dependentRequired",type:"object",schemaType:"object",error:tv.error,code:n=>(0, tv.validatePropertyDeps)(n)};Wh.default=dx;});var rv=w(Gh=>{Object.defineProperty(Gh,"__esModule",{value:true});var fx=ka(),px={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, fx.validateSchemaDeps)(n)};Gh.default=px;});var iv=w(Hh=>{Object.defineProperty(Hh,"__esModule",{value:true});var mx=Q(),gx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, mx.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};Hh.default=gx;});var sv=w(Jh=>{Object.defineProperty(Jh,"__esModule",{value:true});var yx=nv(),vx=rv(),Cx=iv(),bx=[yx.default,vx.default,Cx.default];Jh.default=bx;});var ov=w(zh=>{Object.defineProperty(zh,"__esModule",{value:true});var Rn=M(),av=Q(),_x=xt(),Sx={message:"must NOT have unevaluated properties",params:({params:n})=>(0, Rn._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},Ex={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:Sx,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 Rn.Name?e.if((0, Rn._)`${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, Rn._)`${i} === ${_x.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, av.alwaysValidSchema)(a,t)){let d=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:av.Type.Str},d),s||e.if((0, Rn.not)(d),()=>e.break());}}function l(h,d){return (0, Rn._)`!${h} || !${h}[${d}]`}function c(h,d){let g=[];for(let f in h)h[f]===true&&g.push((0, Rn._)`${d} !== ${f}`);return (0, Rn.and)(...g)}}};zh.default=Ex;});var lv=w(Uh=>{Object.defineProperty(Uh,"__esModule",{value:true});var hr=M(),uv=Q(),wx={message:({params:{len:n}})=>(0, hr.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, hr._)`{limit: ${n}}`},Ax={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:wx,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, hr._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, hr._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, uv.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, hr._)`${s} <= ${a}`);e.if((0, hr.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:uv.Type.Num},u),i.allErrors||e.if((0, hr.not)(u),()=>e.break());});}}};Uh.default=Ax;});var cv=w(Kh=>{Object.defineProperty(Kh,"__esModule",{value:true});var Dx=ov(),xx=lv(),Px=[Dx.default,xx.default];Kh.default=Px;});var dv=w(Xh=>{Object.defineProperty(Xh,"__esModule",{value:true});var Ox=Gc(),Tx=ah(),Nx=xh(),Fx=ev(),Ix=sv(),kx=cv(),Rx=Th(),hv=Nh(),$x=[Fx.default,Ox.default,Tx.default,(0, Nx.default)(true),Rx.default,hv.metadataVocabulary,hv.contentVocabulary,Ix.default,kx.default];Xh.default=$x;});var fv=w((XV,Vx)=>{Vx.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 pv=w((YV,jx)=>{jx.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 mv=w((QV,Lx)=>{Lx.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 gv=w((ZV,qx)=>{qx.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 yv=w((ej,Bx)=>{Bx.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 vv=w((tj,Mx)=>{Mx.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 Cv=w((nj,Wx)=>{Wx.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 bv=w((rj,Gx)=>{Gx.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 _v=w(Yh=>{Object.defineProperty(Yh,"__esModule",{value:true});var Hx=fv(),Jx=pv(),zx=mv(),Ux=gv(),Kx=yv(),Xx=vv(),Yx=Cv(),Qx=bv(),Zx=["/properties"];function eP(n){return [Hx,Jx,zx,Ux,Kx,e(this,Xx),Yx,e(this,Qx)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,Zx):r}}Yh.default=eP;});var Sv=w((Ae,Zh)=>{Object.defineProperty(Ae,"__esModule",{value:true});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv2020=void 0;var tP=Bc(),nP=dv(),rP=Rh(),iP=_v(),Qh="https://json-schema.org/draft/2020-12/schema",Kr=class extends tP.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),nP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(rP.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(iP.default.call(this,e),this.refs["http://json-schema.org/schema"]=Qh);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Qh)?Qh:void 0)}};Ae.Ajv2020=Kr;Zh.exports=Ae=Kr;Zh.exports.Ajv2020=Kr;Object.defineProperty(Ae,"__esModule",{value:true});Ae.default=Kr;var sP=Lr();Object.defineProperty(Ae,"KeywordCxt",{enumerable:true,get:function(){return sP.KeywordCxt}});var Xr=M();Object.defineProperty(Ae,"_",{enumerable:true,get:function(){return Xr._}});Object.defineProperty(Ae,"str",{enumerable:true,get:function(){return Xr.str}});Object.defineProperty(Ae,"stringify",{enumerable:true,get:function(){return Xr.stringify}});Object.defineProperty(Ae,"nil",{enumerable:true,get:function(){return Xr.nil}});Object.defineProperty(Ae,"Name",{enumerable:true,get:function(){return Xr.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:true,get:function(){return Xr.CodeGen}});var aP=Mi();Object.defineProperty(Ae,"ValidationError",{enumerable:true,get:function(){return aP.default}});var oP=qr();Object.defineProperty(Ae,"MissingRefError",{enumerable:true,get:function(){return oP.default}});});var td=w(Ma=>{Object.defineProperty(Ma,"__esModule",{value:true});Ma.CompilerOptions=void 0;var ed=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;}};Ma.CompilerOptions=ed;});var Ev=w(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.DebugSourceRange=void 0;var nd=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};Wa.DebugSourceRange=nd;});var dr=w(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.ErrorType=void 0;var wv;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(wv||(Ga.ErrorType=wv={}));});var Av=w(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.Argument=void 0;var rd=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};Ha.Argument=rd;});var fe=w(Le=>{Object.defineProperty(Le,"__esModule",{value:true});Le.filterUndef=Le.isEquatable=Le.nullIfUndefined=Le.asINamedContentOrNull=Le.asBooleanOrThrows=Le.asNumberOrThrows=Le.asOrThrows=Le.asOrNull=void 0;function uP(n,e){return n instanceof e?Dv(n):null}Le.asOrNull=uP;function lP(n,e){if(n instanceof e)return Dv(n);throw new Error(`${n} is not of type ${e}`)}Le.asOrThrows=lP;function cP(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}Le.asNumberOrThrows=cP;function hP(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}Le.asBooleanOrThrows=hP;function dP(n){return n.hasValidName&&n.name?n:null}Le.asINamedContentOrNull=dP;function fP(n){return typeof n>"u"?null:n}Le.nullIfUndefined=fP;function pP(n){return typeof n=="object"&&typeof n.Equals=="function"}Le.isEquatable=pP;function Dv(n,e){return n}function mP(n){return n!=null}Le.filterUndef=mP;});var xe=w(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.ParsedObject=void 0;var xv=fe(),id=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, xv.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, xv.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;}}};Ja.ParsedObject=id;});var Ua=w(za=>{Object.defineProperty(za,"__esModule",{value:true});za.AuthorWarning=void 0;var gP=xe(),sd=class extends gP.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};za.AuthorWarning=sd;});var pt=w(as=>{Object.defineProperty(as,"__esModule",{value:true});as.Path=void 0;var Yr=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}};as.Path=Yr;Yr.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;})(Yr||(as.Path=Yr={}));});var os=w(Ka=>{Object.defineProperty(Ka,"__esModule",{value:true});Ka.Debug=void 0;var Pv;(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;})(Pv||(Ka.Debug=Pv={}));});var Ye=w(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.throwNullException=Qr.NullException=void 0;var Xa=class extends Error{};Qr.NullException=Xa;function yP(n){throw new Xa(`${n} is null or undefined`)}Qr.throwNullException=yP;});var mt=w(Qa=>{Object.defineProperty(Qa,"__esModule",{value:true});Qa.InkObject=void 0;var Zr=pt(),us=ke(),ad=os(),ei=fe(),Ya=Ye(),od=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 Zr.Path;else {let e=[],t=this,r=(0, ei.asOrNull)(t.parent,us.Container);for(;r!==null;){let i=(0, ei.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Ya.throwNullException)("namedChild.name");e.unshift(new Zr.Path.Component(i.name));}else e.unshift(new Zr.Path.Component(r.content.indexOf(t)));t=r,r=(0, ei.asOrNull)(r.parent,us.Container);}this._path=new Zr.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Ya.throwNullException)("path");if(e.isRelative){let t=(0, ei.asOrNull)(this,us.Container);return t===null&&(ad.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, ei.asOrNull)(this.parent,us.Container),ad.Debug.Assert(t!==null,"Expected parent to be a container"),ad.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Ya.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Ya.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(Zr.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new Zr.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, ei.asOrNull)(e,us.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}};Qa.InkObject=od;});var fr=w(Za=>{Object.defineProperty(Za,"__esModule",{value:true});Za.StringBuilder=void 0;var ud=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="";}};Za.StringBuilder=ud;});var yt=w(ti=>{Object.defineProperty(ti,"__esModule",{value:true});ti.InkList=ti.InkListItem=void 0;var en=Ye(),vP=fr(),gt=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)}};ti.InkListItem=gt;var ld=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, en.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, en.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, en.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 gt){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, en.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, en.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, en.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 gt(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(gt.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=gt.fromSerializedKey(e);if(t.originName===null)return (0, en.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:gt.Null,Value:0};for(let[t,r]of this){let i=gt.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:gt.Null,Value:0};for(let[t,r]of this){let i=gt.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=gt.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=gt.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=gt.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, en.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, en.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 vP.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, en.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};ti.InkList=ld;});var ls=w(eo=>{Object.defineProperty(eo,"__esModule",{value:true});eo.StoryException=void 0;var cd=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};eo.StoryException=cd;});var ni=w($n=>{Object.defineProperty($n,"__esModule",{value:true});$n.tryParseFloat=$n.tryParseInt=$n.tryGetValueFromMap=void 0;function CP(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}}$n.tryGetValueFromMap=CP;function bP(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}$n.tryParseInt=bP;function _P(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}$n.tryParseFloat=_P;});var Oe=w(Te=>{Object.defineProperty(Te,"__esModule",{value:true});Te.ValueType=Te.ListValue=Te.VariablePointerValue=Te.DivertTargetValue=Te.StringValue=Te.FloatValue=Te.IntValue=Te.BoolValue=Te.Value=Te.AbstractValue=void 0;var Ov=mt(),Tv=pt(),pr=yt(),SP=ls(),cs=fe(),Nv=ni(),Nt=Ye(),to=class n extends Ov.InkObject{static Create(e,t){if(t){if(t===De.Int&&Number.isInteger(Number(e)))return new nn(Number(e));if(t===De.Float&&!isNaN(e))return new rn(Number(e))}if(typeof e=="boolean")return new ri(!!e);if(typeof e=="string")return new Cn(String(e));if(Number.isInteger(Number(e)))return new nn(Number(e));if(isNaN(e)){if(e instanceof Tv.Path)return new no((0, cs.asOrThrows)(e,Tv.Path));if(e instanceof pr.InkList)return new ro((0, cs.asOrThrows)(e,pr.InkList))}else return new rn(Number(e));return null}Copy(){return (0, cs.asOrThrows)(n.Create(this.valueObject),Ov.InkObject)}BadCastException(e){return new SP.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};Te.AbstractValue=to;var tn=class extends to{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Nt.throwNullException)("Value.value"):this.value.toString()}};Te.Value=tn;var ri=class extends tn{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return De.Bool}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Int)return new nn(this.value?1:0);if(e==De.Float)return new rn(this.value?1:0);if(e==De.String)return new Cn(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};Te.BoolValue=ri;var nn=class extends tn{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return De.Int}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Bool)return new ri(this.value!==0);if(e==De.Float)return new rn(this.value);if(e==De.String)return new Cn(""+this.value);throw this.BadCastException(e)}};Te.IntValue=nn;var rn=class extends tn{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return De.Float}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Bool)return new ri(this.value!==0);if(e==De.Int)return new nn(this.value);if(e==De.String)return new Cn(""+this.value);throw this.BadCastException(e)}};Te.FloatValue=rn;var Cn=class extends tn{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
- `,this._isInlineWhitespace=true,this.value===null)return (0, Nt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return De.String}get isTruthy(){return this.value===null?(0, Nt.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==De.Int){let t=(0, Nv.tryParseInt)(this.value);if(t.exists)return new nn(t.result);throw this.BadCastException(e)}if(e==De.Float){let t=(0, Nv.tryParseFloat)(this.value);if(t.exists)return new rn(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};Te.StringValue=Cn;var no=class extends tn{constructor(e=null){super(e);}get valueType(){return De.DivertTarget}get targetPath(){return this.value===null?(0, Nt.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+")"}};Te.DivertTargetValue=no;var hd=class n extends tn{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, Nt.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return De.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)}};Te.VariablePointerValue=hd;var ro=class n extends tn{get isTruthy(){return this.value===null?(0, Nt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return De.List}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==De.Int){let t=this.value.maxItem;return t.Key.isNull?new nn(0):new nn(t.Value)}else if(e==De.Float){let t=this.value.maxItem;return t.Key.isNull?new rn(0):new rn(t.Value)}else if(e==De.String){let t=this.value.maxItem;return t.Key.isNull?new Cn(""):new Cn(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new pr.InkList:e instanceof pr.InkList?this.value=new pr.InkList(e):e instanceof pr.InkListItem&&typeof t=="number"&&(this.value=new pr.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, cs.asOrNull)(e,n),i=(0, cs.asOrNull)(t,n);if(i&&i.value===null)return (0, Nt.throwNullException)("newList.value");if(r&&r.value===null)return (0, Nt.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};Te.ListValue=ro;var De;(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";})(De||(Te.ValueType=De={}));});var Fv=w(io=>{Object.defineProperty(io,"__esModule",{value:true});io.SearchResult=void 0;var EP=ke(),dd=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof EP.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};io.SearchResult=dd;});var ke=w(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.Container=void 0;var wP=Oe(),Iv=Ye(),AP=fr(),ii=mt(),DP=Fv(),kv=pt(),Rv=os(),xP=ni(),Vn=fe(),hs=class n extends ii.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, Vn.asOrThrows)(r,ii.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, Vn.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, Vn.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 kv.Path.Component(0)),t=t.content[0]);return new kv.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, Vn.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Rv.Debug.AssertType(e,ii.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Vn.asOrThrows)(e,ii.InkObject);if(t.parent=this,e.name===null)return (0, Iv.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new DP.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, Vn.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, Iv.throwNullException)("component.name");let t=(0, xP.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Vn.asOrThrows)(t.result,ii.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new AP.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 wP.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, Vn.asOrThrows)(o,ii.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Rv.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};ds.Container=hs;(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={}));})(hs||(ds.Container=hs={}));});var Qe=w(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.ControlCommand=void 0;var PP=mt(),fs=class n extends PP.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()}};ps.ControlCommand=fs;(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={}));})(fs||(ps.ControlCommand=fs={}));});var Ft=w(so=>{Object.defineProperty(so,"__esModule",{value:true});so.Expression=void 0;var $v=ke(),fd=Qe(),OP=xe(),pd=class extends OP.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new $v.Container;return e.AddContent(fd.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(fd.ControlCommand.EvalOutput()),e.AddContent(fd.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new $v.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}};so.Expression=pd;});var mr=w(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.Void=void 0;var TP=mt(),md=class extends TP.InkObject{toString(){return "Void"}};ao.Void=md;});var sn=w(uo=>{Object.defineProperty(uo,"__esModule",{value:true});uo.NativeFunctionCall=void 0;var V=Oe(),ms=ls(),NP=mr(),oo=yt(),FP=mt(),It=fe(),vt=Ye(),ne=class n extends FP.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, vt.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, vt.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 NP.Void)throw new ms.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 V.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==V.ValueType.Int?this.CallType(r):i==V.ValueType.Float?this.CallType(r):i==V.ValueType.String?this.CallType(r):i==V.ValueType.DivertTarget?this.CallType(r):i==V.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, It.asOrThrows)(e[0],V.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=V.ValueType[r];throw new ms.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, It.asOrThrows)(e[1],V.Value),l=s;if(i.value===null||u.value===null)return (0, vt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return V.Value.Create(c)}else {let o=s;if(i.value===null)return (0, vt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?V.Value.Create(u,V.ValueType.Int):this.name===n.Float?V.Value.Create(u,V.ValueType.Float):V.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 V.ListValue&&e[1]instanceof V.IntValue)return this.CallListIncrementOperation(e);let t=(0, It.asOrThrows)(e[0],V.Value),r=(0, It.asOrThrows)(e[1],V.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=V.ValueType.List||r.valueType!=V.ValueType.List)){if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(V.ValueType.Int);if(i===null)return (0, vt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, It.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new V.BoolValue(a)}if(t.valueType==V.ValueType.List&&r.valueType==V.ValueType.List)return this.CallType([t,r]);throw new ms.StoryException("Can not call use "+this.name+" operation on "+V.ValueType[t.valueType]+" and "+V.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, It.asOrThrows)(e[0],V.ListValue),r=(0, It.asOrThrows)(e[1],V.IntValue),i=new oo.InkList;if(t.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=oo.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(V.ValueType.Int);if(r.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, vt.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,oo.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new V.ListValue(i)}CoerceValuesToSingleType(e){let t=V.ValueType.Int,r=null;for(let a of e){let s=(0, It.asOrThrows)(a,V.Value);s.valueType>t&&(t=s.valueType),s.valueType==V.ValueType.List&&(r=(0, It.asOrNull)(s,V.ListValue));}let i=[];if(V.ValueType[t]==V.ValueType[V.ValueType.List])for(let a of e){let s=(0, It.asOrThrows)(a,V.Value);if(s.valueType==V.ValueType.List)i.push(s);else if(s.valueType==V.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, It.asOrThrows)(r,V.ListValue),r.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, vt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,oo.InkListItem.Null);if(l.exists){let c=new V.ListValue(l.result,o);i.push(c);}else throw new ms.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=V.ValueType[s.valueType];throw new ms.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, It.asOrThrows)(a,V.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,V.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,V.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, vt.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,V.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};uo.NativeFunctionCall=ne;ne.Add="+";ne.Subtract="-";ne.Divide="/";ne.Multiply="*";ne.Mod="%";ne.Negate="_";ne.Equal="==";ne.Greater=">";ne.Less="<";ne.GreaterThanOrEquals=">=";ne.LessThanOrEquals="<=";ne.NotEquals="!=";ne.Not="!";ne.And="&&";ne.Or="||";ne.Min="MIN";ne.Max="MAX";ne.Pow="POW";ne.Floor="FLOOR";ne.Ceiling="CEILING";ne.Int="INT";ne.Float="FLOAT";ne.Has="?";ne.Hasnt="!?";ne.Intersect="^";ne.ListMin="LIST_MIN";ne.ListMax="LIST_MAX";ne.All="LIST_ALL";ne.Count="LIST_COUNT";ne.ValueOfList="LIST_VALUE";ne.Invert="LIST_INVERT";ne._nativeFunctions=null;});var co=w(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.NumberExpression=void 0;var IP=Ft(),gd=Oe(),kP=fe(),yd=class n extends IP.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 gd.IntValue(this.value)):this.isFloat()?r.AddContent(new gd.FloatValue(this.value)):this.isBool()&&r.AddContent(new gd.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, kP.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};lo.NumberExpression=yd;});var vd=w(ho=>{Object.defineProperty(ho,"__esModule",{value:true});ho.UnaryExpression=void 0;var RP=Ft(),$P=sn(),si=co(),VP=fe(),gs=class extends RP.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($P.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};ho.UnaryExpression=gs;gs.WithInner=(n,e)=>{let t=(0, VP.asOrNull)(n,si.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new si.NumberExpression(-t.value,"int");if(t.isFloat())return new si.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new si.NumberExpression(t.value==0,"bool");if(t.isFloat())return new si.NumberExpression(t.value==0,"bool");if(t.isBool())return new si.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new gs(n,e)};});var bd=w(fo=>{Object.defineProperty(fo,"__esModule",{value:true});fo.BinaryExpression=void 0;var jP=Ft(),LP=sn(),qP=vd(),BP=fe(),Cd=class extends jP.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(LP.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, BP.asOrNull)(this.leftExpression,qP.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.`);}}};fo.BinaryExpression=Cd;});var vs=w(po=>{Object.defineProperty(po,"__esModule",{value:true});po.CharacterSet=void 0;var ys=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);}};po.CharacterSet=ys;ys.FromRange=(n,e)=>new ys().AddRange(n,e);});var jv=w(mo=>{Object.defineProperty(mo,"__esModule",{value:true});mo.CharacterRange=void 0;var Vv=vs(),Cs=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Vv.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 Vv.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}};mo.CharacterRange=Cs;Cs.Define=(n,e,t=[])=>new Cs(n,e,t);});var yo=w(go=>{Object.defineProperty(go,"__esModule",{value:true});go.ChoicePoint=void 0;var MP=mt(),WP=pt(),_d=Ye(),Sd=class extends MP.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, _d.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, _d.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new WP.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, _d.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};go.ChoicePoint=Sd;});var gr=w(vo=>{Object.defineProperty(vo,"__esModule",{value:true});vo.PushPopType=void 0;var Lv;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Lv||(vo.PushPopType=Lv={}));});var bs=w(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.Pointer=void 0;var GP=pt(),Ed=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 GP.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)}};Co.Pointer=Ed;});var an=w(_o=>{Object.defineProperty(_o,"__esModule",{value:true});_o.Divert=void 0;var HP=pt(),JP=gr(),zP=fr(),UP=mt(),wd=bs(),qv=ke(),bo=Ye(),Ad=class n extends UP.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=wd.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, bo.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, bo.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, bo.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof qv.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=wd.Pointer.StartOf(e instanceof qv.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 HP.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=wd.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, bo.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 zP.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==JP.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};_o.Divert=Ad;});var bn=w(So=>{Object.defineProperty(So,"__esModule",{value:true});So.SymbolType=void 0;var Bv;(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";})(Bv||(So.SymbolType=Bv={}));});var jn=w(Eo=>{Object.defineProperty(Eo,"__esModule",{value:true});Eo.VariableAssignment=void 0;var KP=mt(),Dd=class extends KP.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Eo.VariableAssignment=Dd;});var ai=w(Ao=>{Object.defineProperty(Ao,"__esModule",{value:true});Ao.Choice=void 0;var XP=yo(),wo=ke(),Ln=Qe(),xd=an(),Mv=Oe(),YP=xe(),QP=bn(),Wv=jn(),Pd=class extends YP.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 wo.Container,this._runtimeChoice=new XP.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(Ln.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Mv.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Wv.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(Ln.ControlCommand.BeginString()),this._divertToStartContentOuter=new xd.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new xd.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new wo.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(Ln.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(Ln.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(Ln.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(Ln.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new wo.Container,this.startContent){this._returnToR2=new Mv.DivertTargetValue,this._innerContentContainer.AddContent(Ln.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(Ln.ControlCommand.EvalEnd());let i=new Wv.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new xd.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new wo.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,QP.SymbolType.SubFlowAndWeave);}};Ao.Choice=Pd;});var Gv=w(xo=>{Object.defineProperty(xo,"__esModule",{value:true});xo.StringParserElement=void 0;var Do=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;};}};xo.StringParserElement=Do;Do._uniqueIdCounter=1e3;});var Jv=w(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.StringParserState=void 0;var Hv=Gv(),Od=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 Hv.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 Hv.StringParserElement;this._numElements=1;}};Po.StringParserState=Od;});var Nd=w(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.StringParser=yr.ParseSuccess=void 0;var Td=vs(),ZP=Jv();yr.ParseSuccess=Symbol("ParseSuccessStruct");var _s=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 HA={keyword:"dependencies",type:"object",schemaType:"object",error:Yt.error,code(n){let[e,t]=JA(n);_y(n,e),Sy(n,t);}};function JA({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 _y(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, as.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, as.checkReportMissingProp)(n,l);}):(t.if((0, yh._)`${u} && (${(0, as.checkMissingProp)(n,o,a)})`),(0, as.reportMissingProp)(n,a),t.else());}}Yt.validatePropertyDeps=_y;function Sy(n,e=n.schema){let{gen:t,data:r,keyword:i,it:a}=n,s=t.name("valid");for(let o in e)(0, GA.alwaysValidSchema)(a,e[o])||(t.if((0, as.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));}Yt.validateSchemaDeps=Sy;Yt.default=HA;});var wy=S(vh=>{Object.defineProperty(vh,"__esModule",{value:true});var Ey=M(),zA=Y(),UA={message:"property name must be valid",params:({params:n})=>(0, Ey._)`{propertyName: ${n.propertyName}}`},KA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:UA,code(n){let{gen:e,schema:t,data:r,it:i}=n;if((0, zA.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, Ey.not)(a),()=>{n.error(true),i.allErrors||e.break();});}),n.ok(a);}};vh.default=KA;});var bh=S(Ch=>{Object.defineProperty(Ch,"__esModule",{value:true});var $a=Pt(),Mt=M(),XA=xt(),Va=Y(),YA={message:"must NOT have additional properties",params:({params:n})=>(0, Mt._)`{additionalProperty: ${n.additionalProperty}}`},QA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:YA,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, Va.alwaysValidSchema)(s,t))return;let l=(0, $a.allSchemaProperties)(r.properties),c=(0, $a.allSchemaProperties)(r.patternProperties);h(),n.ok((0, Mt._)`${a} === ${XA.default.errors}`);function h(){e.forIn("key",i,C=>{!l.length&&!c.length?p(C):e.if(f(C),()=>p(C));});}function f(C){let b;if(l.length>8){let y=(0, Va.schemaRefOrVal)(s,r.properties,"properties");b=(0, $a.isOwnProperty)(e,y,C);}else l.length?b=(0, Mt.or)(...l.map(y=>(0, Mt._)`${C} === ${y}`)):b=Mt.nil;return c.length&&(b=(0, Mt.or)(b,...c.map(y=>(0, Mt._)`${(0, $a.usePattern)(n,y)}.test(${C})`))),(0, Mt.not)(b)}function g(C){e.code((0, Mt._)`delete ${i}[${C}]`);}function p(C){if(u.removeAdditional==="all"||u.removeAdditional&&t===false){g(C);return}if(t===false){n.setParams({additionalProperty:C}),n.error(),o||e.break();return}if(typeof t=="object"&&!(0, Va.alwaysValidSchema)(s,t)){let b=e.name("valid");u.removeAdditional==="failing"?(m(C,b,false),e.if((0, Mt.not)(b),()=>{n.reset(),g(C);})):(m(C,b),o||e.if((0, Mt.not)(b),()=>e.break()));}}function m(C,b,y){let d={keyword:"additionalProperties",dataProp:C,dataPropType:Va.Type.Str};y===false&&Object.assign(d,{compositeRule:true,createErrors:false,allErrors:false}),n.subschema(d,b);}}};Ch.default=QA;});var xy=S(Sh=>{Object.defineProperty(Sh,"__esModule",{value:true});var ZA=Br(),Ay=Pt(),_h=Y(),Dy=bh(),eD={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&&Dy.default.code(new ZA.KeywordCxt(a,Dy.default,"additionalProperties"));let s=(0, Ay.allSchemaProperties)(t);for(let h of s)a.definedProperties.add(h);a.opts.unevaluated&&s.length&&a.props!==true&&(a.props=_h.mergeEvaluated.props(e,(0, _h.toHash)(s),a.props));let o=s.filter(h=>!(0, _h.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, Ay.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);}}};Sh.default=eD;});var Ny=S(Eh=>{Object.defineProperty(Eh,"__esModule",{value:true});var Py=Pt(),ja=M(),Oy=Y(),Ty=Y(),tD={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, Py.allSchemaProperties)(t),u=o.filter(m=>(0, Oy.alwaysValidSchema)(a,t[m]));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 ja.Name)&&(a.props=(0, Ty.evaluatedPropsToName)(e,a.props));let{props:h}=a;f();function f(){for(let m of o)l&&g(m),a.allErrors?p(m):(e.var(c,true),p(m),e.if(c));}function g(m){for(let C in l)new RegExp(m).test(C)&&(0, Oy.checkStrictMode)(a,`property ${C} matches pattern ${m} (use allowMatchingProperties)`);}function p(m){e.forIn("key",r,C=>{e.if((0, ja._)`${(0, Py.usePattern)(n,m)}.test(${C})`,()=>{let b=u.includes(m);b||n.subschema({keyword:"patternProperties",schemaProp:m,dataProp:C,dataPropType:Ty.Type.Str},c),a.opts.unevaluated&&h!==true?e.assign((0, ja._)`${h}[${C}]`,true):!b&&!a.allErrors&&e.if((0, ja.not)(c),()=>e.break());});});}}};Eh.default=tD;});var Fy=S(wh=>{Object.defineProperty(wh,"__esModule",{value:true});var nD=Y(),rD={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(n){let{gen:e,schema:t,it:r}=n;if((0, nD.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"}};wh.default=rD;});var Iy=S(Ah=>{Object.defineProperty(Ah,"__esModule",{value:true});var iD=Pt(),sD={keyword:"anyOf",schemaType:"array",trackErrors:true,code:iD.validateUnion,error:{message:"must match a schema in anyOf"}};Ah.default=sD;});var ky=S(Dh=>{Object.defineProperty(Dh,"__esModule",{value:true});var La=M(),aD=Y(),oD={message:"must match exactly one schema in oneOf",params:({params:n})=>(0, La._)`{passingSchemas: ${n.passing}}`},uD={keyword:"oneOf",schemaType:"array",trackErrors:true,error:oD,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, aD.alwaysValidSchema)(i,c)?e.var(u,true):f=n.subschema({keyword:"oneOf",schemaProp:h,compositeRule:true},u),h>0&&e.if((0, La._)`${u} && ${s}`).assign(s,false).assign(o,(0, La._)`[${o}, ${h}]`).else(),e.if(u,()=>{e.assign(s,true),e.assign(o,h),f&&n.mergeEvaluated(f,La.Name);});});}}};Dh.default=uD;});var Ry=S(xh=>{Object.defineProperty(xh,"__esModule",{value:true});var lD=Y(),cD={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, lD.alwaysValidSchema)(r,a))return;let o=n.subschema({keyword:"allOf",schemaProp:s},i);n.ok(i),n.mergeEvaluated(o);});}};xh.default=cD;});var jy=S(Ph=>{Object.defineProperty(Ph,"__esModule",{value:true});var qa=M(),Vy=Y(),hD={message:({params:n})=>(0, qa.str)`must match "${n.ifClause}" schema`,params:({params:n})=>(0, qa._)`{failingKeyword: ${n.ifClause}}`},dD={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:hD,code(n){let{gen:e,parentSchema:t,it:r}=n;t.then===void 0&&t.else===void 0&&(0, Vy.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=$y(r,"then"),a=$y(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, qa.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, qa._)`${c}`):n.setParams({ifClause:c});}}}};function $y(n,e){let t=n.schema[e];return t!==void 0&&!(0, Vy.alwaysValidSchema)(n,t)}Ph.default=dD;});var Ly=S(Oh=>{Object.defineProperty(Oh,"__esModule",{value:true});var fD=Y(),pD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:e,it:t}){e.if===void 0&&(0, fD.checkStrictMode)(t,`"${n}" without "if" is ignored`);}};Oh.default=pD;});var Nh=S(Th=>{Object.defineProperty(Th,"__esModule",{value:true});var mD=dh(),gD=yy(),yD=fh(),vD=Cy(),CD=by(),bD=Ra(),_D=wy(),SD=bh(),ED=xy(),wD=Ny(),AD=Fy(),DD=Iy(),xD=ky(),PD=Ry(),OD=jy(),TD=Ly();function ND(n=false){let e=[AD.default,DD.default,xD.default,PD.default,OD.default,TD.default,_D.default,SD.default,bD.default,ED.default,wD.default];return n?e.push(gD.default,vD.default):e.push(mD.default,yD.default),e.push(CD.default),e}Th.default=ND;});var qy=S(Fh=>{Object.defineProperty(Fh,"__esModule",{value:true});var Ie=M(),FD={message:({schemaCode:n})=>(0, Ie.str)`must match format "${n}"`,params:({schemaCode:n})=>(0, Ie._)`{format: ${n}}`},ID={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:FD,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():g();function f(){let p=t.scopeValue("formats",{ref:h.formats,code:u.code.formats}),m=t.const("fDef",(0, Ie._)`${p}[${s}]`),C=t.let("fType"),b=t.let("format");t.if((0, Ie._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>t.assign(C,(0, Ie._)`${m}.type || "string"`).assign(b,(0, Ie._)`${m}.validate`),()=>t.assign(C,(0, Ie._)`"string"`).assign(b,m)),n.fail$data((0, Ie.or)(y(),d()));function y(){return u.strictSchema===false?Ie.nil:(0, Ie._)`${s} && !${b}`}function d(){let _=c.$async?(0, Ie._)`(${m}.async ? await ${b}(${r}) : ${b}(${r}))`:(0, Ie._)`${b}(${r})`,v=(0, Ie._)`(typeof ${b} == "function" ? ${_} : ${b}.test(${r}))`;return (0, Ie._)`${b} && ${b} !== true && ${C} === ${e} && !${v}`}}function g(){let p=h.formats[a];if(!p){y();return}if(p===true)return;let[m,C,b]=d(p);m===e&&n.pass(_());function y(){if(u.strictSchema===false){h.logger.warn(v());return}throw new Error(v());function v(){return `unknown format "${a}" ignored in schema at path "${l}"`}}function d(v){let w=v instanceof RegExp?(0, Ie.regexpCode)(v):u.code.formats?(0, Ie._)`${u.code.formats}${(0, Ie.getProperty)(a)}`:void 0,D=t.scopeValue("formats",{key:a,ref:v,code:w});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0, Ie._)`${D}.validate`]:["string",v,D]}function _(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!c.$async)throw new Error("async format in sync schema");return (0, Ie._)`await ${b}(${r})`}return typeof C=="function"?(0, Ie._)`${b}(${r})`:(0, Ie._)`${b}.test(${r})`}}}};Fh.default=ID;});var kh=S(Ih=>{Object.defineProperty(Ih,"__esModule",{value:true});var kD=qy(),RD=[kD.default];Ih.default=RD;});var Rh=S(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.contentVocabulary=zr.metadataVocabulary=void 0;zr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var My=S($h=>{Object.defineProperty($h,"__esModule",{value:true});var $D=Uc(),VD=ch(),jD=Nh(),LD=kh(),By=Rh(),qD=[$D.default,VD.default,(0, jD.default)(),LD.default,By.metadataVocabulary,By.contentVocabulary];$h.default=qD;});var Gy=S(Ba=>{Object.defineProperty(Ba,"__esModule",{value:true});Ba.DiscrError=void 0;var Wy;(function(n){n.Tag="tag",n.Mapping="mapping";})(Wy||(Ba.DiscrError=Wy={}));});var Lh=S(jh=>{Object.defineProperty(jh,"__esModule",{value:true});var Ur=M(),Vh=Gy(),Hy=Ji(),BD=Mr(),MD=Y(),WD={message:({params:{discrError:n,tagName:e}})=>n===Vh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:n,tag:e,tagName:t}})=>(0, Ur._)`{error: ${n}, tag: ${t}, tagValue: ${e}}`},GD={keyword:"discriminator",type:"object",schemaType:"object",error:WD,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, Ur._)`${t}${(0, Ur.getProperty)(o)}`);e.if((0, Ur._)`typeof ${l} == "string"`,()=>c(),()=>n.error(false,{discrError:Vh.DiscrError.Tag,tag:l,tagName:o})),n.ok(u);function c(){let g=f();e.if(false);for(let p in g)e.elseIf((0, Ur._)`${l} === ${p}`),e.assign(u,h(g[p]));e.else(),n.error(false,{discrError:Vh.DiscrError.Mapping,tag:l,tagName:o}),e.endIf();}function h(g){let p=e.name("valid"),m=n.subschema({keyword:"oneOf",schemaProp:g},p);return n.mergeEvaluated(m,Ur.Name),p}function f(){var g;let p={},m=b(i),C=true;for(let _=0;_<s.length;_++){let v=s[_];if(v?.$ref&&!(0, MD.schemaHasRulesButRef)(v,a.self.RULES)){let D=v.$ref;if(v=Hy.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,D),v instanceof Hy.SchemaEnv&&(v=v.schema),v===void 0)throw new BD.default(a.opts.uriResolver,a.baseId,D)}let w=(g=v?.properties)===null||g===void 0?void 0:g[o];if(typeof w!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${o}"`);C=C&&(m||b(v)),y(w,_);}if(!C)throw new Error(`discriminator: "${o}" must be required`);return p;function b({required:_}){return Array.isArray(_)&&_.includes(o)}function y(_,v){if(_.const)d(_.const,v);else if(_.enum)for(let w of _.enum)d(w,v);else throw new Error(`discriminator: "properties/${o}" must have "const" or "enum"`)}function d(_,v){if(typeof _!="string"||_ in p)throw new Error(`discriminator: "${o}" values must be unique strings`);p[_]=v;}}}};jh.default=GD;});var Jy=S((LV,HD)=>{HD.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 Uy=S((we,qh)=>{Object.defineProperty(we,"__esModule",{value:true});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv=void 0;var JD=Hc(),zD=My(),UD=Lh(),zy=Jy(),KD=["/properties"],Ma="http://json-schema.org/draft-07/schema",Kr=class extends JD.default{_addVocabularies(){super._addVocabularies(),zD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(UD.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(zy,KD):zy;this.addMetaSchema(e,Ma,false),this.refs["http://json-schema.org/schema"]=Ma;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ma)?Ma:void 0)}};we.Ajv=Kr;qh.exports=we=Kr;qh.exports.Ajv=Kr;Object.defineProperty(we,"__esModule",{value:true});we.default=Kr;var XD=Br();Object.defineProperty(we,"KeywordCxt",{enumerable:true,get:function(){return XD.KeywordCxt}});var Xr=M();Object.defineProperty(we,"_",{enumerable:true,get:function(){return Xr._}});Object.defineProperty(we,"str",{enumerable:true,get:function(){return Xr.str}});Object.defineProperty(we,"stringify",{enumerable:true,get:function(){return Xr.stringify}});Object.defineProperty(we,"nil",{enumerable:true,get:function(){return Xr.nil}});Object.defineProperty(we,"Name",{enumerable:true,get:function(){return Xr.Name}});Object.defineProperty(we,"CodeGen",{enumerable:true,get:function(){return Xr.CodeGen}});var YD=Hi();Object.defineProperty(we,"ValidationError",{enumerable:true,get:function(){return YD.default}});var QD=Mr();Object.defineProperty(we,"MissingRefError",{enumerable:true,get:function(){return QD.default}});});var Mh=S(os=>{Object.defineProperty(os,"__esModule",{value:true});os.dynamicAnchor=void 0;var Bh=M(),ZD=xt(),Ky=Ji(),ex=Oa(),tx={keyword:"$dynamicAnchor",schemaType:"string",code:n=>Xy(n,n.schema)};function Xy(n,e){let{gen:t,it:r}=n;r.schemaEnv.root.dynamicAnchors[e]=true;let i=(0, Bh._)`${ZD.default.dynamicAnchors}${(0, Bh.getProperty)(e)}`,a=r.errSchemaPath==="#"?r.validateName:nx(n);t.if((0, Bh._)`!${i}`,()=>t.assign(i,a));}os.dynamicAnchor=Xy;function nx(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 Ky.SchemaEnv({schema:t,schemaId:u,root:i,baseId:a,localRefs:s,meta:o});return Ky.compileSchema.call(r,l),(0, ex.getValidate)(n,l)}os.default=tx;});var Wh=S(us=>{Object.defineProperty(us,"__esModule",{value:true});us.dynamicRef=void 0;var Yy=M(),rx=xt(),Qy=Oa(),ix={keyword:"$dynamicRef",schemaType:"string",code:n=>Zy(n,n.schema)};function Zy(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, Yy._)`${rx.default.dynamicAnchors}${(0, Yy.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, Qy.callRef)(n,u),t.let(l,true);}):()=>(0, Qy.callRef)(n,u)}}us.dynamicRef=Zy;us.default=ix;});var ev=S(Gh=>{Object.defineProperty(Gh,"__esModule",{value:true});var sx=Mh(),ax=Y(),ox={keyword:"$recursiveAnchor",schemaType:"boolean",code(n){n.schema?(0, sx.dynamicAnchor)(n,""):(0, ax.checkStrictMode)(n.it,"$recursiveAnchor: false is ignored");}};Gh.default=ox;});var tv=S(Hh=>{Object.defineProperty(Hh,"__esModule",{value:true});var ux=Wh(),lx={keyword:"$recursiveRef",schemaType:"string",code:n=>(0, ux.dynamicRef)(n,n.schema)};Hh.default=lx;});var nv=S(Jh=>{Object.defineProperty(Jh,"__esModule",{value:true});var cx=Mh(),hx=Wh(),dx=ev(),fx=tv(),px=[cx.default,hx.default,dx.default,fx.default];Jh.default=px;});var iv=S(zh=>{Object.defineProperty(zh,"__esModule",{value:true});var rv=Ra(),mx={keyword:"dependentRequired",type:"object",schemaType:"object",error:rv.error,code:n=>(0, rv.validatePropertyDeps)(n)};zh.default=mx;});var sv=S(Uh=>{Object.defineProperty(Uh,"__esModule",{value:true});var gx=Ra(),yx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0, gx.validateSchemaDeps)(n)};Uh.default=yx;});var av=S(Kh=>{Object.defineProperty(Kh,"__esModule",{value:true});var vx=Y(),Cx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:e,it:t}){e.contains===void 0&&(0, vx.checkStrictMode)(t,`"${n}" without "contains" is ignored`);}};Kh.default=Cx;});var ov=S(Xh=>{Object.defineProperty(Xh,"__esModule",{value:true});var bx=iv(),_x=sv(),Sx=av(),Ex=[bx.default,_x.default,Sx.default];Xh.default=Ex;});var lv=S(Yh=>{Object.defineProperty(Yh,"__esModule",{value:true});var $n=M(),uv=Y(),wx=xt(),Ax={message:"must NOT have unevaluated properties",params:({params:n})=>(0, $n._)`{unevaluatedProperty: ${n.unevaluatedProperty}}`},Dx={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:true,error:Ax,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 $n.Name?e.if((0, $n._)`${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, $n._)`${i} === ${wx.default.errors}`);function u(h){if(t===false){n.setParams({unevaluatedProperty:h}),n.error(),s||e.break();return}if(!(0, uv.alwaysValidSchema)(a,t)){let f=e.name("valid");n.subschema({keyword:"unevaluatedProperties",dataProp:h,dataPropType:uv.Type.Str},f),s||e.if((0, $n.not)(f),()=>e.break());}}function l(h,f){return (0, $n._)`!${h} || !${h}[${f}]`}function c(h,f){let g=[];for(let p in h)h[p]===true&&g.push((0, $n._)`${f} !== ${p}`);return (0, $n.and)(...g)}}};Yh.default=Dx;});var hv=S(Qh=>{Object.defineProperty(Qh,"__esModule",{value:true});var fr=M(),cv=Y(),xx={message:({params:{len:n}})=>(0, fr.str)`must NOT have more than ${n} items`,params:({params:{len:n}})=>(0, fr._)`{limit: ${n}}`},Px={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:xx,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, fr._)`${r}.length`);if(t===false)n.setParams({len:a}),n.fail((0, fr._)`${s} > ${a}`);else if(typeof t=="object"&&!(0, cv.alwaysValidSchema)(i,t)){let u=e.var("valid",(0, fr._)`${s} <= ${a}`);e.if((0, fr.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:cv.Type.Num},u),i.allErrors||e.if((0, fr.not)(u),()=>e.break());});}}};Qh.default=Px;});var dv=S(Zh=>{Object.defineProperty(Zh,"__esModule",{value:true});var Ox=lv(),Tx=hv(),Nx=[Ox.default,Tx.default];Zh.default=Nx;});var pv=S(ed=>{Object.defineProperty(ed,"__esModule",{value:true});var Fx=Uc(),Ix=ch(),kx=Nh(),Rx=nv(),$x=ov(),Vx=dv(),jx=kh(),fv=Rh(),Lx=[Rx.default,Fx.default,Ix.default,(0, kx.default)(true),jx.default,fv.metadataVocabulary,fv.contentVocabulary,$x.default,Vx.default];ed.default=Lx;});var mv=S((ZV,qx)=>{qx.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 gv=S((ej,Bx)=>{Bx.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 yv=S((tj,Mx)=>{Mx.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 vv=S((nj,Wx)=>{Wx.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 Cv=S((rj,Gx)=>{Gx.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 bv=S((ij,Hx)=>{Hx.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 _v=S((sj,Jx)=>{Jx.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 Sv=S((aj,zx)=>{zx.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 Ev=S(td=>{Object.defineProperty(td,"__esModule",{value:true});var Ux=mv(),Kx=gv(),Xx=yv(),Yx=vv(),Qx=Cv(),Zx=bv(),eP=_v(),tP=Sv(),nP=["/properties"];function rP(n){return [Ux,Kx,Xx,Yx,Qx,e(this,Zx),eP,e(this,tP)].forEach(t=>this.addMetaSchema(t,void 0,false)),this;function e(t,r){return n?t.$dataMetaSchema(r,nP):r}}td.default=rP;});var wv=S((Ae,rd)=>{Object.defineProperty(Ae,"__esModule",{value:true});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv2020=void 0;var iP=Hc(),sP=pv(),aP=Lh(),oP=Ev(),nd="https://json-schema.org/draft/2020-12/schema",Yr=class extends iP.default{constructor(e={}){super({...e,dynamicRef:true,next:true,unevaluated:true});}_addVocabularies(){super._addVocabularies(),sP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(aP.default);}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(oP.default.call(this,e),this.refs["http://json-schema.org/schema"]=nd);}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(nd)?nd:void 0)}};Ae.Ajv2020=Yr;rd.exports=Ae=Yr;rd.exports.Ajv2020=Yr;Object.defineProperty(Ae,"__esModule",{value:true});Ae.default=Yr;var uP=Br();Object.defineProperty(Ae,"KeywordCxt",{enumerable:true,get:function(){return uP.KeywordCxt}});var Qr=M();Object.defineProperty(Ae,"_",{enumerable:true,get:function(){return Qr._}});Object.defineProperty(Ae,"str",{enumerable:true,get:function(){return Qr.str}});Object.defineProperty(Ae,"stringify",{enumerable:true,get:function(){return Qr.stringify}});Object.defineProperty(Ae,"nil",{enumerable:true,get:function(){return Qr.nil}});Object.defineProperty(Ae,"Name",{enumerable:true,get:function(){return Qr.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:true,get:function(){return Qr.CodeGen}});var lP=Hi();Object.defineProperty(Ae,"ValidationError",{enumerable:true,get:function(){return lP.default}});var cP=Mr();Object.defineProperty(Ae,"MissingRefError",{enumerable:true,get:function(){return cP.default}});});var sd=S(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.CompilerOptions=void 0;var id=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;}};Wa.CompilerOptions=id;});var Av=S(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.DebugSourceRange=void 0;var ad=class{constructor(e,t,r){this.length=e,this.debugMetadata=t,this.text=r;}};Ga.DebugSourceRange=ad;});var pr=S(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.ErrorType=void 0;var Dv;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(Dv||(Ha.ErrorType=Dv={}));});var xv=S(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.Argument=void 0;var od=class{constructor(e=null,t=null,r=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=r;}get typeName(){return "Argument"}};Ja.Argument=od;});var fe=S(Be=>{Object.defineProperty(Be,"__esModule",{value:true});Be.filterUndef=Be.isEquatable=Be.nullIfUndefined=Be.asINamedContentOrNull=Be.asBooleanOrThrows=Be.asNumberOrThrows=Be.asOrThrows=Be.asOrNull=void 0;function hP(n,e){return n instanceof e?Pv(n):null}Be.asOrNull=hP;function dP(n,e){if(n instanceof e)return Pv(n);throw new Error(`${n} is not of type ${e}`)}Be.asOrThrows=dP;function fP(n){if(typeof n=="number")return n;throw new Error(`${n} is not a number`)}Be.asNumberOrThrows=fP;function pP(n){if(typeof n=="boolean")return n;throw new Error(`${n} is not a boolean`)}Be.asBooleanOrThrows=pP;function mP(n){return n.hasValidName&&n.name?n:null}Be.asINamedContentOrNull=mP;function gP(n){return typeof n>"u"?null:n}Be.nullIfUndefined=gP;function yP(n){return typeof n=="object"&&typeof n.Equals=="function"}Be.isEquatable=yP;function Pv(n,e){return n}function vP(n){return n!=null}Be.filterUndef=vP;});var Pe=S(za=>{Object.defineProperty(za,"__esModule",{value:true});za.ParsedObject=void 0;var Ov=fe(),ud=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, Ov.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, Ov.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;}}};za.ParsedObject=ud;});var Ka=S(Ua=>{Object.defineProperty(Ua,"__esModule",{value:true});Ua.AuthorWarning=void 0;var CP=Pe(),ld=class extends CP.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};Ua.AuthorWarning=ld;});var pt=S(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.Path=void 0;var Zr=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}};ls.Path=Zr;Zr.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;})(Zr||(ls.Path=Zr={}));});var cs=S(Xa=>{Object.defineProperty(Xa,"__esModule",{value:true});Xa.Debug=void 0;var Tv;(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;})(Tv||(Xa.Debug=Tv={}));});var Qe=S(ei=>{Object.defineProperty(ei,"__esModule",{value:true});ei.throwNullException=ei.NullException=void 0;var Ya=class extends Error{};ei.NullException=Ya;function bP(n){throw new Ya(`${n} is null or undefined`)}ei.throwNullException=bP;});var mt=S(Za=>{Object.defineProperty(Za,"__esModule",{value:true});Za.InkObject=void 0;var ti=pt(),hs=Re(),cd=cs(),ni=fe(),Qa=Qe(),hd=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 ti.Path;else {let e=[],t=this,r=(0, ni.asOrNull)(t.parent,hs.Container);for(;r!==null;){let i=(0, ni.asINamedContentOrNull)(t);if(i!=null&&i.hasValidName){if(i.name===null)return (0, Qa.throwNullException)("namedChild.name");e.unshift(new ti.Path.Component(i.name));}else e.unshift(new ti.Path.Component(r.content.indexOf(t)));t=r,r=(0, ni.asOrNull)(r.parent,hs.Container);}this._path=new ti.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, Qa.throwNullException)("path");if(e.isRelative){let t=(0, ni.asOrNull)(this,hs.Container);return t===null&&(cd.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, ni.asOrNull)(this.parent,hs.Container),cd.Debug.Assert(t!==null,"Expected parent to be a container"),cd.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, Qa.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, Qa.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(ti.Path.Component.ToParent());for(let u=i+1;u<e.componentCount;++u)s.push(e.GetComponent(u));return new ti.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, ni.asOrNull)(e,hs.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}};Za.InkObject=hd;});var mr=S(eo=>{Object.defineProperty(eo,"__esModule",{value:true});eo.StringBuilder=void 0;var dd=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="";}};eo.StringBuilder=dd;});var yt=S(ri=>{Object.defineProperty(ri,"__esModule",{value:true});ri.InkList=ri.InkListItem=void 0;var Qt=Qe(),_P=mr(),gt=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)}};ri.InkListItem=gt;var fd=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, Qt.throwNullException)("originStory.listDefinitions");let r=t.listDefinitions.TryListGetDefinition(e,null);if(r.exists){if(r.result===null)return (0, Qt.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, Qt.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 gt){let r=e;if(r.originName==null){this.AddItem(r.itemName);return}if(this.origins===null)return (0, Qt.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, Qt.throwNullException)("this.origins");for(let a of this.origins){if(r===null)return (0, Qt.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 gt(i.name,r),s=i.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(gt.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=gt.fromSerializedKey(e);if(t.originName===null)return (0, Qt.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:gt.Null,Value:0};for(let[t,r]of this){let i=gt.fromSerializedKey(t);(e.Key.isNull||r>e.Value)&&(e={Key:i,Value:r});}return e}get minItem(){let e={Key:gt.Null,Value:0};for(let[t,r]of this){let i=gt.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=gt.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=gt.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=gt.fromSerializedKey(t);e.push({Key:i,Value:r});}return e.sort((t,r)=>t.Key.originName===null?(0, Qt.throwNullException)("x.Key.originName"):r.Key.originName===null?(0, Qt.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 _P.StringBuilder;for(let r=0;r<e.length;r++){r>0&&t.Append(", ");let i=e[r].Key;if(i.itemName===null)return (0, Qt.throwNullException)("item.itemName");t.Append(i.itemName);}return t.toString()}valueOf(){return NaN}};ri.InkList=fd;});var ds=S(to=>{Object.defineProperty(to,"__esModule",{value:true});to.StoryException=void 0;var pd=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};to.StoryException=pd;});var ii=S(Vn=>{Object.defineProperty(Vn,"__esModule",{value:true});Vn.tryParseFloat=Vn.tryParseInt=Vn.tryGetValueFromMap=void 0;function SP(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}}Vn.tryGetValueFromMap=SP;function EP(n,e=0){let t=parseInt(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Vn.tryParseInt=EP;function wP(n,e=0){let t=parseFloat(n);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Vn.tryParseFloat=wP;});var Te=S(Ne=>{Object.defineProperty(Ne,"__esModule",{value:true});Ne.ValueType=Ne.ListValue=Ne.VariablePointerValue=Ne.DivertTargetValue=Ne.StringValue=Ne.FloatValue=Ne.IntValue=Ne.BoolValue=Ne.Value=Ne.AbstractValue=void 0;var Nv=mt(),Fv=pt(),gr=yt(),AP=ds(),fs=fe(),Iv=ii(),Nt=Qe(),no=class n extends Nv.InkObject{static Create(e,t){if(t){if(t===De.Int&&Number.isInteger(Number(e)))return new en(Number(e));if(t===De.Float&&!isNaN(e))return new tn(Number(e))}if(typeof e=="boolean")return new si(!!e);if(typeof e=="string")return new vn(String(e));if(Number.isInteger(Number(e)))return new en(Number(e));if(isNaN(e)){if(e instanceof Fv.Path)return new ro((0, fs.asOrThrows)(e,Fv.Path));if(e instanceof gr.InkList)return new io((0, fs.asOrThrows)(e,gr.InkList))}else return new tn(Number(e));return null}Copy(){return (0, fs.asOrThrows)(n.Create(this.valueObject),Nv.InkObject)}BadCastException(e){return new AP.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};Ne.AbstractValue=no;var Zt=class extends no{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Nt.throwNullException)("Value.value"):this.value.toString()}};Ne.Value=Zt;var si=class extends Zt{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return De.Bool}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Int)return new en(this.value?1:0);if(e==De.Float)return new tn(this.value?1:0);if(e==De.String)return new vn(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};Ne.BoolValue=si;var en=class extends Zt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return De.Int}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Bool)return new si(this.value!==0);if(e==De.Float)return new tn(this.value);if(e==De.String)return new vn(""+this.value);throw this.BadCastException(e)}};Ne.IntValue=en;var tn=class extends Zt{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return De.Float}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==De.Bool)return new si(this.value!==0);if(e==De.Int)return new en(this.value);if(e==De.String)return new vn(""+this.value);throw this.BadCastException(e)}};Ne.FloatValue=tn;var vn=class extends Zt{constructor(e){if(super(e||""),this._isNewline=this.value==`
10
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Nt.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return De.String}get isTruthy(){return this.value===null?(0, Nt.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==De.Int){let t=(0, Iv.tryParseInt)(this.value);if(t.exists)return new en(t.result);throw this.BadCastException(e)}if(e==De.Float){let t=(0, Iv.tryParseFloat)(this.value);if(t.exists)return new tn(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};Ne.StringValue=vn;var ro=class extends Zt{constructor(e=null){super(e);}get valueType(){return De.DivertTarget}get targetPath(){return this.value===null?(0, Nt.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+")"}};Ne.DivertTargetValue=ro;var md=class n extends Zt{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, Nt.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return De.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)}};Ne.VariablePointerValue=md;var io=class n extends Zt{get isTruthy(){return this.value===null?(0, Nt.throwNullException)("this.value"):this.value.Count>0}get valueType(){return De.List}Cast(e){if(this.value===null)return (0, Nt.throwNullException)("Value.value");if(e==De.Int){let t=this.value.maxItem;return t.Key.isNull?new en(0):new en(t.Value)}else if(e==De.Float){let t=this.value.maxItem;return t.Key.isNull?new tn(0):new tn(t.Value)}else if(e==De.String){let t=this.value.maxItem;return t.Key.isNull?new vn(""):new vn(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new gr.InkList:e instanceof gr.InkList?this.value=new gr.InkList(e):e instanceof gr.InkListItem&&typeof t=="number"&&(this.value=new gr.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let r=(0, fs.asOrNull)(e,n),i=(0, fs.asOrNull)(t,n);if(i&&i.value===null)return (0, Nt.throwNullException)("newList.value");if(r&&r.value===null)return (0, Nt.throwNullException)("oldList.value");r&&i&&i.value.Count==0&&i.value.SetInitialOriginNames(r.value.originNames);}};Ne.ListValue=io;var De;(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";})(De||(Ne.ValueType=De={}));});var kv=S(so=>{Object.defineProperty(so,"__esModule",{value:true});so.SearchResult=void 0;var DP=Re(),gd=class n{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof DP.Container?this.obj:null}copy(){let e=new n;return e.obj=this.obj,e.approximate=this.approximate,e}};so.SearchResult=gd;});var Re=S(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.Container=void 0;var xP=Te(),Rv=Qe(),PP=mr(),ai=mt(),OP=kv(),$v=pt(),Vv=cs(),TP=ii(),jn=fe(),ps=class n extends ai.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, jn.asOrThrows)(r,ai.InkObject);e.set(t,i);}for(let t of this.content){let r=(0, jn.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, jn.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 $v.Path.Component(0)),t=t.content[0]);return new $v.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, jn.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Vv.Debug.AssertType(e,ai.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, jn.asOrThrows)(e,ai.InkObject);if(t.parent=this,e.name===null)return (0, Rv.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,r=-1){r==-1&&(r=e.length);let i=new OP.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, jn.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, Rv.throwNullException)("component.name");let t=(0, TP.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, jn.asOrThrows)(t.result,ai.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new PP.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 xP.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, jn.asOrThrows)(o,ai.InkObject))>=0||a.set(s,o);if(a.size>0){i(),e.AppendLine("-- named: --");for(let[,s]of a)Vv.Debug.AssertType(s,n,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,r),e.AppendLine();}t--,i(),e.Append("]");}};ms.Container=ps;(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={}));})(ps||(ms.Container=ps={}));});var Ze=S(ys=>{Object.defineProperty(ys,"__esModule",{value:true});ys.ControlCommand=void 0;var NP=mt(),gs=class n extends NP.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()}};ys.ControlCommand=gs;(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={}));})(gs||(ys.ControlCommand=gs={}));});var Ft=S(ao=>{Object.defineProperty(ao,"__esModule",{value:true});ao.Expression=void 0;var jv=Re(),yd=Ze(),FP=Pe(),vd=class extends FP.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new jv.Container;return e.AddContent(yd.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(yd.ControlCommand.EvalOutput()),e.AddContent(yd.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new jv.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}};ao.Expression=vd;});var yr=S(oo=>{Object.defineProperty(oo,"__esModule",{value:true});oo.Void=void 0;var IP=mt(),Cd=class extends IP.InkObject{toString(){return "Void"}};oo.Void=Cd;});var nn=S(lo=>{Object.defineProperty(lo,"__esModule",{value:true});lo.NativeFunctionCall=void 0;var V=Te(),vs=ds(),kP=yr(),uo=yt(),RP=mt(),It=fe(),vt=Qe(),te=class n extends RP.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, vt.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(n._nativeFunctions===null?(0, vt.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 kP.Void)throw new vs.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 V.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let r=this.CoerceValuesToSingleType(e),i=r[0].valueType;return i==V.ValueType.Int?this.CallType(r):i==V.ValueType.Float?this.CallType(r):i==V.ValueType.String?this.CallType(r):i==V.ValueType.DivertTarget?this.CallType(r):i==V.ValueType.List?this.CallType(r):null}CallType(e){let t=(0, It.asOrThrows)(e[0],V.Value),r=t.valueType,i=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(r);if(!s){let o=V.ValueType[r];throw new vs.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let u=(0, It.asOrThrows)(e[1],V.Value),l=s;if(i.value===null||u.value===null)return (0, vt.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=l(i.value,u.value);return V.Value.Create(c)}else {let o=s;if(i.value===null)return (0, vt.throwNullException)("NativeFunctionCall.Call UnaryOp value");let u=o(i.value);return this.name===n.Int?V.Value.Create(u,V.ValueType.Int):this.name===n.Float?V.Value.Create(u,V.ValueType.Float):V.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 V.ListValue&&e[1]instanceof V.IntValue)return this.CallListIncrementOperation(e);let t=(0, It.asOrThrows)(e[0],V.Value),r=(0, It.asOrThrows)(e[1],V.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=V.ValueType.List||r.valueType!=V.ValueType.List)){if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let i=this._operationFuncs.get(V.ValueType.Int);if(i===null)return (0, vt.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, It.asBooleanOrThrows)(i(t.isTruthy?1:0,r.isTruthy?1:0));return new V.BoolValue(a)}if(t.valueType==V.ValueType.List&&r.valueType==V.ValueType.List)return this.CallType([t,r]);throw new vs.StoryException("Can not call use "+this.name+" operation on "+V.ValueType[t.valueType]+" and "+V.ValueType[r.valueType])}CallListIncrementOperation(e){let t=(0, It.asOrThrows)(e[0],V.ListValue),r=(0, It.asOrThrows)(e[1],V.IntValue),i=new uo.InkList;if(t.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=uo.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, vt.throwNullException)("NativeFunctionCall._operationFuncs");let u=this._operationFuncs.get(V.ValueType.Int);if(r.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let l=u(s,r.value),c=null;if(t.value.origins===null)return (0, vt.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,uo.InkListItem.Null);h.exists&&i.Add(h.result,l);}}return new V.ListValue(i)}CoerceValuesToSingleType(e){let t=V.ValueType.Int,r=null;for(let a of e){let s=(0, It.asOrThrows)(a,V.Value);s.valueType>t&&(t=s.valueType),s.valueType==V.ValueType.List&&(r=(0, It.asOrNull)(s,V.ListValue));}let i=[];if(V.ValueType[t]==V.ValueType[V.ValueType.List])for(let a of e){let s=(0, It.asOrThrows)(a,V.Value);if(s.valueType==V.ValueType.List)i.push(s);else if(s.valueType==V.ValueType.Int){let o=parseInt(s.valueObject);if(r=(0, It.asOrThrows)(r,V.ListValue),r.value===null)return (0, vt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let u=r.value.originOfMaxItem;if(u===null)return (0, vt.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let l=u.TryGetItemWithValue(o,uo.InkListItem.Null);if(l.exists){let c=new V.ListValue(l.result,o);i.push(c);}else throw new vs.StoryException("Could not find List item with the value "+o+" in "+u.name)}else {let o=V.ValueType[s.valueType];throw new vs.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, It.asOrThrows)(a,V.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,V.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,V.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, vt.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,V.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,V.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,V.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};lo.NativeFunctionCall=te;te.Add="+";te.Subtract="-";te.Divide="/";te.Multiply="*";te.Mod="%";te.Negate="_";te.Equal="==";te.Greater=">";te.Less="<";te.GreaterThanOrEquals=">=";te.LessThanOrEquals="<=";te.NotEquals="!=";te.Not="!";te.And="&&";te.Or="||";te.Min="MIN";te.Max="MAX";te.Pow="POW";te.Floor="FLOOR";te.Ceiling="CEILING";te.Int="INT";te.Float="FLOAT";te.Has="?";te.Hasnt="!?";te.Intersect="^";te.ListMin="LIST_MIN";te.ListMax="LIST_MAX";te.All="LIST_ALL";te.Count="LIST_COUNT";te.ValueOfList="LIST_VALUE";te.Invert="LIST_INVERT";te._nativeFunctions=null;});var ho=S(co=>{Object.defineProperty(co,"__esModule",{value:true});co.NumberExpression=void 0;var $P=Ft(),bd=Te(),VP=fe(),_d=class n extends $P.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 bd.IntValue(this.value)):this.isFloat()?r.AddContent(new bd.FloatValue(this.value)):this.isBool()&&r.AddContent(new bd.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, VP.asOrNull)(e,n);return t?t.subtype==this.subtype&&t.value==this.value:false}};co.NumberExpression=_d;});var Sd=S(fo=>{Object.defineProperty(fo,"__esModule",{value:true});fo.UnaryExpression=void 0;var jP=Ft(),LP=nn(),oi=ho(),qP=fe(),Cs=class extends jP.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(LP.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};fo.UnaryExpression=Cs;Cs.WithInner=(n,e)=>{let t=(0, qP.asOrNull)(n,oi.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new oi.NumberExpression(-t.value,"int");if(t.isFloat())return new oi.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new oi.NumberExpression(t.value==0,"bool");if(t.isFloat())return new oi.NumberExpression(t.value==0,"bool");if(t.isBool())return new oi.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new Cs(n,e)};});var wd=S(po=>{Object.defineProperty(po,"__esModule",{value:true});po.BinaryExpression=void 0;var BP=Ft(),MP=nn(),WP=Sd(),GP=fe(),Ed=class extends BP.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(MP.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, GP.asOrNull)(this.leftExpression,WP.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.`);}}};po.BinaryExpression=Ed;});var _s=S(mo=>{Object.defineProperty(mo,"__esModule",{value:true});mo.CharacterSet=void 0;var bs=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);}};mo.CharacterSet=bs;bs.FromRange=(n,e)=>new bs().AddRange(n,e);});var qv=S(go=>{Object.defineProperty(go,"__esModule",{value:true});go.CharacterRange=void 0;var Lv=_s(),Ss=class{constructor(e,t,r=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Lv.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 Lv.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}};go.CharacterRange=Ss;Ss.Define=(n,e,t=[])=>new Ss(n,e,t);});var vo=S(yo=>{Object.defineProperty(yo,"__esModule",{value:true});yo.ChoicePoint=void 0;var HP=mt(),JP=pt(),Ad=Qe(),Dd=class extends HP.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, Ad.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, Ad.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new JP.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, Ad.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};yo.ChoicePoint=Dd;});var vr=S(Co=>{Object.defineProperty(Co,"__esModule",{value:true});Co.PushPopType=void 0;var Bv;(function(n){n[n.Tunnel=0]="Tunnel",n[n.Function=1]="Function",n[n.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(Bv||(Co.PushPopType=Bv={}));});var Es=S(bo=>{Object.defineProperty(bo,"__esModule",{value:true});bo.Pointer=void 0;var zP=pt(),xd=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 zP.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)}};bo.Pointer=xd;});var rn=S(So=>{Object.defineProperty(So,"__esModule",{value:true});So.Divert=void 0;var UP=pt(),KP=vr(),XP=mr(),YP=mt(),Pd=Es(),Mv=Re(),_o=Qe(),Od=class n extends YP.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=Pd.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, _o.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, _o.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, _o.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof Mv.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Pd.Pointer.StartOf(e instanceof Mv.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 UP.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Pd.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, _o.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 XP.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==KP.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};So.Divert=Od;});var Cn=S(Eo=>{Object.defineProperty(Eo,"__esModule",{value:true});Eo.SymbolType=void 0;var Wv;(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";})(Wv||(Eo.SymbolType=Wv={}));});var Ln=S(wo=>{Object.defineProperty(wo,"__esModule",{value:true});wo.VariableAssignment=void 0;var QP=mt(),Td=class extends QP.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};wo.VariableAssignment=Td;});var ui=S(Do=>{Object.defineProperty(Do,"__esModule",{value:true});Do.Choice=void 0;var ZP=vo(),Ao=Re(),qn=Ze(),Nd=rn(),Gv=Te(),eO=Pe(),tO=Cn(),Hv=Ln(),Fd=class extends eO.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 Ao.Container,this._runtimeChoice=new ZP.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(qn.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Gv.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let i=new Hv.VariableAssignment("$r",true);this._outerContainer.AddContent(i),this._outerContainer.AddContent(qn.ControlCommand.BeginString()),this._divertToStartContentOuter=new Nd.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new Nd.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ao.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(qn.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(qn.ControlCommand.BeginString());let i=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(i),this._outerContainer.AddContent(qn.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(qn.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ao.Container,this.startContent){this._returnToR2=new Gv.DivertTargetValue,this._innerContentContainer.AddContent(qn.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(qn.ControlCommand.EvalEnd());let i=new Hv.VariableAssignment("$r",true);this._innerContentContainer.AddContent(i),this._divertToStartContentInner=new Nd.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ao.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,tO.SymbolType.SubFlowAndWeave);}};Do.Choice=Fd;});var Jv=S(Po=>{Object.defineProperty(Po,"__esModule",{value:true});Po.StringParserElement=void 0;var xo=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;};}};Po.StringParserElement=xo;xo._uniqueIdCounter=1e3;});var Uv=S(Oo=>{Object.defineProperty(Oo,"__esModule",{value:true});Oo.StringParserState=void 0;var zv=Jv(),Id=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 zv.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 zv.StringParserElement;this._numElements=1;}};Oo.StringParserState=Id;});var Rd=S(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.StringParser=Cr.ParseSuccess=void 0;var kd=_s(),nO=Uv();Cr.ParseSuccess=Symbol("ParseSuccessStruct");var ws=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 Td.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 kd.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 ZP.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 Td.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)}};yr.StringParser=_s;_s.ParseSuccess=yr.ParseSuccess;_s.numbersCharacterSet=new Td.CharacterSet("0123456789");});var zv=w(Oo=>{Object.defineProperty(Oo,"__esModule",{value:true});Oo.CommentEliminator=void 0;var Fd=vs(),eO=Nd(),Id=class extends eO.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Fd.CharacterSet(`/\r
19
- `),this._commentBlockEndCharacter=new Fd.CharacterSet("*"),this._newlineCharacters=new Fd.CharacterSet(`
17
+ `)};let t=this.PreProcessInputString(e);this.state=new nO.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 kd.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)}};Cr.StringParser=ws;ws.ParseSuccess=Cr.ParseSuccess;ws.numbersCharacterSet=new kd.CharacterSet("0123456789");});var Kv=S(To=>{Object.defineProperty(To,"__esModule",{value:true});To.CommentEliminator=void 0;var $d=_s(),rO=Rd(),Vd=class extends rO.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new $d.CharacterSet(`/\r
19
+ `),this._commentBlockEndCharacter=new $d.CharacterSet("*"),this._newlineCharacters=new $d.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}};Oo.CommentEliminator=Id;});var No=w(To=>{Object.defineProperty(To,"__esModule",{value:true});To.Conditional=void 0;var tO=ke(),Uv=Qe(),nO=xe(),kd=class extends nO.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new tO.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(Uv.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Uv.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);}};To.Conditional=kd;});var qn=w(Fo=>{Object.defineProperty(Fo,"__esModule",{value:true});Fo.Text=void 0;var rO=xe(),iO=Oe(),Rd=class extends rO.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new iO.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Fo.Text=Rd;});var ko=w(Io=>{Object.defineProperty(Io,"__esModule",{value:true});Io.ConstantDeclaration=void 0;var sO=xe(),aO=bn(),$d=class extends sO.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,aO.SymbolType.Var);}};Io.ConstantDeclaration=$d;});var oi=w(Ro=>{Object.defineProperty(Ro,"__esModule",{value:true});Ro.FlowLevel=void 0;var Kv;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Kv||(Ro.FlowLevel=Kv={}));});var Ss=w($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.Gather=void 0;var oO=ke(),uO=xe(),lO=bn(),Vd=class extends uO.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 oO.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,lO.SymbolType.SubFlowAndWeave);}};$o.Gather=Vd;});var vr=w(jo=>{Object.defineProperty(jo,"__esModule",{value:true});jo.Path=void 0;var Vo=fe(),Xv=on(),ui=oi(),cO=Cr(),jd=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?ui.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(Vo.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===ui.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, Vo.asOrNull)(i,Xv.FlowBase);if(u!==null?o=u.flowLevel+1:o=ui.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, Vo.asOrNull)(r,cO.Weave);if(i&&u!==null&&(o||a===ui.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, Vo.asOrNull)(r,Xv.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===ui.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values(ui.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"}};jo.Path=jd;});var Bd=w(Lo=>{Object.defineProperty(Lo,"__esModule",{value:true});Lo.ReturnType=void 0;var hO=xe(),dO=ke(),Ld=Qe(),fO=mr(),qd=class extends hO.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new dO.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Ld.ControlCommand.EvalStart()),t.AddContent(new fO.Void),t.AddContent(Ld.ControlCommand.EvalEnd())),t.AddContent(Ld.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Lo.ReturnType=qd;});var Es=w(qo=>{Object.defineProperty(qo,"__esModule",{value:true});qo.ClosestFlowBase=void 0;function pO(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}qo.ClosestFlowBase=pO;});var Mo=w(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.Identifier=void 0;var Md=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")}};Bo.Identifier=Md;});var on=w(Wo=>{Object.defineProperty(Wo,"__esModule",{value:true});Wo.FlowBase=void 0;var mO=ai(),Wd=ci(),gO=li(),un=oi(),yO=Ss(),vO=xe(),CO=vr(),bO=Bd(),_O=ke(),SO=an(),EO=jn(),Gd=bn(),wO=Cr(),AO=Es(),DO=Mo(),Yv=fe(),Hd=class n extends vO.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 g of s){let f=(0, Yv.asOrNull)(g,n);f?(this._firstChildFlow===null&&(this._firstChildFlow=f),h.push(g),!((u=f.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=f.identifier)===null||l===void 0?void 0:l.name,f)):c.push(g);}o&&c.push(new yO.Gather(null,1),new Wd.Divert(new CO.Path(DO.Identifier.Done())));let d=[];return c.length>0&&(this._rootWeave=new wO.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, AO.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===un.FlowLevel.Knot||this.flowLevel===un.FlowLevel.Stitch)&&(o=this.Find(bO.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 _O.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===un.FlowLevel.Knot&&(this._startingSubFlowDivert=new SO.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=d);let g=d,f=u.namedContent.get(g.name)||null;if(f){let m=`${this.GetType()} already contains flow named '${g.name}' (at ${f.debugMetadata})`;this.Error(m,h);}u.AddToNamedContentOnly(g);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==un.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 EO.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===un.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===un.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,un.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!==un.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(Wd.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof gO.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(mO.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, Yv.asOrNull)(s,Wd.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,Gd.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!==un.FlowLevel.Story){let i=this.flowLevel===un.FlowLevel.Knot?Gd.SymbolType.Knot:Gd.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Wo.FlowBase=Hd;});var Ho=w(Go=>{Object.defineProperty(Go,"__esModule",{value:true});Go.ContentList=void 0;var xO=ke(),PO=xe(),OO=qn(),TO=fe(),Jd=class extends PO.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, TO.asOrNull)(this.content[r],OO.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 xO.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"}};Go.ContentList=Jd;});var hi=w(Jo=>{Object.defineProperty(Jo,"__esModule",{value:true});Jo.VariableReference=void 0;var NO=mt(),FO=pt(),zd=class extends NO.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 FO.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};Jo.VariableReference=zd;});var di=w(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.VariableReference=void 0;var IO=Ho(),kO=Ft(),Qv=on(),RO=vr(),$O=hi(),VO=Cr(),jO=Mo(),Zv=fe(),Ud=class extends kO.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Zv.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new jO.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 $O.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 RO.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, Zv.asOrNull)(r,Qv.FlowBase);i&&i.isFunction&&(this.parent instanceof VO.Weave||this.parent instanceof IO.ContentList||this.parent instanceof Qv.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);}};zo.VariableReference=Ud;});var ws=w(Yo=>{Object.defineProperty(Yo,"__esModule",{value:true});Yo.FunctionCall=void 0;var ln=Qe(),LO=ci(),qO=li(),BO=Ft(),MO=yt(),WO=Oe(),Ko=sn(),e0=co(),GO=vr(),HO=Oe(),JO=di(),Uo=fe(),Xo=class n extends BO.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(ln.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(ln.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Uo.asOrNull)(this.args[0],qO.DivertTarget),o=(0, Uo.asOrNull)(this.args[0],JO.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(ln.ControlCommand.TurnsSince()):r.AddContent(ln.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, Uo.asOrNull)(this.args[s],e0.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(ln.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Uo.asOrNull)(this.args[0],e0.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(ln.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(ln.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(ln.ControlCommand.ListRandom());else if(Ko.NativeFunctionCall.CallExistsWithName(this.name)){let s=Ko.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(Ko.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 HO.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(ln.ControlCommand.ListFromInt());else {let s=new MO.InkList;s.SetInitialOriginName(this.name),r.AddContent(new WO.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(ln.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new LO.Divert(new GO.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.`);}}};Yo.FunctionCall=Xo;Xo.IsBuiltIn=n=>Ko.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 Xd=w(Qo=>{Object.defineProperty(Qo,"__esModule",{value:true});Qo.MultipleConditionExpression=void 0;var zO=Ft(),UO=sn(),Kd=class extends zO.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(UO.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Qo.MultipleConditionExpression=Kd;});var li=w(Zo=>{Object.defineProperty(Zo,"__esModule",{value:true});Zo.DivertTarget=void 0;var KO=bd(),XO=ai(),YO=No(),QO=ef(),ZO=Oe(),Yd=Ft(),eT=on(),t0=ws(),tT=Xd(),n0=di(),Qd=fe(),Zd=class n extends Yd.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 ZO.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, Qd.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 Yd.Expression;){let i=false,a=false,s=t.parent;if(s instanceof KO.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof n0.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof n0.VariableReference)||(i=true),a=true;}else if(s instanceof t0.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof Yd.Expression||s instanceof tT.MultipleConditionExpression||s instanceof XO.Choice&&s.condition===t||s instanceof YO.Conditional||s instanceof QO.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, Qd.asOrNull)(this.parent,t0.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, Qd.asOrNull)(r,eT.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}').`);}}};Zo.DivertTarget=Zd;});var ci=w(eu=>{Object.defineProperty(eu,"__esModule",{value:true});eu.Divert=void 0;var nT=ke(),As=Qe(),rT=an(),tf=li(),nf=on(),iT=ws(),sT=xe(),r0=vr(),aT=pt(),i0=gr(),oT=Oe(),s0=di(),uT=Es(),Ds=fe(),rf=class extends sT.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 As.ControlCommand.End();if(this.isDone)return As.ControlCommand.Done();this.runtimeDivert=new rT.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 nT.Container;if(r){this.isFunctionCall||i.AddContent(As.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, Ds.asOrNull)(o,s0.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new r0.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 oT.VariablePointerValue(l.name);i.AddContent(d);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(As.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(As.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?i0.PushPopType.Function:i0.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, Ds.asOrNull)((0, uT.ClosestFlowBase)(this),nf.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, Ds.asOrNull)(this.targetContent,nf.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 tf.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, Ds.asOrNull)(u,s0.VariableReference);if(!(u instanceof tf.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 r0.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, Ds.asOrNull)(this.targetContent,nf.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 tf.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=iT.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 aT.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);}};eu.Divert=rf;});var a0=w(tu=>{Object.defineProperty(tu,"__esModule",{value:true});tu.GatherPointToResolve=void 0;var sf=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};tu.GatherPointToResolve=sf;});var o0=w(nu=>{Object.defineProperty(nu,"__esModule",{value:true});nu.SequenceDivertToResolve=void 0;var af=class{constructor(e,t){this.divert=e,this.targetContent=t;}};nu.SequenceDivertToResolve=af;});var of=w(ru=>{Object.defineProperty(ru,"__esModule",{value:true});ru.SequenceType=void 0;var u0;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(u0||(ru.SequenceType=u0={}));});var cf=w(au=>{Object.defineProperty(au,"__esModule",{value:true});au.Sequence=void 0;var l0=ke(),Wt=Qe(),uf=an(),xs=Oe(),iu=sn(),lT=xe(),cT=o0(),su=of(),hT=Cr(),lf=class extends lT.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new l0.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(Wt.ControlCommand.EvalStart()),r.AddContent(Wt.ControlCommand.VisitIndex());let i=(this.sequenceType&su.SequenceType.Once)>0,a=(this.sequenceType&su.SequenceType.Cycle)>0,s=(this.sequenceType&su.SequenceType.Stopping)>0,o=(this.sequenceType&su.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new xs.IntValue(u-1)),r.AddContent(iu.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new xs.IntValue(this.sequenceElements.length)),r.AddContent(iu.NativeFunctionCall.CallWithName("%"))),o){let c=Wt.ControlCommand.NoOp();if(i||s){let d=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(Wt.ControlCommand.Duplicate()),r.AddContent(new xs.IntValue(d)),r.AddContent(iu.NativeFunctionCall.CallWithName("=="));let g=new uf.Divert;g.isConditional=true,r.AddContent(g),this.AddDivertToResolve(g,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new xs.IntValue(h)),r.AddContent(Wt.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(Wt.ControlCommand.EvalEnd());let l=Wt.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(Wt.ControlCommand.EvalStart()),r.AddContent(Wt.ControlCommand.Duplicate()),r.AddContent(new xs.IntValue(c)),r.AddContent(iu.NativeFunctionCall.CallWithName("==")),r.AddContent(Wt.ControlCommand.EvalEnd());let h=new uf.Divert;h.isConditional=true,r.AddContent(h);let d;c<this.sequenceElements.length?d=this.sequenceElements[c].runtimeObject:d=new l0.Container,d.name=`s${c}`,d.InsertContent(Wt.ControlCommand.PopEvaluatedValue(),0);let g=new uf.Divert;d.AddContent(g),r.AddToNamedContentOnly(d),this.AddDivertToResolve(h,d),this.AddDivertToResolve(g,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new cT.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 hT.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;}};au.Sequence=lf;});var df=w(ou=>{Object.defineProperty(ou,"__esModule",{value:true});ou.TunnelOnwards=void 0;var dT=ke(),Ps=Qe(),fT=an(),pT=Oe(),mT=xe(),gT=mr(),yT=fe(),vT=hi(),hf=class extends mT.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new dT.Container;if(e.AddContent(Ps.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===Ps.ControlCommand.CommandType.EvalStart?s=u:l.commandType===Ps.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, yT.asOrNull)(t,fT.Divert);if(i!=null&&i.hasVariableTarget){let a=new vT.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new pT.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new gT.Void);return e.AddContent(Ps.ControlCommand.EvalEnd()),e.AddContent(Ps.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);}};ou.TunnelOnwards=hf;});var mf=w(uu=>{Object.defineProperty(uu,"__esModule",{value:true});uu.ListDefinition=void 0;var ff=yt(),pf=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 ff.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 ff.InkListItem(this.name,r),{result:t,exists:true};return t=ff.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}}};uu.ListDefinition=pf;});var cu=w(lu=>{Object.defineProperty(lu,"__esModule",{value:true});lu.ListDefinition=void 0;var CT=yt(),bT=yt(),_T=mf(),ST=Oe(),ET=xe(),wT=bn(),gf=class extends ET.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 _T.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 CT.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new bT.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 ST.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,wT.SymbolType.List);}};lu.ListDefinition=gf;});var vf=w(hu=>{Object.defineProperty(hu,"__esModule",{value:true});hu.VariableAssignment=void 0;var AT=ke(),DT=Es(),xT=cu(),PT=xe(),c0=bn(),OT=jn(),TT=di(),NT=fe(),yf=class extends PT.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, DT.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new AT.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new OT.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 xT.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?c0.SymbolType.Var:c0.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, NT.asOrNull)(this.expression,TT.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);}}};hu.VariableAssignment=yf;});var Cr=w(pu=>{Object.defineProperty(pu,"__esModule",{value:true});pu.Weave=void 0;var h0=Ua(),kt=ai(),du=No(),FT=ko(),IT=ke(),fu=ci(),kT=an(),RT=li(),$T=on(),cn=Ss(),VT=a0(),jT=xe(),Cf=cf(),LT=qn(),qT=df(),BT=vf(),Rt=fe(),bf=class n extends jT.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,LT.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(cn.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(kt.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 cn.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 kt.Choice||i instanceof cn.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],kt.Choice)||(0, Rt.asOrNull)(this.content[r],cn.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 kt.Choice||i instanceof cn.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new IT.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof kt.Choice||r instanceof cn.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 cn.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof fu.Divert)u=o.runtimeObject;else {u=new kT.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new VT.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof cn.Gather)this.AddRuntimeForGather(r);else if(r instanceof kt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof cn.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,kt.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 Cf.Sequence||s instanceof du.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 kt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof kt.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,BT.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, Rt.asOrNull)(r,FT.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 kt.Choice||l instanceof cn.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof h0.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 kt.Choice||a instanceof fu.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 Cf.Sequence||s instanceof du.Conditional){i=(0, Rt.asOrNull)(s,du.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(kt.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(fu.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof RT.DivertTarget))!==null&&(s=true),u.Find(qT.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof h0.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],fu.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,$T.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 Cf.Sequence||r instanceof du.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};pu.Weave=bf;});var ef=w(gu=>{Object.defineProperty(gu,"__esModule",{value:true});gu.ConditionalSingleBranch=void 0;var d0=ke(),mu=Qe(),f0=an(),MT=xe(),WT=sn(),GT=Oe(),HT=qn(),JT=Cr(),zT=fe(),_f=class extends MT.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, zT.asOrNull)(i,HT.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 d0.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(mu.ControlCommand.Duplicate()),this._conditionalDivert=new f0.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(mu.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(WT.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(mu.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new GT.StringValue(`
23
- `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(mu.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new f0.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new d0.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new JT.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);}};gu.ConditionalSingleBranch=_f;});var m0=w(yu=>{Object.defineProperty(yu,"__esModule",{value:true});yu.CustomFlags=void 0;var p0;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(p0||(yu.CustomFlags=p0={}));});var g0=w(vu=>{Object.defineProperty(vu,"__esModule",{value:true});vu.DebugMetadata=void 0;var Sf=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}};vu.DebugMetadata=Sf;});var y0=w(Cu=>{Object.defineProperty(Cu,"__esModule",{value:true});Cu.ExternalDeclaration=void 0;var UT=xe(),Ef=class extends UT.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}`}};Cu.ExternalDeclaration=Ef;});var v0=w(bu=>{Object.defineProperty(bu,"__esModule",{value:true});bu.FlowDecl=void 0;var wf=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};bu.FlowDecl=wf;});var Df=w(_u=>{Object.defineProperty(_u,"__esModule",{value:true});_u.Wrap=void 0;var KT=xe(),Af=class extends KT.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};_u.Wrap=Af;});var C0=w(Su=>{Object.defineProperty(Su,"__esModule",{value:true});Su.Glue=void 0;var XT=Df(),xf=class extends XT.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Su.Glue=xf;});var wu=w(Eu=>{Object.defineProperty(Eu,"__esModule",{value:true});Eu.Glue=void 0;var YT=mt(),Pf=class extends YT.InkObject{toString(){return "Glue"}};Eu.Glue=Pf;});var _0=w(Au=>{Object.defineProperty(Au,"__esModule",{value:true});Au.IncDecExpression=void 0;var QT=Ho(),b0=Ft(),ZT=on(),e1=sn(),t1=Oe(),n1=jn(),r1=hi(),i1=Cr(),Of=class extends b0.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new r1.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new t1.IntValue(1)),i.AddContent(e1.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new n1.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 b0.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 i1.Weave)&&!(this.parent instanceof ZT.FlowBase)&&!(this.parent instanceof QT.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Au.IncDecExpression=Of;});var Nf=w(Du=>{Object.defineProperty(Du,"__esModule",{value:true});Du.IncludedFile=void 0;var s1=xe(),Tf=class extends s1.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Du.IncludedFile=Tf;});var S0=w(xu=>{Object.defineProperty(xu,"__esModule",{value:true});xu.InfixOperator=void 0;var Ff=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};xu.InfixOperator=Ff;});var kf=w(Pu=>{Object.defineProperty(Pu,"__esModule",{value:true});Pu.Knot=void 0;var a1=on(),E0=oi(),If=class extends a1.FlowBase{get flowLevel(){return E0.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,E0.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);}}}};Pu.Knot=If;});var w0=w(Ou=>{Object.defineProperty(Ou,"__esModule",{value:true});Ou.List=void 0;var o1=Ft(),u1=yt(),l1=yt(),c1=Oe(),Rf=class extends o1.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new u1.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 l1.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 c1.ListValue(a));};}get typeName(){return "List"}};Ou.List=Rf;});var Vf=w(Tu=>{Object.defineProperty(Tu,"__esModule",{value:true});Tu.ListElementDefinition=void 0;var h1=xe(),d1=bn(),$f=class extends h1.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,d1.SymbolType.ListItem);}};Tu.ListElementDefinition=$f;});var jf=w(Nu=>{Object.defineProperty(Nu,"__esModule",{value:true});Nu.StatementLevel=void 0;var A0;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(A0||(Nu.StatementLevel=A0={}));});var qf=w(Fu=>{Object.defineProperty(Fu,"__esModule",{value:true});Fu.Stitch=void 0;var f1=on(),p1=oi(),Lf=class extends f1.FlowBase{get flowLevel(){return p1.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"}};Fu.Stitch=Lf;});var ku=w(Iu=>{Object.defineProperty(Iu,"__esModule",{value:true});Iu.Tag=void 0;var m1=mt(),Bf=class extends m1.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Iu.Tag=Bf;});var Wf=w(Ru=>{Object.defineProperty(Ru,"__esModule",{value:true});Ru.Choice=void 0;var g1=pt(),y1=Ye(),v1=mt(),Mf=class n extends v1.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, y1.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new g1.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}};Ru.Choice=Mf;});var Hf=w($u=>{Object.defineProperty($u,"__esModule",{value:true});$u.ListDefinitionsOrigin=void 0;var C1=yt(),b1=Oe(),_1=Ye(),Gf=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=C1.InkListItem.fromSerializedKey(r),s=new b1.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, _1.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};$u.ListDefinitionsOrigin=Gf;});var pi=w(qu=>{Object.defineProperty(qu,"__esModule",{value:true});qu.JsonSerialisation=void 0;var Vu=ke(),Ct=Oe(),D0=wu(),oe=Qe(),fi=gr(),x0=an(),P0=yo(),Jf=hi(),O0=jn(),zf=sn(),T0=mr(),N0=ku(),S1=pt(),F0=Wf(),E1=mf(),w1=Hf(),ju=yt(),Re=fe(),br=Ye(),Lu=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, br.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, Re.asOrNull)(t,Vu.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, Re.asOrNull)(t,x0.Divert);if(i){let C="->";i.isExternal?C="x()":i.pushesToStack&&(i.stackPushType==fi.PushPopType.Function?C="f()":i.stackPushType==fi.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, Re.asOrNull)(t,P0.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, Re.asOrNull)(t,Ct.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, Re.asOrNull)(t,Ct.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, Re.asOrNull)(t,Ct.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, Re.asOrNull)(t,Ct.StringValue);if(l){l.isNewline?e.Write(`
24
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, Re.asOrNull)(t,Ct.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, Re.asOrNull)(t,Ct.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, br.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let d=(0, Re.asOrNull)(t,Ct.VariablePointerValue);if(d){e.WriteObjectStart(),e.WriteProperty("^var",d.value),e.WriteIntProperty("ci",d.contextIndex),e.WriteObjectEnd();return}if((0, Re.asOrNull)(t,D0.Glue)){e.Write("<>");return}let f=(0, Re.asOrNull)(t,oe.ControlCommand);if(f){e.Write(n._controlCommandNames[f.commandType]);return}let m=(0, Re.asOrNull)(t,zf.NativeFunctionCall);if(m){let C=m.name;C=="^"&&(C="L^"),e.Write(C);return}let b=(0, Re.asOrNull)(t,Jf.VariableReference);if(b){e.WriteObjectStart();let C=b.pathStringForCount;C!=null?e.WriteProperty("CNT?",C):e.WriteProperty("VAR?",b.name),e.WriteObjectEnd();return}let _=(0, Re.asOrNull)(t,O0.VariableAssignment);if(_){e.WriteObjectStart();let C=_.isGlobal?"VAR=":"temp=";e.WriteProperty(C,_.variableName),_.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, Re.asOrNull)(t,T0.Void)){e.Write("void");return}let p=(0, Re.asOrNull)(t,N0.Tag);if(p){e.WriteObjectStart(),e.WriteProperty("#",p.text),e.WriteObjectEnd();return}let v=(0, Re.asOrNull)(t,F0.Choice);if(v){this.WriteChoice(e,v);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, br.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 Ct.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new Ct.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new Ct.StringValue(t.substring(1));if(i==`
21
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};To.CommentEliminator=Vd;});var Fo=S(No=>{Object.defineProperty(No,"__esModule",{value:true});No.Conditional=void 0;var iO=Re(),Xv=Ze(),sO=Pe(),jd=class extends sO.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let r=new iO.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(Xv.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Xv.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);}};No.Conditional=jd;});var Bn=S(Io=>{Object.defineProperty(Io,"__esModule",{value:true});Io.Text=void 0;var aO=Pe(),oO=Te(),Ld=class extends aO.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new oO.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};Io.Text=Ld;});var Ro=S(ko=>{Object.defineProperty(ko,"__esModule",{value:true});ko.ConstantDeclaration=void 0;var uO=Pe(),lO=Cn(),qd=class extends uO.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,lO.SymbolType.Var);}};ko.ConstantDeclaration=qd;});var li=S($o=>{Object.defineProperty($o,"__esModule",{value:true});$o.FlowLevel=void 0;var Yv;(function(n){n[n.Story=0]="Story",n[n.Knot=1]="Knot",n[n.Stitch=2]="Stitch",n[n.WeavePoint=3]="WeavePoint";})(Yv||($o.FlowLevel=Yv={}));});var As=S(Vo=>{Object.defineProperty(Vo,"__esModule",{value:true});Vo.Gather=void 0;var cO=Re(),hO=Pe(),dO=Cn(),Bd=class extends hO.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 cO.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,dO.SymbolType.SubFlowAndWeave);}};Vo.Gather=Bd;});var br=S(Lo=>{Object.defineProperty(Lo,"__esModule",{value:true});Lo.Path=void 0;var jo=fe(),Qv=sn(),ci=li(),fO=_r(),Md=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?ci.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(jo.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===ci.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, jo.asOrNull)(i,Qv.FlowBase);if(u!==null?o=u.flowLevel+1:o=ci.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, jo.asOrNull)(r,fO.Weave);if(i&&u!==null&&(o||a===ci.FlowLevel.WeavePoint))return u.WeavePointNamed(i);let l=(0, jo.asOrNull)(r,Qv.FlowBase);if(i&&l!==null){let c=s||l.flowLevel===ci.FlowLevel.Knot;return l.ContentWithNameAtLevel(i,a,c)}return null},Object.values(ci.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"}};Lo.Path=Md;});var Hd=S(qo=>{Object.defineProperty(qo,"__esModule",{value:true});qo.ReturnType=void 0;var pO=Pe(),mO=Re(),Wd=Ze(),gO=yr(),Gd=class extends pO.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new mO.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Wd.ControlCommand.EvalStart()),t.AddContent(new gO.Void),t.AddContent(Wd.ControlCommand.EvalEnd())),t.AddContent(Wd.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};qo.ReturnType=Gd;});var Ds=S(Bo=>{Object.defineProperty(Bo,"__esModule",{value:true});Bo.ClosestFlowBase=void 0;function yO(n){let e=n.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Bo.ClosestFlowBase=yO;});var Wo=S(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.Identifier=void 0;var Jd=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")}};Mo.Identifier=Jd;});var sn=S(Go=>{Object.defineProperty(Go,"__esModule",{value:true});Go.FlowBase=void 0;var vO=ui(),zd=di(),CO=hi(),an=li(),bO=As(),_O=Pe(),SO=br(),EO=Hd(),wO=Re(),AO=rn(),DO=Ln(),Ud=Cn(),xO=_r(),PO=Ds(),OO=Wo(),Zv=fe(),Kd=class n extends _O.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 g of s){let p=(0, Zv.asOrNull)(g,n);p?(this._firstChildFlow===null&&(this._firstChildFlow=p),h.push(g),!((u=p.identifier)===null||u===void 0)&&u.name&&this._subFlowsByName.set((l=p.identifier)===null||l===void 0?void 0:l.name,p)):c.push(g);}o&&c.push(new bO.Gather(null,1),new zd.Divert(new SO.Path(OO.Identifier.Done())));let f=[];return c.length>0&&(this._rootWeave=new xO.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, PO.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===an.FlowLevel.Knot||this.flowLevel===an.FlowLevel.Stitch)&&(o=this.Find(EO.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 wO.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===an.FlowLevel.Knot&&(this._startingSubFlowDivert=new AO.Divert,u.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let g=f,p=u.namedContent.get(g.name)||null;if(p){let m=`${this.GetType()} already contains flow named '${g.name}' (at ${p.debugMetadata})`;this.Error(m,h);}u.AddToNamedContentOnly(g);}else c&&u.AddContent(c.runtimeObject);l+=1;}return this.flowLevel!==an.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 DO.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===an.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===an.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,an.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!==an.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(zd.Divert)();for(let u of s)!u.isFunctionCall&&!(u.parent instanceof CO.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${u}'`,u);let o=this._rootWeave.FindAll(vO.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, Zv.asOrNull)(s,zd.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,Ud.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!==an.FlowLevel.Story){let i=this.flowLevel===an.FlowLevel.Knot?Ud.SymbolType.Knot:Ud.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,i);}}};Go.FlowBase=Kd;});var Jo=S(Ho=>{Object.defineProperty(Ho,"__esModule",{value:true});Ho.ContentList=void 0;var TO=Re(),NO=Pe(),FO=Bn(),IO=fe(),Xd=class extends NO.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, IO.asOrNull)(this.content[r],FO.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 TO.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"}};Ho.ContentList=Xd;});var fi=S(zo=>{Object.defineProperty(zo,"__esModule",{value:true});zo.VariableReference=void 0;var kO=mt(),RO=pt(),Yd=class extends kO.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 RO.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};zo.VariableReference=Yd;});var pi=S(Uo=>{Object.defineProperty(Uo,"__esModule",{value:true});Uo.VariableReference=void 0;var $O=Jo(),VO=Ft(),e0=sn(),jO=br(),LO=fi(),qO=_r(),BO=Wo(),t0=fe(),Qd=class extends VO.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(t0.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new BO.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 LO.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 jO.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, t0.asOrNull)(r,e0.FlowBase);i&&i.isFunction&&(this.parent instanceof qO.Weave||this.parent instanceof $O.ContentList||this.parent instanceof e0.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);}};Uo.VariableReference=Qd;});var xs=S(Qo=>{Object.defineProperty(Qo,"__esModule",{value:true});Qo.FunctionCall=void 0;var on=Ze(),MO=di(),WO=hi(),GO=Ft(),HO=yt(),JO=Te(),Xo=nn(),n0=ho(),zO=br(),UO=Te(),KO=pi(),Ko=fe(),Yo=class n extends GO.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(on.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),r.AddContent(on.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, Ko.asOrNull)(this.args[0],WO.DivertTarget),o=(0, Ko.asOrNull)(this.args[0],KO.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(on.ControlCommand.TurnsSince()):r.AddContent(on.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, Ko.asOrNull)(this.args[s],n0.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(on.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, Ko.asOrNull)(this.args[0],n0.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(r),r.AddContent(on.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(on.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(on.ControlCommand.ListRandom());else if(Xo.NativeFunctionCall.CallExistsWithName(this.name)){let s=Xo.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(Xo.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 UO.StringValue(this.name)),this.args[0].GenerateIntoContainer(r),r.AddContent(on.ControlCommand.ListFromInt());else {let s=new HO.InkList;s.SetInitialOriginName(this.name),r.AddContent(new JO.ListValue(s));}else r.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&r.AddContent(on.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let r=this.args.join(", ");return `${this.name}(${r})`},this._proxyDivert=new MO.Divert(new zO.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.`);}}};Qo.FunctionCall=Yo;Yo.IsBuiltIn=n=>Xo.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 ef=S(Zo=>{Object.defineProperty(Zo,"__esModule",{value:true});Zo.MultipleConditionExpression=void 0;var XO=Ft(),YO=nn(),Zd=class extends XO.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(YO.NativeFunctionCall.CallWithName("&&")),r=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};Zo.MultipleConditionExpression=Zd;});var hi=S(eu=>{Object.defineProperty(eu,"__esModule",{value:true});eu.DivertTarget=void 0;var QO=wd(),ZO=ui(),eT=Fo(),tT=sf(),nT=Te(),tf=Ft(),rT=sn(),r0=xs(),iT=ef(),i0=pi(),nf=fe(),rf=class n extends tf.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 nT.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let r=(0, nf.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 tf.Expression;){let i=false,a=false,s=t.parent;if(s instanceof QO.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?i=true:(o.leftExpression instanceof n||o.leftExpression instanceof i0.VariableReference)&&(o.rightExpression instanceof n||o.rightExpression instanceof i0.VariableReference)||(i=true),a=true;}else if(s instanceof r0.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(i=true),a=true;}else (s instanceof tf.Expression||s instanceof iT.MultipleConditionExpression||s instanceof ZO.Choice&&s.condition===t||s instanceof eT.Conditional||s instanceof tT.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, nf.asOrNull)(this.parent,r0.FunctionCall);s&&s.isTurnsSince||(i.visitsShouldBeCounted=true),i.turnIndexShouldBeCounted=true;}let a=(0, nf.asOrNull)(r,rT.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}').`);}}};eu.DivertTarget=rf;});var di=S(tu=>{Object.defineProperty(tu,"__esModule",{value:true});tu.Divert=void 0;var sT=Re(),Ps=Ze(),aT=rn(),af=hi(),of=sn(),oT=xs(),uT=Pe(),s0=br(),lT=pt(),a0=vr(),cT=Te(),o0=pi(),hT=Ds(),Os=fe(),uf=class extends uT.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 Ps.ControlCommand.End();if(this.isDone)return Ps.ControlCommand.Done();this.runtimeDivert=new aT.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 sT.Container;if(r){this.isFunctionCall||i.AddContent(Ps.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, Os.asOrNull)(o,o0.VariableReference);if(!l){this.Error(`Expected variable name to pass by reference to 'ref ${u.identifier}' but saw ${o}`);break}let c=new s0.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 cT.VariablePointerValue(l.name);i.AddContent(f);}else o.GenerateIntoContainer(i);}this.isFunctionCall||i.AddContent(Ps.ControlCommand.EvalEnd());}return this.isThread?i.AddContent(Ps.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?a0.PushPopType.Function:a0.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, Os.asOrNull)((0, hT.ClosestFlowBase)(this),of.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, Os.asOrNull)(this.targetContent,of.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 af.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, Os.asOrNull)(u,o0.VariableReference);if(!(u instanceof af.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 s0.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, Os.asOrNull)(this.targetContent,of.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 af.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=oT.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 lT.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);}};tu.Divert=uf;});var u0=S(nu=>{Object.defineProperty(nu,"__esModule",{value:true});nu.GatherPointToResolve=void 0;var lf=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};nu.GatherPointToResolve=lf;});var l0=S(ru=>{Object.defineProperty(ru,"__esModule",{value:true});ru.SequenceDivertToResolve=void 0;var cf=class{constructor(e,t){this.divert=e,this.targetContent=t;}};ru.SequenceDivertToResolve=cf;});var hf=S(iu=>{Object.defineProperty(iu,"__esModule",{value:true});iu.SequenceType=void 0;var c0;(function(n){n[n.Stopping=1]="Stopping",n[n.Cycle=2]="Cycle",n[n.Shuffle=4]="Shuffle",n[n.Once=8]="Once";})(c0||(iu.SequenceType=c0={}));});var pf=S(ou=>{Object.defineProperty(ou,"__esModule",{value:true});ou.Sequence=void 0;var h0=Re(),Wt=Ze(),df=rn(),Ts=Te(),su=nn(),dT=Pe(),fT=l0(),au=hf(),pT=_r(),ff=class extends dT.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let r=new h0.Container;r.visitsShouldBeCounted=true,r.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],r.AddContent(Wt.ControlCommand.EvalStart()),r.AddContent(Wt.ControlCommand.VisitIndex());let i=(this.sequenceType&au.SequenceType.Once)>0,a=(this.sequenceType&au.SequenceType.Cycle)>0,s=(this.sequenceType&au.SequenceType.Stopping)>0,o=(this.sequenceType&au.SequenceType.Shuffle)>0,u=this.sequenceElements.length;if(i&&(u+=1),s||i?(r.AddContent(new Ts.IntValue(u-1)),r.AddContent(su.NativeFunctionCall.CallWithName("MIN"))):a&&(r.AddContent(new Ts.IntValue(this.sequenceElements.length)),r.AddContent(su.NativeFunctionCall.CallWithName("%"))),o){let c=Wt.ControlCommand.NoOp();if(i||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;r.AddContent(Wt.ControlCommand.Duplicate()),r.AddContent(new Ts.IntValue(f)),r.AddContent(su.NativeFunctionCall.CallWithName("=="));let g=new df.Divert;g.isConditional=true,r.AddContent(g),this.AddDivertToResolve(g,c);}let h=this.sequenceElements.length;s&&(h-=1),r.AddContent(new Ts.IntValue(h)),r.AddContent(Wt.ControlCommand.SequenceShuffleIndex()),(i||s)&&r.AddContent(c);}r.AddContent(Wt.ControlCommand.EvalEnd());let l=Wt.ControlCommand.NoOp();for(let c=0;c<u;c+=1){r.AddContent(Wt.ControlCommand.EvalStart()),r.AddContent(Wt.ControlCommand.Duplicate()),r.AddContent(new Ts.IntValue(c)),r.AddContent(su.NativeFunctionCall.CallWithName("==")),r.AddContent(Wt.ControlCommand.EvalEnd());let h=new df.Divert;h.isConditional=true,r.AddContent(h);let f;c<this.sequenceElements.length?f=this.sequenceElements[c].runtimeObject:f=new h0.Container,f.name=`s${c}`,f.InsertContent(Wt.ControlCommand.PopEvaluatedValue(),0);let g=new df.Divert;f.AddContent(g),r.AddToNamedContentOnly(f),this.AddDivertToResolve(h,f),this.AddDivertToResolve(g,l);}return r.AddContent(l),r},this.AddDivertToResolve=(r,i)=>{this._sequenceDivertsToResolve.push(new fT.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 pT.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;}};ou.Sequence=ff;});var gf=S(uu=>{Object.defineProperty(uu,"__esModule",{value:true});uu.TunnelOnwards=void 0;var mT=Re(),Ns=Ze(),gT=rn(),yT=Te(),vT=Pe(),CT=yr(),bT=fe(),_T=fi(),mf=class extends vT.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new mT.Container;if(e.AddContent(Ns.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===Ns.ControlCommand.CommandType.EvalStart?s=u:l.commandType===Ns.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, bT.asOrNull)(t,gT.Divert);if(i!=null&&i.hasVariableTarget){let a=new _T.VariableReference(i.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new yT.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new CT.Void);return e.AddContent(Ns.ControlCommand.EvalEnd()),e.AddContent(Ns.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);}};uu.TunnelOnwards=mf;});var Cf=S(lu=>{Object.defineProperty(lu,"__esModule",{value:true});lu.ListDefinition=void 0;var yf=yt(),vf=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 yf.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 yf.InkListItem(this.name,r),{result:t,exists:true};return t=yf.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}}};lu.ListDefinition=vf;});var hu=S(cu=>{Object.defineProperty(cu,"__esModule",{value:true});cu.ListDefinition=void 0;var ST=yt(),ET=yt(),wT=Cf(),AT=Te(),DT=Pe(),xT=Cn(),bf=class extends DT.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 wT.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 ST.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new ET.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 AT.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,xT.SymbolType.List);}};cu.ListDefinition=bf;});var Sf=S(du=>{Object.defineProperty(du,"__esModule",{value:true});du.VariableAssignment=void 0;var PT=Re(),OT=Ds(),TT=hu(),NT=Pe(),d0=Cn(),FT=Ln(),IT=pi(),kT=fe(),_f=class extends NT.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, OT.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new PT.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new FT.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 TT.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?d0.SymbolType.Var:d0.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, kT.asOrNull)(this.expression,IT.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);}}};du.VariableAssignment=_f;});var _r=S(mu=>{Object.defineProperty(mu,"__esModule",{value:true});mu.Weave=void 0;var f0=Ka(),kt=ui(),fu=Fo(),RT=Ro(),$T=Re(),pu=di(),VT=rn(),jT=hi(),LT=sn(),un=As(),qT=u0(),BT=Pe(),Ef=pf(),MT=Bn(),WT=gf(),GT=Sf(),Rt=fe(),wf=class n extends BT.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,MT.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(un.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(kt.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 un.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 kt.Choice||i instanceof un.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],kt.Choice)||(0, Rt.asOrNull)(this.content[r],un.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 kt.Choice||i instanceof un.Gather)return i.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new $T.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let r of this.content)if(r instanceof kt.Choice||r instanceof un.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 un.Gather&&o.indentationDepth==r.indentationDepth)continue;let u=null;if(o instanceof pu.Divert)u=o.runtimeObject;else {u=new VT.Divert;let l=o;if(!l.runtimeContainer)throw new Error;l.runtimeContainer.AddContent(u);}this.gatherPointsToResolve.push(new qT.GatherPointToResolve(u,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=r=>{if(r instanceof un.Gather)this.AddRuntimeForGather(r);else if(r instanceof kt.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof un.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,kt.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 Ef.Sequence||s instanceof fu.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 kt.Choice&&r!==null)r.ReceiveLooseEnd(o),u=true;else if(!(o instanceof kt.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,GT.VariableAssignment);return !!(i&&i.isGlobalDeclaration&&i.isDeclaration||(0, Rt.asOrNull)(r,RT.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 kt.Choice||l instanceof un.Gather||l instanceof n)break;i.push(l);}}return i},this.ValidateTermination=r=>{if(this.lastParsedSignificantObject instanceof f0.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 kt.Choice||a instanceof pu.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 Ef.Sequence||s instanceof fu.Conditional){i=(0, Rt.asOrNull)(s,fu.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";i!==null&&i.FindAll(kt.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(pu.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof jT.DivertTarget))!==null&&(s=true),u.Find(WT.TunnelOnwards)()!=null){s=true;break}o=u;}if(!s){if(o instanceof f0.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],pu.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,LT.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 Ef.Sequence||r instanceof fu.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};mu.Weave=wf;});var sf=S(yu=>{Object.defineProperty(yu,"__esModule",{value:true});yu.ConditionalSingleBranch=void 0;var p0=Re(),gu=Ze(),m0=rn(),HT=Pe(),JT=nn(),zT=Te(),UT=Bn(),KT=_r(),XT=fe(),Af=class extends HT.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, XT.asOrNull)(i,UT.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 p0.Container,r=this.matchingEquality&&!this.isElse;if(r&&t.AddContent(gu.ControlCommand.Duplicate()),this._conditionalDivert=new m0.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let i=this.ownExpression!==null;i&&t.AddContent(gu.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(JT.NativeFunctionCall.CallWithName("==")),i&&t.AddContent(gu.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new zT.StringValue(`
23
+ `),0),(r||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(gu.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new m0.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new p0.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new KT.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);}};yu.ConditionalSingleBranch=Af;});var y0=S(vu=>{Object.defineProperty(vu,"__esModule",{value:true});vu.CustomFlags=void 0;var g0;(function(n){n[n.ParsingString=1]="ParsingString",n[n.TagActive=2]="TagActive";})(g0||(vu.CustomFlags=g0={}));});var v0=S(Cu=>{Object.defineProperty(Cu,"__esModule",{value:true});Cu.DebugMetadata=void 0;var Df=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}};Cu.DebugMetadata=Df;});var C0=S(bu=>{Object.defineProperty(bu,"__esModule",{value:true});bu.ExternalDeclaration=void 0;var YT=Pe(),xf=class extends YT.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}`}};bu.ExternalDeclaration=xf;});var b0=S(_u=>{Object.defineProperty(_u,"__esModule",{value:true});_u.FlowDecl=void 0;var Pf=class{constructor(e,t,r){this.name=e,this.args=t,this.isFunction=r;}};_u.FlowDecl=Pf;});var Tf=S(Su=>{Object.defineProperty(Su,"__esModule",{value:true});Su.Wrap=void 0;var QT=Pe(),Of=class extends QT.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Su.Wrap=Of;});var _0=S(Eu=>{Object.defineProperty(Eu,"__esModule",{value:true});Eu.Glue=void 0;var ZT=Tf(),Nf=class extends ZT.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Eu.Glue=Nf;});var Au=S(wu=>{Object.defineProperty(wu,"__esModule",{value:true});wu.Glue=void 0;var e1=mt(),Ff=class extends e1.InkObject{toString(){return "Glue"}};wu.Glue=Ff;});var E0=S(Du=>{Object.defineProperty(Du,"__esModule",{value:true});Du.IncDecExpression=void 0;var t1=Jo(),S0=Ft(),n1=sn(),r1=nn(),i1=Te(),s1=Ln(),a1=fi(),o1=_r(),If=class extends S0.Expression{constructor(e,t,r){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=i=>{var a,s;i.AddContent(new a1.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(i):i.AddContent(new i1.IntValue(1)),i.AddContent(r1.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new s1.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 S0.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 o1.Weave)&&!(this.parent instanceof n1.FlowBase)&&!(this.parent instanceof t1.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Du.IncDecExpression=If;});var Rf=S(xu=>{Object.defineProperty(xu,"__esModule",{value:true});xu.IncludedFile=void 0;var u1=Pe(),kf=class extends u1.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};xu.IncludedFile=kf;});var w0=S(Pu=>{Object.defineProperty(Pu,"__esModule",{value:true});Pu.InfixOperator=void 0;var $f=class{constructor(e,t,r){this.type=e,this.precedence=t,this.requireWhitespace=r,this.toString=()=>this.type;}};Pu.InfixOperator=$f;});var jf=S(Ou=>{Object.defineProperty(Ou,"__esModule",{value:true});Ou.Knot=void 0;var l1=sn(),A0=li(),Vf=class extends l1.FlowBase{get flowLevel(){return A0.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,A0.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);}}}};Ou.Knot=Vf;});var D0=S(Tu=>{Object.defineProperty(Tu,"__esModule",{value:true});Tu.List=void 0;var c1=Ft(),h1=yt(),d1=yt(),f1=Te(),Lf=class extends c1.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var r,i;let a=new h1.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 d1.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 f1.ListValue(a));};}get typeName(){return "List"}};Tu.List=Lf;});var Bf=S(Nu=>{Object.defineProperty(Nu,"__esModule",{value:true});Nu.ListElementDefinition=void 0;var p1=Pe(),m1=Cn(),qf=class extends p1.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,m1.SymbolType.ListItem);}};Nu.ListElementDefinition=qf;});var Mf=S(Fu=>{Object.defineProperty(Fu,"__esModule",{value:true});Fu.StatementLevel=void 0;var x0;(function(n){n[n.InnerBlock=0]="InnerBlock",n[n.Stitch=1]="Stitch",n[n.Knot=2]="Knot",n[n.Top=3]="Top";})(x0||(Fu.StatementLevel=x0={}));});var Gf=S(Iu=>{Object.defineProperty(Iu,"__esModule",{value:true});Iu.Stitch=void 0;var g1=sn(),y1=li(),Wf=class extends g1.FlowBase{get flowLevel(){return y1.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"}};Iu.Stitch=Wf;});var Ru=S(ku=>{Object.defineProperty(ku,"__esModule",{value:true});ku.Tag=void 0;var v1=mt(),Hf=class extends v1.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};ku.Tag=Hf;});var zf=S($u=>{Object.defineProperty($u,"__esModule",{value:true});$u.Choice=void 0;var C1=pt(),b1=Qe(),_1=mt(),Jf=class n extends _1.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, b1.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new C1.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}};$u.Choice=Jf;});var Kf=S(Vu=>{Object.defineProperty(Vu,"__esModule",{value:true});Vu.ListDefinitionsOrigin=void 0;var S1=yt(),E1=Te(),w1=Qe(),Uf=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=S1.InkListItem.fromSerializedKey(r),s=new E1.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, w1.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Vu.ListDefinitionsOrigin=Uf;});var gi=S(Bu=>{Object.defineProperty(Bu,"__esModule",{value:true});Bu.JsonSerialisation=void 0;var ju=Re(),Ct=Te(),P0=Au(),oe=Ze(),mi=vr(),O0=rn(),T0=vo(),Xf=fi(),N0=Ln(),Yf=nn(),F0=yr(),I0=Ru(),A1=pt(),k0=zf(),D1=Cf(),x1=Kf(),Lu=yt(),$e=fe(),Sr=Qe(),qu=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, Sr.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, $e.asOrNull)(t,ju.Container);if(r){this.WriteRuntimeContainer(e,r);return}let i=(0, $e.asOrNull)(t,O0.Divert);if(i){let v="->";i.isExternal?v="x()":i.pushesToStack&&(i.stackPushType==mi.PushPopType.Function?v="f()":i.stackPushType==mi.PushPopType.Tunnel&&(v="->t->"));let w;i.hasVariableTarget?w=i.variableDivertName:w=i.targetPathString,e.WriteObjectStart(),e.WriteProperty(v,w),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, $e.asOrNull)(t,T0.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, $e.asOrNull)(t,Ct.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, $e.asOrNull)(t,Ct.IntValue);if(o){e.WriteInt(o.value);return}let u=(0, $e.asOrNull)(t,Ct.FloatValue);if(u){e.WriteFloat(u.value);return}let l=(0, $e.asOrNull)(t,Ct.StringValue);if(l){l.isNewline?e.Write(`
24
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(l.value),e.WriteStringEnd());return}let c=(0, $e.asOrNull)(t,Ct.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, $e.asOrNull)(t,Ct.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, Sr.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let f=(0, $e.asOrNull)(t,Ct.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, $e.asOrNull)(t,P0.Glue)){e.Write("<>");return}let p=(0, $e.asOrNull)(t,oe.ControlCommand);if(p){e.Write(n._controlCommandNames[p.commandType]);return}let m=(0, $e.asOrNull)(t,Yf.NativeFunctionCall);if(m){let v=m.name;v=="^"&&(v="L^"),e.Write(v);return}let C=(0, $e.asOrNull)(t,Xf.VariableReference);if(C){e.WriteObjectStart();let v=C.pathStringForCount;v!=null?e.WriteProperty("CNT?",v):e.WriteProperty("VAR?",C.name),e.WriteObjectEnd();return}let b=(0, $e.asOrNull)(t,N0.VariableAssignment);if(b){e.WriteObjectStart();let v=b.isGlobal?"VAR=":"temp=";e.WriteProperty(v,b.variableName),b.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, $e.asOrNull)(t,F0.Void)){e.Write("void");return}let d=(0, $e.asOrNull)(t,I0.Tag);if(d){e.WriteObjectStart(),e.WriteProperty("#",d.text),e.WriteObjectEnd();return}let _=(0, $e.asOrNull)(t,k0.Choice);if(_){this.WriteChoice(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, Sr.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 Ct.Value.Create(e);if(typeof e=="string"){let t=e.toString(),r=/^([0-9]+.[0-9]+f)$/.exec(t);if(r)return new Ct.FloatValue(parseFloat(r[0]));let i=t[0];if(i=="^")return new Ct.StringValue(t.substring(1));if(i==`
25
25
  `&&t.length==1)return new Ct.StringValue(`
26
- `);if(t=="<>")return new D0.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new oe.ControlCommand(a)}if(t=="L^"&&(t="^"),zf.NativeFunctionCall.CallExistsWithName(t))return zf.NativeFunctionCall.CallWithName(t);if(t=="->->")return oe.ControlCommand.PopTunnel();if(t=="~ret")return oe.ControlCommand.PopFunction();if(t=="void")return new T0.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new Ct.DivertTargetValue(new S1.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new Ct.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=fi.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=fi.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=fi.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=fi.PushPopType.Function),i){let c=new x0.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 P0.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new Jf.VariableReference(r.toString());if(r=t["CNT?"]){let c=new Jf.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 O0.VariableAssignment(c,h);return d.isGlobal=l,d}if(t["#"]!==void 0)return r=t["#"],new N0.Tag(r.toString());if(r=t.list){let c=r,h=new ju.InkList;if(r=t.origins){let d=r;h.SetInitialOriginNames(d);}for(let d in c)if(c.hasOwnProperty(d)){let g=c[d],f=new ju.InkListItem(d),m=parseInt(g);h.Add(f,m);}return new Ct.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, br.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, Re.asOrNull)(l,Vu.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 Vu.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, Re.asOrNull)(s,Vu.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new F0.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, br.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=ju.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, br.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=ju.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, br.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 E1.ListDefinition(a,o);r.push(u);}return new w1.ListDefinitionsOrigin(r)}};qu.JsonSerialisation=Lu;Lu._controlCommandNames=(()=>{let n=[];n[oe.ControlCommand.CommandType.EvalStart]="ev",n[oe.ControlCommand.CommandType.EvalOutput]="out",n[oe.ControlCommand.CommandType.EvalEnd]="/ev",n[oe.ControlCommand.CommandType.Duplicate]="du",n[oe.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[oe.ControlCommand.CommandType.PopFunction]="~ret",n[oe.ControlCommand.CommandType.PopTunnel]="->->",n[oe.ControlCommand.CommandType.BeginString]="str",n[oe.ControlCommand.CommandType.EndString]="/str",n[oe.ControlCommand.CommandType.NoOp]="nop",n[oe.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[oe.ControlCommand.CommandType.Turns]="turn",n[oe.ControlCommand.CommandType.TurnsSince]="turns",n[oe.ControlCommand.CommandType.ReadCount]="readc",n[oe.ControlCommand.CommandType.Random]="rnd",n[oe.ControlCommand.CommandType.SeedRandom]="srnd",n[oe.ControlCommand.CommandType.VisitIndex]="visit",n[oe.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[oe.ControlCommand.CommandType.StartThread]="thread",n[oe.ControlCommand.CommandType.Done]="done",n[oe.ControlCommand.CommandType.End]="end",n[oe.ControlCommand.CommandType.ListFromInt]="listInt",n[oe.ControlCommand.CommandType.ListRange]="range",n[oe.ControlCommand.CommandType.ListRandom]="lrnd",n[oe.ControlCommand.CommandType.BeginTag]="#",n[oe.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<oe.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var Xf=w(Ns=>{Object.defineProperty(Ns,"__esModule",{value:true});Ns.CallStack=void 0;var Uf=gr(),I0=pt(),A1=Fs(),k0=pi(),D1=Oe(),x1=fr(),Os=bs(),P1=os(),R0=ni(),Kf=Ye(),Ts=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){P1.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=Os.Pointer.Null,arguments[0]instanceof A1.Story){let e=arguments[0];this._startOfRoot=Os.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(Uf.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=Os.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==Uf.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, R0.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, R0.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&D1.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 x1.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==Uf.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, Kf.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Ns.CallStack=Ts;(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=Os.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=Os.Pointer.Null,d,g=l.cPath;if(typeof g<"u"){d=g.toString();let _=a.ContentAtPath(new I0.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 f=!!l.exp,m=new e(c,h,f),b=l.temp;typeof b<"u"?m.temporaryVariables=k0.JsonSerialisation.JObjectToDictionaryRuntimeObjs(b):m.temporaryVariables.clear(),this.callstack.push(m);}let o=i.previousContentObject;if(typeof o<"u"){let u=new I0.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, Kf.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"),k0.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, Kf.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(Ts||(Ns.CallStack=Ts={}));});var V0=w(Mu=>{Object.defineProperty(Mu,"__esModule",{value:true});Mu.VariablesState=void 0;var Je=Oe(),O1=ls(),$0=pi(),Ze=fe(),Is=ni(),Bn=Ye();function T1(){return class{}}var Bu=class n extends T1(){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=Je.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, Bn.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=$0.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Bn.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),$0.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Bn.throwNullException)("obj1");if(t===null)return (0, Bn.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, Ze.asOrNull)(e,Je.BoolValue);if(r!==null)return r.value===(0, Ze.asOrThrows)(t,Je.BoolValue).value;let i=(0, Ze.asOrNull)(e,Je.IntValue);if(i!==null)return i.value===(0, Ze.asOrThrows)(t,Je.IntValue).value;let a=(0, Ze.asOrNull)(e,Je.FloatValue);if(a!==null)return a.value===(0, Ze.asOrThrows)(t,Je.FloatValue).value;let s=(0, Ze.asOrNull)(e,Je.Value),o=(0, Ze.asOrNull)(t,Je.Value);if(s!==null&&o!==null)return (0, Ze.isEquatable)(s.valueObject)&&(0, Ze.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, Ze.asOrNull)(r,Je.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, Is.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, Is.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, Is.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Bn.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, Bn.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, Ze.asOrNull)(t,Je.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Ze.asOrNull)(this.GetRawVariableWithName(r,i),Je.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, Ze.asOrThrows)(e,Je.ListValue),i=(0, Ze.asOrThrows)(t,Je.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, Is.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, Is.tryGetValueFromMap)(this._globalVariables,e,null))),Je.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, Bn.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, Bn.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, Ze.asOrNull)(r,Je.VariablePointerValue);return i??new Je.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Mu.VariablesState=Bu;Bu.dontSaveDefaultValues=true;});var Qf=w(Wu=>{Object.defineProperty(Wu,"__esModule",{value:true});Wu.PRNG=void 0;var Yf=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}};Wu.PRNG=Yf;});var j0=w(Gu=>{Object.defineProperty(Gu,"__esModule",{value:true});Gu.StatePatch=void 0;var Zf=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}}};Gu.StatePatch=Zf;});var ep=w(Rs=>{Object.defineProperty(Rs,"__esModule",{value:true});Rs.SimpleJson=void 0;var ks=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};Rs.SimpleJson=ks;(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={}));})(ks||(Rs.SimpleJson=ks={}));});var q0=w(Ju=>{Object.defineProperty(Ju,"__esModule",{value:true});Ju.Flow=void 0;var L0=Xf(),Hu=pi(),N1=Ye(),tp=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new L0.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=Hu.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=Hu.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=>Hu.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, N1.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)Hu.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 L0.CallStack.Thread(a,t);}}}};Ju.Flow=tp;});var W0=w(Uu=>{Object.defineProperty(Uu,"__esModule",{value:true});Uu.StoryState=void 0;var F1=Xf(),I1=V0(),qe=Oe(),Mn=gr(),k1=ku(),np=wu(),B0=pt(),st=Qe(),rp=fr(),Wn=pi(),R1=Qf(),$1=mr(),mi=bs(),$s=ni(),Ve=fe(),V1=os(),$t=Ye(),j1=Fs(),L1=j0(),M0=ep(),zu=q0(),q1=yt(),ip=class n{ToJson(e=false){let t=new M0.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=M0.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 B0.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, $s.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, $t.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, $s.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, $s.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, $s.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, $t.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, $t.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 rp.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, Ve.asOrNull)(r,qe.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, Ve.asOrNull)(r,st.ControlCommand);a!==null&&(a.commandType==st.ControlCommand.CommandType.BeginTag?t=true:a.commandType==st.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new rp.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 P0.Glue;for(let a=0;a<n._controlCommandNames.length;++a){let s=n._controlCommandNames[a];if(t==s)return new oe.ControlCommand(a)}if(t=="L^"&&(t="^"),Yf.NativeFunctionCall.CallExistsWithName(t))return Yf.NativeFunctionCall.CallWithName(t);if(t=="->->")return oe.ControlCommand.PopTunnel();if(t=="~ret")return oe.ControlCommand.PopFunction();if(t=="void")return new F0.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,r;if(t["^->"])return r=t["^->"],new Ct.DivertTargetValue(new A1.Path(r.toString()));if(t["^var"]){r=t["^var"];let c=new Ct.VariablePointerValue(r.toString());return "ci"in t&&(r=t.ci,c.contextIndex=parseInt(r)),c}let i=false,a=false,s=mi.PushPopType.Function,o=false;if((r=t["->"])?i=true:(r=t["f()"])?(i=true,a=true,s=mi.PushPopType.Function):(r=t["->t->"])?(i=true,a=true,s=mi.PushPopType.Tunnel):(r=t["x()"])&&(i=true,o=true,a=false,s=mi.PushPopType.Function),i){let c=new O0.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 T0.ChoicePoint;return c.pathStringOnChoice=r.toString(),(r=t.flg)&&(c.flags=parseInt(r)),c}if(r=t["VAR?"])return new Xf.VariableReference(r.toString());if(r=t["CNT?"]){let c=new Xf.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 N0.VariableAssignment(c,h);return f.isGlobal=l,f}if(t["#"]!==void 0)return r=t["#"],new I0.Tag(r.toString());if(r=t.list){let c=r,h=new Lu.InkList;if(r=t.origins){let f=r;h.SetInitialOriginNames(f);}for(let f in c)if(c.hasOwnProperty(f)){let g=c[f],p=new Lu.InkListItem(f),m=parseInt(g);h.Add(p,m);}return new Ct.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, Sr.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, $e.asOrNull)(l,ju.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 ju.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, $e.asOrNull)(s,ju.Container);o&&(o.name=a),i.set(a,s);}t.namedOnlyContent=i;}return t}static JObjectToChoice(e){let t=new k0.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, Sr.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[i,a]of r){let s=Lu.InkListItem.fromSerializedKey(i),o=a;if(s.itemName===null)return (0, Sr.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=Lu.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, Sr.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 D1.ListDefinition(a,o);r.push(u);}return new x1.ListDefinitionsOrigin(r)}};Bu.JsonSerialisation=qu;qu._controlCommandNames=(()=>{let n=[];n[oe.ControlCommand.CommandType.EvalStart]="ev",n[oe.ControlCommand.CommandType.EvalOutput]="out",n[oe.ControlCommand.CommandType.EvalEnd]="/ev",n[oe.ControlCommand.CommandType.Duplicate]="du",n[oe.ControlCommand.CommandType.PopEvaluatedValue]="pop",n[oe.ControlCommand.CommandType.PopFunction]="~ret",n[oe.ControlCommand.CommandType.PopTunnel]="->->",n[oe.ControlCommand.CommandType.BeginString]="str",n[oe.ControlCommand.CommandType.EndString]="/str",n[oe.ControlCommand.CommandType.NoOp]="nop",n[oe.ControlCommand.CommandType.ChoiceCount]="choiceCnt",n[oe.ControlCommand.CommandType.Turns]="turn",n[oe.ControlCommand.CommandType.TurnsSince]="turns",n[oe.ControlCommand.CommandType.ReadCount]="readc",n[oe.ControlCommand.CommandType.Random]="rnd",n[oe.ControlCommand.CommandType.SeedRandom]="srnd",n[oe.ControlCommand.CommandType.VisitIndex]="visit",n[oe.ControlCommand.CommandType.SequenceShuffleIndex]="seq",n[oe.ControlCommand.CommandType.StartThread]="thread",n[oe.ControlCommand.CommandType.Done]="done",n[oe.ControlCommand.CommandType.End]="end",n[oe.ControlCommand.CommandType.ListFromInt]="listInt",n[oe.ControlCommand.CommandType.ListRange]="range",n[oe.ControlCommand.CommandType.ListRandom]="lrnd",n[oe.ControlCommand.CommandType.BeginTag]="#",n[oe.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<oe.ControlCommand.CommandType.TOTAL_VALUES;++e)if(n[e]==null)throw new Error("Control command not accounted for in serialisation");return n})();});var ep=S(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.CallStack=void 0;var Qf=vr(),R0=pt(),P1=Rs(),$0=gi(),O1=Te(),T1=mr(),Fs=Es(),N1=cs(),V0=ii(),Zf=Qe(),Is=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){N1.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=Fs.Pointer.Null,arguments[0]instanceof P1.Story){let e=arguments[0];this._startOfRoot=Fs.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(Qf.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=Fs.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==Qf.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, V0.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, V0.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&O1.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 T1.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==Qf.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, Zf.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};ks.CallStack=Is;(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=Fs.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=Fs.Pointer.Null,f,g=l.cPath;if(typeof g<"u"){f=g.toString();let b=a.ContentAtPath(new R0.Path(f));if(h.container=b.container,h.index=parseInt(l.idx),b.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?");b.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 p=!!l.exp,m=new e(c,h,p),C=l.temp;typeof C<"u"?m.temporaryVariables=$0.JsonSerialisation.JObjectToDictionaryRuntimeObjs(C):m.temporaryVariables.clear(),this.callstack.push(m);}let o=i.previousContentObject;if(typeof o<"u"){let u=new R0.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, Zf.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"),$0.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, Zf.throwNullException)("this.previousPointer.Resolve()");i.WriteProperty("previousContentObject",a.path.toString());}i.WriteObjectEnd();}}n.Thread=t;})(Is||(ks.CallStack=Is={}));});var L0=S(Wu=>{Object.defineProperty(Wu,"__esModule",{value:true});Wu.VariablesState=void 0;var ze=Te(),F1=ds(),j0=gi(),et=fe(),$s=ii(),Mn=Qe();function I1(){return class{}}var Mu=class n extends I1(){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 F1.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let r=ze.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, Mn.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=j0.JsonSerialisation.JTokenToRuntimeObject(i);if(a===null)return (0, Mn.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),j0.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Mn.throwNullException)("obj1");if(t===null)return (0, Mn.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let r=(0, et.asOrNull)(e,ze.BoolValue);if(r!==null)return r.value===(0, et.asOrThrows)(t,ze.BoolValue).value;let i=(0, et.asOrNull)(e,ze.IntValue);if(i!==null)return i.value===(0, et.asOrThrows)(t,ze.IntValue).value;let a=(0, et.asOrNull)(e,ze.FloatValue);if(a!==null)return a.value===(0, et.asOrThrows)(t,ze.FloatValue).value;let s=(0, et.asOrNull)(e,ze.Value),o=(0, et.asOrNull)(t,ze.Value);if(s!==null&&o!==null)return (0, et.isEquatable)(s.valueObject)&&(0, et.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, et.asOrNull)(r,ze.VariablePointerValue);return i!==null&&(r=this.ValueAtVariablePointer(i)),r}TryGetDefaultVariableValue(e){let t=(0, $s.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, $s.tryGetValueFromMap)(this._globalVariables,e,null),i.exists)||this._defaultGlobalVariables!==null&&(i=(0, $s.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),i.exists))return i.result;if(this._listDefsOrigin===null)return (0, Mn.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, Mn.throwNullException)("name");let i=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(r),e.isNewDeclaration){let s=(0, et.asOrNull)(t,ze.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, et.asOrNull)(this.GetRawVariableWithName(r,i),ze.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, et.asOrThrows)(e,ze.ListValue),i=(0, et.asOrThrows)(t,ze.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, $s.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists||(r=(0, $s.tryGetValueFromMap)(this._globalVariables,e,null))),ze.ListValue.RetainListOriginsForAssignment(r.result,t),e===null)return (0, Mn.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, Mn.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, et.asOrNull)(r,ze.VariablePointerValue);return i??new ze.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Wu.VariablesState=Mu;Mu.dontSaveDefaultValues=true;});var np=S(Gu=>{Object.defineProperty(Gu,"__esModule",{value:true});Gu.PRNG=void 0;var tp=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}};Gu.PRNG=tp;});var q0=S(Hu=>{Object.defineProperty(Hu,"__esModule",{value:true});Hu.StatePatch=void 0;var rp=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}}};Hu.StatePatch=rp;});var ip=S(js=>{Object.defineProperty(js,"__esModule",{value:true});js.SimpleJson=void 0;var Vs=class n{static TextToDictionary(e){return new n.Reader(e).ToDictionary()}static TextToArray(e){return new n.Reader(e).ToArray()}};js.SimpleJson=Vs;(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={}));})(Vs||(js.SimpleJson=Vs={}));});var M0=S(zu=>{Object.defineProperty(zu,"__esModule",{value:true});zu.Flow=void 0;var B0=ep(),Ju=gi(),k1=Qe(),sp=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new B0.CallStack(t),arguments[2]){let r=arguments[2];this.callStack.SetJsonToken(r.callstack,t),this.outputStream=Ju.JsonSerialisation.JArrayToRuntimeObjList(r.outputStream),this.currentChoices=Ju.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=>Ju.JsonSerialisation.WriteListRuntimeObjs(r,this.outputStream));let t=false;for(let r of this.currentChoices){if(r.threadAtGeneration===null)return (0, k1.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)Ju.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 B0.CallStack.Thread(a,t);}}}};zu.Flow=sp;});var H0=S(Ku=>{Object.defineProperty(Ku,"__esModule",{value:true});Ku.StoryState=void 0;var R1=ep(),$1=L0(),Me=Te(),Wn=vr(),V1=Ru(),ap=Au(),W0=pt(),at=Ze(),op=mr(),Gn=gi(),j1=np(),L1=yr(),yi=Es(),Ls=ii(),je=fe(),q1=cs(),$t=Qe(),B1=Rs(),M1=q0(),G0=ip(),Uu=M0(),W1=yt(),up=class n{ToJson(e=false){let t=new G0.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=G0.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 W0.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, Ls.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, $t.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, Ls.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, Ls.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, Ls.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, $t.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, $t.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 op.StringBuilder,t=false;for(let r of this.outputStream){let i=(0, je.asOrNull)(r,Me.StringValue);if(!t&&i!==null)e.Append(i.value);else {let a=(0, je.asOrNull)(r,at.ControlCommand);a!==null&&(a.commandType==at.ControlCommand.CommandType.BeginTag?t=true:a.commandType==at.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new op.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 rp.StringBuilder;for(let r of this.outputStream){let i=(0, Ve.asOrNull)(r,st.ControlCommand);if(i!=null){if(i.commandType==st.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==st.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, Ve.asOrNull)(r,qe.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, Ve.asOrNull)(r,k1.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=mi.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 zu.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new I1.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new R1.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=mi.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, $s.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new zu.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, $t.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new n(this.story);if(t._patch=new L1.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new F1.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=>Wn.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, $t.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Wn.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Wn.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",j1.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 zu.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new zu.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, $t.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=Wn.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Wn.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=Wn.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new B0.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Wn.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Wn.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, Ve.asOrNull)(e,qe.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, $t.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 op.StringBuilder;for(let r of this.outputStream){let i=(0, je.asOrNull)(r,at.ControlCommand);if(i!=null){if(i.commandType==at.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==at.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, je.asOrNull)(r,Me.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, je.asOrNull)(r,V1.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=yi.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 Uu.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new $1.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new j1.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=yi.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, Ls.tryGetValueFromMap)(this._namedFlows,e,null);r.exists?t=r.result:(t=new Uu.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, $t.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 R1.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=>Gn.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, $t.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Gn.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Gn.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",B1.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 Uu.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new Uu.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, $t.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=Gn.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Gn.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=Gn.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new W0.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Gn.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Gn.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, je.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, $t.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
- `)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 qe.StringValue(t.substring(0,r));o.push(c);}o.push(new qe.StringValue(`
32
- `)),u=i+1;}if(a!=-1&&(l=s),l>u){let c=t.substring(u,l);o.push(new qe.StringValue(c));}if(a!=-1&&s>i&&(o.push(new qe.StringValue(`
33
- `)),a<t.length-1)){let c=t.length-a-1,h=new qe.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, Ve.asOrNull)(e,np.Glue),r=(0, Ve.asOrNull)(e,qe.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==Mn.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 st.ControlCommand?c:null;if((c instanceof np.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==st.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==Mn.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, $t.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, Ve.asOrNull)(r,st.ControlCommand),a=(0, Ve.asOrNull)(r,qe.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, Ve.asOrNull)(this.outputStream[t],qe.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 np.Glue)this.outputStream.splice(e,1);else if(t instanceof st.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof st.ControlCommand);e--){let r=this.outputStream[e];if(r instanceof qe.StringValue){if(r.isNewline)return true;if(r.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof qe.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, Ve.asOrNull)(this.outputStream[e],st.ControlCommand);if(t instanceof st.ControlCommand&&t.commandType==st.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, Ve.asOrNull)(e,qe.ListValue);if(t){let r=t.value;if(r===null)return (0, $t.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, $t.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, $t.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, $t.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, Ve.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, Ve.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=mi.Pointer.Null,this.previousPointer=mi.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){V1.Debug.Assert(this.callStack.currentElement.type==Mn.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, Ve.asOrNull)(r,qe.StringValue),a=(0, Ve.asOrNull)(r,st.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==Mn.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(Mn.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=mi.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 q1.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, Ve.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(qe.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Mn.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=mi.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Mn.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(Mn.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof $1.Void)return null;let r=(0, Ve.asOrThrows)(t,qe.Value);return r.valueType==qe.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;}};Uu.StoryState=ip;});var G0=w(Ku=>{Object.defineProperty(Ku,"__esModule",{value:true});Ku.Stopwatch=void 0;var sp=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;}};Ku.Stopwatch=sp;});var J0=w(Xu=>{Object.defineProperty(Xu,"__esModule",{value:true});Xu.ErrorType=void 0;var H0;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(H0||(Xu.ErrorType=H0={}));});var Fs=w(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.Story=Er.InkList=void 0;var et=ke(),ap=mt(),op=pi(),B1=W0(),K=Qe(),Vt=gr(),M1=yo(),W1=Wf(),z0=an(),L=Oe(),up=pt(),Vs=mr(),Yu=ku(),G1=jn(),H1=hi(),J1=sn(),_r=ls(),lp=Qf(),Sr=fr(),z1=Hf(),U1=G0(),Gn=bs(),js=yt(),Z=fe(),he=Ye(),U0=ep(),K0=J0(),K1=yt();Object.defineProperty(Er,"InkList",{enumerable:true,get:function(){return K1.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var gi=class n extends ap.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, he.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 et.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=U0.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new z1.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=op.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, Z.asOrThrows)(op.JsonSerialisation.JTokenToRuntimeObject(o),et.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new U0.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>op.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=js.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 B1.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, he.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, he.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new up.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 U1.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof _r.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(Vt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Vt.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,K0.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,K0.ErrorType.Warning);this.ResetErrors();}else {let s=new Sr.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 _r.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, he.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, he.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, he.throwNullException)("prevText");if(t===null)return (0, he.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 Sr.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 et.Container?t:null}PointerAtPath(e){if(e.length==0)return Gn.Pointer.Null;let t=new Gn.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, he.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, he.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, Z.asOrNull)(t.Resolve(),et.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=Gn.Pointer.StartOf(r),r=(0, Z.asOrNull)(t.Resolve(),et.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, Z.asOrNull)(i,M1.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof et.Container&&(e=false),e){let u=(0, Z.asOrNull)(i,L.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new L.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, Z.asOrNull)(i,K.ControlCommand);o&&o.commandType==K.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, Z.asOrNull)(s,et.Container)||(0, Z.asOrNull)(e.container,et.Container);for(;o;)this._prevContainers.push(o),o=(0, Z.asOrNull)(o.parent,et.Container);}let r=t.Resolve();if(r==null)return;let i=(0, Z.asOrNull)(r.parent,et.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, Z.asOrNull)(i.parent,et.Container);}}PopChoiceStringAndTags(e){let t=(0, Z.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);for(;this.state.evaluationStack.length>0&&(0, Z.asOrNull)(this.state.PeekEvaluationStack(),Yu.Tag)!=null;){let r=(0, Z.asOrNull)(this.state.PopEvaluationStack(),Yu.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 W1.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 L.Value){let r=e;if(r instanceof L.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 z0.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 L.DivertTargetValue)){let s=(0, Z.asOrNull)(i,L.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof L.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, Z.asOrThrows)(i,L.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 K.ControlCommand){let t=e;switch(t.commandType){case K.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case K.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case K.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof Vs.Void)){let S=new L.StringValue(C.toString());this.state.PushToOutputStream(S);}}break;case K.ControlCommand.CommandType.NoOp:break;case K.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case K.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case K.ControlCommand.CommandType.PopFunction:case K.ControlCommand.CommandType.PopTunnel:let r=t.commandType==K.ControlCommand.CommandType.PopFunction?Vt.PushPopType.Function:Vt.PushPopType.Tunnel,i=null;if(r==Vt.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();i=(0, Z.asOrNull)(C,L.DivertTargetValue),i===null&&this.Assert(C instanceof Vs.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(Vt.PushPopType.Function,"function return statement (~ return)"),C.set(Vt.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 D="Found "+C.get(r)+", when expected "+S;this.Error(D);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case K.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 K.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case K.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],S=0;for(let A=this.state.outputStream.length-1;A>=0;--A){let E=this.state.outputStream[A];S++;let F=(0, Z.asOrNull)(E,K.ControlCommand);if(F!=null){if(F.commandType==K.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}E instanceof L.StringValue&&C.push(E);}this.state.PopFromOutputStream(S);let D=new Sr.StringBuilder;for(let A of C.reverse())D.Append(A.toString());let O=new Yu.Tag(this.state.CleanOutputWhitespace(D.toString()));this.state.PushEvaluationStack(O);}else this.state.PushToOutputStream(t);break}case K.ControlCommand.CommandType.EndString:{let C=[],S=[],D=0;for(let A=this.state.outputStream.length-1;A>=0;--A){let E=this.state.outputStream[A];D++;let F=(0, Z.asOrNull)(E,K.ControlCommand);if(F&&F.commandType==K.ControlCommand.CommandType.BeginString)break;E instanceof Yu.Tag&&S.push(E),E instanceof L.StringValue&&C.push(E);}this.state.PopFromOutputStream(D);for(let A of S)this.state.PushToOutputStream(A);C=C.reverse();let O=new Sr.StringBuilder;for(let A of C)O.Append(A.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new L.StringValue(O.toString()));break}case K.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new L.IntValue(a));break;case K.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new L.IntValue(this.state.currentTurnIndex+1));break;case K.ControlCommand.CommandType.TurnsSince:case K.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof L.DivertTargetValue)){let C="";s instanceof L.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, Z.asOrThrows)(s,L.DivertTargetValue),u=(0, Z.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,et.Container),l;u!=null?t.commandType==K.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==K.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 L.IntValue(l));break;case K.ControlCommand.CommandType.Random:{let C=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),S=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(S==null||!(S instanceof L.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(C==null||!(C instanceof L.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(C.value===null)return (0, he.throwNullException)("maxInt.value");if(S.value===null)return (0, he.throwNullException)("minInt.value");let D=C.value-S.value+1;(!isFinite(D)||D>Number.MAX_SAFE_INTEGER)&&(D=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),D<=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,E=new lp.PRNG(O).next(),F=E%D+S.value;this.state.PushEvaluationStack(new L.IntValue(F)),this.state.previousRandom=E;break}case K.ControlCommand.CommandType.SeedRandom:let c=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(c==null||!(c instanceof L.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, he.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Vs.Void);break;case K.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new L.IntValue(h));break;case K.ControlCommand.CommandType.SequenceShuffleIndex:let d=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new L.IntValue(d));break;case K.ControlCommand.CommandType.StartThread:break;case K.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Gn.Pointer.Null);break;case K.ControlCommand.CommandType.End:this.state.ForceEnd();break;case K.ControlCommand.CommandType.ListFromInt:let g=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),f=(0, Z.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);if(g===null)throw new _r.StoryException("Passed non-integer when creating a list element from a numerical value.");let m=null;if(this.listDefinitions===null)return (0, he.throwNullException)("this.listDefinitions");let b=this.listDefinitions.TryListGetDefinition(f.value,null);if(b.exists){if(g.value===null)return (0, he.throwNullException)("minInt.value");let C=b.result.TryGetItemWithValue(g.value,js.InkListItem.Null);C.exists&&(m=new L.ListValue(C.result,g.value));}else throw new _r.StoryException("Failed to find LIST called "+f.value);m==null&&(m=new L.ListValue),this.state.PushEvaluationStack(m);break;case K.ControlCommand.CommandType.ListRange:let _=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.Value),y=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.Value),p=(0, Z.asOrNull)(this.state.PopEvaluationStack(),L.ListValue);if(p===null||y===null||_===null)throw new _r.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(p.value===null)return (0, he.throwNullException)("targetList.value");let v=p.value.ListWithSubRange(y.valueObject,_.valueObject);this.state.PushEvaluationStack(new L.ListValue(v));break;case K.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new _r.StoryException("Expected list for LIST_RANDOM");let S=C.value,D=null;if(S===null)throw (0, he.throwNullException)("list");if(S.Count==0)D=new js.InkList;else {let O=this.state.storySeed+this.state.previousRandom,E=new lp.PRNG(O).next(),F=E%S.Count,R=S.entries();for(let P=0;P<=F-1;P++)R.next();let k=R.next().value,x={Key:js.InkListItem.fromSerializedKey(k[0]),Value:k[1]};if(x.Key.originName===null)return (0, he.throwNullException)("randomItem.Key.originName");D=new js.InkList(x.Key.originName,this),D.Add(x.Key,x.Value),this.state.previousRandom=E;}this.state.PushEvaluationStack(new L.ListValue(D));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof G1.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof H1.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new L.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 L.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof J1.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==Vt.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 up.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, he.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, he.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 Sr.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(Vt.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, he.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(Vt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Gn.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, Z.asOrThrows)(this.state.PopEvaluationStack(),L.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=L.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new Vs.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 et.Container&&(e=arguments[0]),arguments[0]instanceof ap.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, Z.asOrNull)(i,ap.InkObject),r);}else if(t!=null){let i=(0, Z.asOrNull)(t,z0.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, he.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 L.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, Z.asOrThrows)(t,L.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 up.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, he.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof et.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, Z.asOrNull)(s,K.ControlCommand);if(o!=null)o.commandType==K.ControlCommand.CommandType.BeginTag?i=true:o.commandType==K.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, Z.asOrNull)(s,L.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 Sr.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new Sr.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=Gn.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Vt.PushPopType.Function)?(this.state.PopCallStack(Vt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Vs.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, he.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, Z.asOrNull)(t.container.parent,et.Container);if(!(r instanceof et.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new Gn.Pointer(r,i),t.index++,e=true,t.container===null)return (0, he.throwNullException)("pointer.container")}return e||(t=Gn.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, he.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, he.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, Z.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(!(e instanceof L.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, he.throwNullException)("seqContainer");if(e.value===null)return (0, he.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, Z.asOrThrows)(this.state.PopEvaluationStack(),L.IntValue).value;if(a===null)return (0, he.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let g=0,f=u.length;g<f;g++)l+=u.charCodeAt(g)||0;let c=l+s+this.state.storySeed,h=new lp.PRNG(Math.floor(c)),d=[];for(let g=0;g<r;++g)d.push(g);for(let g=0;g<=o;++g){let f=h.next()%d.length,m=d[f];if(d.splice(f,1),g==o)return m}throw new Error("Should never reach here")}Error(e,t=false){let r=new _r.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}};Er.Story=gi;gi.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={}));})(gi||(Er.Story=gi={}));});var Y0=w(nl=>{Object.defineProperty(nl,"__esModule",{value:true});nl.Story=void 0;var X1=Ua(),Y1=ko(),Qu=ke(),Zu=Qe(),Ls=dr(),el=on(),X0=oi(),Q1=Nf(),Z1=cu(),eN=Vf(),tN=Fs(),yi=bn(),nN=qn(),rN=jn(),qs=fe(),iN=Es(),sN=ws(),aN=vr(),tl=class n extends el.FlowBase{get flowLevel(){return X0.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(Y1.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(Z1.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 Qu.Container;o.AddContent(Zu.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 rN.VariableAssignment(c,true);d.isGlobal=true,o.AddContent(d);}o.AddContent(Zu.ControlCommand.EvalEnd()),o.AddContent(Zu.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(Zu.ControlCommand.Done());let l=new tN.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, qs.asOrNull)(a,Qu.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, qs.asOrNull)(a,Qu.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, qs.asOrNull)(r.parent,Qu.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?Ls.ErrorType.Warning:Ls.ErrorType.Error,o="";if(i instanceof X1.AuthorWarning?(o+="TODO: ",s=Ls.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===Ls.ErrorType.Error,this._hadWarning=s===Ls.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(sN.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||"",X0.FlowLevel.Knot),c=(0, qs.asOrNull)(l,el.FlowBase);if(c&&(c!==r||a===yi.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<yi.SymbolType.List)return;for(let[f,m]of this._listDefs)if(i?.name===f&&r!==m&&m.variableAssignment!==r&&this.NameConflictError(r,i?.name,m,u),!(r instanceof eN.ListElementDefinition))for(let b of m.itemDefinitions)i?.name===b.name&&this.NameConflictError(r,i?.name||"",b,u);if(a<=yi.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<yi.SymbolType.SubFlowAndWeave)return;let g=new aN.Path(i).ResolveFromContext(r);if(g&&g!==r){this.NameConflictError(r,i?.name||"",g,u);return}if(!(a<yi.SymbolType.Arg)&&a!==yi.SymbolType.Arg){let f=(0, qs.asOrNull)(r,el.FlowBase);if(f||(f=(0, iN.ClosestFlowBase)(r)),f&&f.hasParameters&&f.args){for(let m of f.args)if(((o=m.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${i}': name has already been used for a argument to ${f.identifier} on ${f.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let r of e)if(r instanceof Q1.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 el.FlowBase?t.push(u):s.push(u);s.push(new nN.Text(`
36
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};nl.Story=tl;tl.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 Z0=w(rl=>{Object.defineProperty(rl,"__esModule",{value:true});rl.StringExpression=void 0;var Q0=Qe(),oN=Ft(),uN=qn(),lN=fe(),cp=class n extends oN.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof uN.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Q0.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(Q0.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, lN.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};rl.StringExpression=cp;});var tC=w(vi=>{Object.defineProperty(vi,"__esModule",{value:true});vi.LegacyTag=vi.Tag=void 0;var cN=xe(),eC=Qe(),hp=class extends cN.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?eC.ControlCommand.BeginTag():eC.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};vi.Tag=hp;var hN=Df(),dp=class extends hN.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};vi.LegacyTag=dp;});var nC=w(il=>{Object.defineProperty(il,"__esModule",{value:true});il.DefaultFileHandler=void 0;var fp=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.")};}};il.DefaultFileHandler=fp;});var yp=w(ul=>{Object.defineProperty(ul,"__esModule",{value:true});ul.InkParser=void 0;var dN=Av(),fN=Ua(),pN=bd(),Gt=jv(),Me=vs(),mN=ai(),gN=zv(),yN=No(),Bs=ef(),bt=Ho(),vN=ko(),sl=m0(),CN=g0(),wr=ci(),pp=li(),bN=Ft(),_N=y0(),rC=v0(),al=ws(),SN=Ss(),EN=C0(),wN=wu(),ol=_0(),iC=Nf(),AN=S0(),DN=kf(),sC=w0(),xN=cu(),PN=Vf(),ON=Xd(),aC=xe(),TN=vr(),oC=Bd(),uC=cf(),Be=of(),at=jf(),NN=qf(),lC=Y0(),Ms=Z0(),_n=Nd(),Ci=tC(),Sn=qn(),cC=df(),mp=vf(),gp=di(),FN=vd(),Hn=fe(),Ws=Mo(),bi=co(),hC=dr(),IN=nC(),ve=class n extends _n.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(at.StatementLevel.Top);return new lC.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 CN.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, Hn.asOrNull)(s,aC.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let d of c)(0, Hn.asOrNull)(d,aC.ParsedObject)&&(d.hasOwnDebugMetadata||(d.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, Hn.asOrNull)(s,Ws.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?hC.ErrorType.Warning:hC.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 fN.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 bt.ContentList(h));let d=null,g=null,f=this.ParseString("[")!==null;if(f){this.EndTagIfNecessary(c);let y=this.Parse(this.MixedTextAndLogic);y!==null&&(d=new bt.ContentList(y)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(d);let p=this.Parse(this.MixedTextAndLogic);p!==null&&(g=new bt.ContentList(p));}this.Whitespace(),this.EndTagIfNecessary(g??c);let m=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let b=!c&&!g&&!d;if(b&&m===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&f&&!d&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),g||(g=new bt.ContentList),this.EndTagIfNecessary(g),m!==null)for(let y of m){let p=(0, Hn.asOrNull)(y,wr.Divert);p&&p.isEmpty||g.AddContent(y);}g.AddContent(new Sn.Text(`
38
- `));let _=new mN.Choice(c,d,g);return u&&(_.identifier=u),_.indentationDepth=o.length,_.hasWeaveStyleInlineBrackets=f,_.condition=l,_.onceOnly=s,_.isInvisibleDefault=b,_},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new ON.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),_n.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 SN.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(at.StatementLevel.InnerBlock);if(h!==null){o=[new Bs.ConditionalSingleBranch(h)];let g=this.Parse(this.SingleMultilineCondition);g&&(g.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",g),g.isElse=true),o.push(g));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Bs.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let d=0;d<o.length;++d){let g=o[d],f=d===o.length-1;g.ownExpression?(g.matchingEquality=true,h=true):h&&f?(g.matchingEquality=true,g.isElse=true):!f&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",g):d===0?g.isTrueBranch=true:g.isElse=true;}}else {for(let h=0;h<o.length;++h){let d=o[h],g=h===o.length-1;if(d.ownExpression===null)if(g)d.isElse=true;else if(d.isElse){let f=o[o.length-1];f.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",f):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 yN.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 Bs.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new Bs.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(at.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new Sn.Text("")]),this.MultilineWhitespace();let l=new Bs.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:_n.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 Sn.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 wr.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Ci.Tag&&s[0].isStart||s.push(new Sn.Text(`
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 Sn.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Me.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Me.CharacterSet(`{}|
40
- \r\\#`),this._notTextEndCharactersChoice=new Me.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Me.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 cC.TunnelOnwards;if(l<u.length-1){let g=(0, Hn.asOrNull)(u[l+1],wr.Divert);d.divertAfter=g;}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 wr.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 wr.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 TN.Path(s);return new wr.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof cC.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 ol.IncDecExpression(o,c,u):new mp.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof ol.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 oC.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=FN.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof gp.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new ol.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 pp.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new bi.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new bi.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 Sn.Text("")]:o.find(u=>u instanceof wr.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Ms.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new bi.NumberExpression(true,"bool"):s==="false"?new bi.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 al.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||lC.Story.IsReservedKeyword(s[0].name)?null:new gp.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 pN.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 sC.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 AN.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(`
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
+ `)),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, je.asOrNull)(e,ap.Glue),r=(0, je.asOrNull)(e,Me.StringValue),i=true;if(t)this.TrimNewlinesFromOutputStream(),i=true;else if(r){let a=-1,s=this.callStack.currentElement;s.type==Wn.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 at.ControlCommand?c:null;if((c instanceof ap.Glue?c:null)!=null){o=l;break}else if(h!=null&&h.commandType==at.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==Wn.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else r.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(i=false);}if(i){if(e===null)return (0, $t.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, je.asOrNull)(r,at.ControlCommand),a=(0, je.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, je.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 ap.Glue)this.outputStream.splice(e,1);else if(t instanceof at.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof at.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, je.asOrNull)(this.outputStream[e],at.ControlCommand);if(t instanceof at.ControlCommand&&t.commandType==at.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, je.asOrNull)(e,Me.ListValue);if(t){let r=t.value;if(r===null)return (0, $t.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, $t.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(i,null);if(a.result===null)return (0, $t.throwNullException)("StoryState def.result");r.origins.indexOf(a.result)<0&&r.origins.push(a.result);}}}if(e===null)return (0, $t.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, je.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, je.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=yi.Pointer.Null,this.previousPointer=yi.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){q1.Debug.Assert(this.callStack.currentElement.type==Wn.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, je.asOrNull)(r,Me.StringValue),a=(0, je.asOrNull)(r,at.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==Wn.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(Wn.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=yi.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 W1.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, je.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(Me.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==Wn.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=yi.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=Wn.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(Wn.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof L1.Void)return null;let r=(0, je.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;}};Ku.StoryState=up;});var J0=S(Xu=>{Object.defineProperty(Xu,"__esModule",{value:true});Xu.Stopwatch=void 0;var lp=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;}};Xu.Stopwatch=lp;});var U0=S(Yu=>{Object.defineProperty(Yu,"__esModule",{value:true});Yu.ErrorType=void 0;var z0;(function(n){n[n.Author=0]="Author",n[n.Warning=1]="Warning",n[n.Error=2]="Error";})(z0||(Yu.ErrorType=z0={}));});var Rs=S(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.Story=Ar.InkList=void 0;var tt=Re(),cp=mt(),hp=gi(),G1=H0(),K=Ze(),Vt=vr(),H1=vo(),J1=zf(),K0=rn(),L=Te(),dp=pt(),qs=yr(),Qu=Ru(),z1=Ln(),U1=fi(),K1=nn(),Er=ds(),fp=np(),wr=mr(),X1=Kf(),Y1=J0(),Hn=Es(),Bs=yt(),Q=fe(),he=Qe(),X0=ip(),Y0=U0(),Q1=yt();Object.defineProperty(Ar,"InkList",{enumerable:true,get:function(){return Q1.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var vi=class n extends cp.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, he.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 tt.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=X0.SimpleJson.TextToDictionary(i);}else r=arguments[0];if(t!=null&&(this._listDefinitions=new X1.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=hp.JsonSerialisation.JTokenToListDefinitions(u)),this._mainContentContainer=(0, Q.asOrThrows)(hp.JsonSerialisation.JTokenToRuntimeObject(o),tt.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new X0.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",n.inkVersionCurrent),e.WriteProperty("root",r=>hp.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=Bs.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 G1.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, he.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, he.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new dp.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 Y1.Stopwatch;r.Start();let i=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{i=this.ContinueSingleStep();}catch(s){if(!(s instanceof Er.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(Vt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(Vt.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,Y0.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,Y0.ErrorType.Warning);this.ResetErrors();}else {let s=new wr.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 Er.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, he.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, he.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, he.throwNullException)("prevText");if(t===null)return (0, he.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 wr.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 tt.Container?t:null}PointerAtPath(e){if(e.length==0)return Hn.Pointer.Null;let t=new Hn.Pointer,r=e.length,i=null;return e.lastComponent===null?(0, he.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, he.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, Q.asOrNull)(t.Resolve(),tt.Container);for(;r&&(this.VisitContainer(r,true),r.content.length!=0);)t=Hn.Pointer.StartOf(r),r=(0, Q.asOrNull)(t.Resolve(),tt.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, Q.asOrNull)(i,H1.ChoicePoint);if(s){let u=this.ProcessChoice(s);u&&this.state.generatedChoices.push(u),i=null,e=false;}if(i instanceof tt.Container&&(e=false),e){let u=(0, Q.asOrNull)(i,L.VariablePointerValue);if(u&&u.contextIndex==-1){let l=this.state.callStack.ContextForVariableNamed(u.variableName);i=new L.VariablePointerValue(u.variableName,l);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(i):this.state.PushToOutputStream(i);}this.NextContent();let o=(0, Q.asOrNull)(i,K.ControlCommand);o&&o.commandType==K.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, Q.asOrNull)(s,tt.Container)||(0, Q.asOrNull)(e.container,tt.Container);for(;o;)this._prevContainers.push(o),o=(0, Q.asOrNull)(o.parent,tt.Container);}let r=t.Resolve();if(r==null)return;let i=(0, Q.asOrNull)(r.parent,tt.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, Q.asOrNull)(i.parent,tt.Container);}}PopChoiceStringAndTags(e){let t=(0, Q.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);for(;this.state.evaluationStack.length>0&&(0, Q.asOrNull)(this.state.PeekEvaluationStack(),Qu.Tag)!=null;){let r=(0, Q.asOrNull)(this.state.PopEvaluationStack(),Qu.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 J1.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 L.Value){let r=e;if(r instanceof L.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 K0.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 L.DivertTargetValue)){let s=(0, Q.asOrNull)(i,L.IntValue),o="Tried to divert to a target from a variable, but the variable ("+r+") didn't contain a divert target, it ";s instanceof L.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+i+"'.",this.Error(o);}let a=(0, Q.asOrThrows)(i,L.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 K.ControlCommand){let t=e;switch(t.commandType){case K.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case K.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case K.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let v=this.state.PopEvaluationStack();if(!(v instanceof qs.Void)){let w=new L.StringValue(v.toString());this.state.PushToOutputStream(w);}}break;case K.ControlCommand.CommandType.NoOp:break;case K.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case K.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case K.ControlCommand.CommandType.PopFunction:case K.ControlCommand.CommandType.PopTunnel:let r=t.commandType==K.ControlCommand.CommandType.PopFunction?Vt.PushPopType.Function:Vt.PushPopType.Tunnel,i=null;if(r==Vt.PushPopType.Tunnel){let v=this.state.PopEvaluationStack();i=(0, Q.asOrNull)(v,L.DivertTargetValue),i===null&&this.Assert(v instanceof qs.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 v=new Map;v.set(Vt.PushPopType.Function,"function return statement (~ return)"),v.set(Vt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let w=v.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(w="end of flow (-> END or choice)");let D="Found "+v.get(r)+", when expected "+w;this.Error(D);}else this.state.PopCallStack(),i&&(this.state.divertedPointer=this.PointerAtPath(i.targetPath));break;case K.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 K.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case K.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let v=[],w=0;for(let P=this.state.outputStream.length-1;P>=0;--P){let E=this.state.outputStream[P];w++;let F=(0, Q.asOrNull)(E,K.ControlCommand);if(F!=null){if(F.commandType==K.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}E instanceof L.StringValue&&v.push(E);}this.state.PopFromOutputStream(w);let D=new wr.StringBuilder;for(let P of v.reverse())D.Append(P.toString());let O=new Qu.Tag(this.state.CleanOutputWhitespace(D.toString()));this.state.PushEvaluationStack(O);}else this.state.PushToOutputStream(t);break}case K.ControlCommand.CommandType.EndString:{let v=[],w=[],D=0;for(let P=this.state.outputStream.length-1;P>=0;--P){let E=this.state.outputStream[P];D++;let F=(0, Q.asOrNull)(E,K.ControlCommand);if(F&&F.commandType==K.ControlCommand.CommandType.BeginString)break;E instanceof Qu.Tag&&w.push(E),E instanceof L.StringValue&&v.push(E);}this.state.PopFromOutputStream(D);for(let P of w)this.state.PushToOutputStream(P);v=v.reverse();let O=new wr.StringBuilder;for(let P of v)O.Append(P.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new L.StringValue(O.toString()));break}case K.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new L.IntValue(a));break;case K.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new L.IntValue(this.state.currentTurnIndex+1));break;case K.ControlCommand.CommandType.TurnsSince:case K.ControlCommand.CommandType.ReadCount:let s=this.state.PopEvaluationStack();if(!(s instanceof L.DivertTargetValue)){let v="";s instanceof L.IntValue&&(v=". 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+v);break}let o=(0, Q.asOrThrows)(s,L.DivertTargetValue),u=(0, Q.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,tt.Container),l;u!=null?t.commandType==K.ControlCommand.CommandType.TurnsSince?l=this.state.TurnsSinceForContainer(u):l=this.state.VisitCountForContainer(u):(t.commandType==K.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 L.IntValue(l));break;case K.ControlCommand.CommandType.Random:{let v=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),w=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(w==null||!(w instanceof L.IntValue))return this.Error("Invalid value for minimum parameter of RANDOM(min, max)");if(v==null||!(v instanceof L.IntValue))return this.Error("Invalid value for maximum parameter of RANDOM(min, max)");if(v.value===null)return (0, he.throwNullException)("maxInt.value");if(w.value===null)return (0, he.throwNullException)("minInt.value");let D=v.value-w.value+1;(!isFinite(D)||D>Number.MAX_SAFE_INTEGER)&&(D=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),D<=0&&this.Error("RANDOM was called with minimum as "+w.value+" and maximum as "+v.value+". The maximum must be larger");let O=this.state.storySeed+this.state.previousRandom,E=new fp.PRNG(O).next(),F=E%D+w.value;this.state.PushEvaluationStack(new L.IntValue(F)),this.state.previousRandom=E;break}case K.ControlCommand.CommandType.SeedRandom:let c=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(c==null||!(c instanceof L.IntValue))return this.Error("Invalid value passed to SEED_RANDOM");if(c.value===null)return (0, he.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new qs.Void);break;case K.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new L.IntValue(h));break;case K.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new L.IntValue(f));break;case K.ControlCommand.CommandType.StartThread:break;case K.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Hn.Pointer.Null);break;case K.ControlCommand.CommandType.End:this.state.ForceEnd();break;case K.ControlCommand.CommandType.ListFromInt:let g=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),p=(0, Q.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);if(g===null)throw new Er.StoryException("Passed non-integer when creating a list element from a numerical value.");let m=null;if(this.listDefinitions===null)return (0, he.throwNullException)("this.listDefinitions");let C=this.listDefinitions.TryListGetDefinition(p.value,null);if(C.exists){if(g.value===null)return (0, he.throwNullException)("minInt.value");let v=C.result.TryGetItemWithValue(g.value,Bs.InkListItem.Null);v.exists&&(m=new L.ListValue(v.result,g.value));}else throw new Er.StoryException("Failed to find LIST called "+p.value);m==null&&(m=new L.ListValue),this.state.PushEvaluationStack(m);break;case K.ControlCommand.CommandType.ListRange:let b=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.Value),y=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.Value),d=(0, Q.asOrNull)(this.state.PopEvaluationStack(),L.ListValue);if(d===null||y===null||b===null)throw new Er.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(d.value===null)return (0, he.throwNullException)("targetList.value");let _=d.value.ListWithSubRange(y.valueObject,b.valueObject);this.state.PushEvaluationStack(new L.ListValue(_));break;case K.ControlCommand.CommandType.ListRandom:{let v=this.state.PopEvaluationStack();if(v===null)throw new Er.StoryException("Expected list for LIST_RANDOM");let w=v.value,D=null;if(w===null)throw (0, he.throwNullException)("list");if(w.Count==0)D=new Bs.InkList;else {let O=this.state.storySeed+this.state.previousRandom,E=new fp.PRNG(O).next(),F=E%w.Count,R=w.entries();for(let x=0;x<=F-1;x++)R.next();let k=R.next().value,A={Key:Bs.InkListItem.fromSerializedKey(k[0]),Value:k[1]};if(A.Key.originName===null)return (0, he.throwNullException)("randomItem.Key.originName");D=new Bs.InkList(A.Key.originName,this),D.Add(A.Key,A.Value),this.state.previousRandom=E;}this.state.PushEvaluationStack(new L.ListValue(D));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof z1.VariableAssignment){let t=e,r=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,r),true}else if(e instanceof U1.VariableReference){let t=e,r=null;if(t.pathForCount!=null){let i=t.containerForCount,a=this.state.VisitCountForContainer(i);r=new L.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 L.IntValue(0));return this.state.PushEvaluationStack(r),true}else if(e instanceof K1.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==Vt.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 dp.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, he.throwNullException)("choiceToChoose.threadAtGeneration");if(r.targetPath===null)return (0, he.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 wr.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(Vt.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, he.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(Vt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Hn.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, Q.asOrThrows)(this.state.PopEvaluationStack(),L.Value).valueObject;s.push(h);}s.reverse();let o=r.function(s),u=null;o!=null?(u=L.Value.Create(o),this.Assert(u!==null,"Could not create ink value from returned object of type "+typeof o)):u=new qs.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 tt.Container&&(e=arguments[0]),arguments[0]instanceof cp.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, Q.asOrNull)(i,cp.InkObject),r);}else if(t!=null){let i=(0, Q.asOrNull)(t,K0.Divert);if(i&&i.isExternal){let a=i.targetPathString;if(a===null)return (0, he.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 L.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let i=(0, Q.asOrThrows)(t,L.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 dp.Path(e),r=this.ContentAtPath(t).container;if(r===null)return (0, he.throwNullException)("flowContainer");for(;;){let s=r.content[0];if(s instanceof tt.Container)r=s;else break}let i=false,a=null;for(let s of r.content){let o=(0, Q.asOrNull)(s,K.ControlCommand);if(o!=null)o.commandType==K.ControlCommand.CommandType.BeginTag?i=true:o.commandType==K.ControlCommand.CommandType.EndTag&&(i=false);else if(i){let u=(0, Q.asOrNull)(s,L.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 wr.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new wr.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=Hn.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(Vt.PushPopType.Function)?(this.state.PopCallStack(Vt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new qs.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, he.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let r=(0, Q.asOrNull)(t.container.parent,tt.Container);if(!(r instanceof tt.Container))break;let i=r.content.indexOf(t.container);if(i==-1)break;if(t=new Hn.Pointer(r,i),t.index++,e=true,t.container===null)return (0, he.throwNullException)("pointer.container")}return e||(t=Hn.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, he.throwNullException)("choice.targetPath"):r.threadAtGeneration===null?(0, he.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, Q.asOrNull)(this.state.PopEvaluationStack(),L.IntValue);if(!(e instanceof L.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, he.throwNullException)("seqContainer");if(e.value===null)return (0, he.throwNullException)("numElementsIntVal.value");let r=e.value,a=(0, Q.asOrThrows)(this.state.PopEvaluationStack(),L.IntValue).value;if(a===null)return (0, he.throwNullException)("seqCount");let s=a/r,o=a%r,u=t.path.toString(),l=0;for(let g=0,p=u.length;g<p;g++)l+=u.charCodeAt(g)||0;let c=l+s+this.state.storySeed,h=new fp.PRNG(Math.floor(c)),f=[];for(let g=0;g<r;++g)f.push(g);for(let g=0;g<=o;++g){let p=h.next()%f.length,m=f[p];if(f.splice(p,1),g==o)return m}throw new Error("Should never reach here")}Error(e,t=false){let r=new Er.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}};Ar.Story=vi;vi.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={}));})(vi||(Ar.Story=vi={}));});var Z0=S(rl=>{Object.defineProperty(rl,"__esModule",{value:true});rl.Story=void 0;var Z1=Ka(),eN=Ro(),Zu=Re(),el=Ze(),Ms=pr(),tl=sn(),Q0=li(),tN=Rf(),nN=hu(),rN=Bf(),iN=Rs(),Ci=Cn(),sN=Bn(),aN=Ln(),Ws=fe(),oN=Ds(),uN=xs(),lN=br(),nl=class n extends tl.FlowBase{get flowLevel(){return Q0.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(eN.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(nN.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 Zu.Container;o.AddContent(el.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 aN.VariableAssignment(c,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(el.ControlCommand.EvalEnd()),o.AddContent(el.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(el.ControlCommand.Done());let l=new iN.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, Ws.asOrNull)(a,Zu.Container);s&&i.add(s);}if(r.namedContent)for(let[,a]of r.namedContent){let s=(0, Ws.asOrNull)(a,Zu.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, Ws.asOrNull)(r.parent,Zu.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?Ms.ErrorType.Warning:Ms.ErrorType.Error,o="";if(i instanceof Z1.AuthorWarning?(o+="TODO: ",s=Ms.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===Ms.ErrorType.Error,this._hadWarning=s===Ms.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(uN.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||"",Q0.FlowLevel.Knot),c=(0, Ws.asOrNull)(l,tl.FlowBase);if(c&&(c!==r||a===Ci.SymbolType.Arg)){this.NameConflictError(r,i?.name||"",c,u);return}if(a<Ci.SymbolType.List)return;for(let[p,m]of this._listDefs)if(i?.name===p&&r!==m&&m.variableAssignment!==r&&this.NameConflictError(r,i?.name,m,u),!(r instanceof rN.ListElementDefinition))for(let C of m.itemDefinitions)i?.name===C.name&&this.NameConflictError(r,i?.name||"",C,u);if(a<=Ci.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<Ci.SymbolType.SubFlowAndWeave)return;let g=new lN.Path(i).ResolveFromContext(r);if(g&&g!==r){this.NameConflictError(r,i?.name||"",g,u);return}if(!(a<Ci.SymbolType.Arg)&&a!==Ci.SymbolType.Arg){let p=(0, Ws.asOrNull)(r,tl.FlowBase);if(p||(p=(0, oN.ClosestFlowBase)(r)),p&&p.hasParameters&&p.args){for(let m of p.args)if(((o=m.identifier)===null||o===void 0?void 0:o.name)===i?.name){r.Error(`${u} '${i}': name has already been used for a argument to ${p.identifier} on ${p.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let r of e)if(r instanceof tN.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 tl.FlowBase?t.push(u):s.push(u);s.push(new sN.Text(`
36
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};rl.Story=nl;nl.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 tC=S(il=>{Object.defineProperty(il,"__esModule",{value:true});il.StringExpression=void 0;var eC=Ze(),cN=Ft(),hN=Bn(),dN=fe(),pp=class n extends cN.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof hN.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(eC.ControlCommand.BeginString());for(let r of this.content)t.AddContent(r.runtimeObject);t.AddContent(eC.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, dN.asOrNull)(e,n);if(t===null||!this.isSingleString||!t.isSingleString)return false;let r=this.toString(),i=t.toString();return r===i}};il.StringExpression=pp;});var rC=S(bi=>{Object.defineProperty(bi,"__esModule",{value:true});bi.LegacyTag=bi.Tag=void 0;var fN=Pe(),nC=Ze(),mp=class extends fN.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?nC.ControlCommand.BeginTag():nC.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};bi.Tag=mp;var pN=Tf(),gp=class extends pN.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};bi.LegacyTag=gp;});var iC=S(sl=>{Object.defineProperty(sl,"__esModule",{value:true});sl.DefaultFileHandler=void 0;var yp=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.")};}};sl.DefaultFileHandler=yp;});var _p=S(ll=>{Object.defineProperty(ll,"__esModule",{value:true});ll.InkParser=void 0;var mN=xv(),gN=Ka(),yN=wd(),Gt=qv(),Ge=_s(),vN=ui(),CN=Kv(),bN=Fo(),Gs=sf(),bt=Jo(),_N=Ro(),al=y0(),SN=v0(),Dr=di(),vp=hi(),EN=Ft(),wN=C0(),sC=b0(),ol=xs(),AN=As(),DN=_0(),xN=Au(),ul=E0(),aC=Rf(),PN=w0(),ON=jf(),oC=D0(),TN=hu(),NN=Bf(),FN=ef(),uC=Pe(),IN=br(),lC=Hd(),cC=pf(),We=hf(),ot=Mf(),kN=Gf(),hC=Z0(),Hs=tC(),bn=Rd(),_i=rC(),_n=Bn(),dC=gf(),Cp=Sf(),bp=pi(),RN=Sd(),Jn=fe(),Js=Wo(),Si=ho(),fC=pr(),$N=iC(),ve=class n extends bn.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(ot.StatementLevel.Top);return new hC.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 SN.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, Jn.asOrNull)(s,uC.ParsedObject);l&&(l.debugMetadata=this.CreateDebugMetadata(o,u));let c=Array.isArray(s)?s:null;if(c!==null)for(let f of c)(0, Jn.asOrNull)(f,uC.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,u)));let h=(0, Jn.asOrNull)(s,Js.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?fC.ErrorType.Warning:fC.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 gN.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 bt.ContentList(h));let f=null,g=null,p=this.ParseString("[")!==null;if(p){this.EndTagIfNecessary(c);let y=this.Parse(this.MixedTextAndLogic);y!==null&&(f=new bt.ContentList(y)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let d=this.Parse(this.MixedTextAndLogic);d!==null&&(g=new bt.ContentList(d));}this.Whitespace(),this.EndTagIfNecessary(g??c);let m=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let C=!c&&!g&&!f;if(C&&m===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&p&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),g||(g=new bt.ContentList),this.EndTagIfNecessary(g),m!==null)for(let y of m){let d=(0, Jn.asOrNull)(y,Dr.Divert);d&&d.isEmpty||g.AddContent(y);}g.AddContent(new _n.Text(`
38
+ `));let b=new vN.Choice(c,f,g);return u&&(b.identifier=u),b.indentationDepth=o.length,b.hasWeaveStyleInlineBrackets=p,b.condition=l,b.onceOnly=s,b.isInvisibleDefault=C,b},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new FN.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),bn.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 AN.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(ot.StatementLevel.InnerBlock);if(h!==null){o=[new Gs.ConditionalSingleBranch(h)];let g=this.Parse(this.SingleMultilineCondition);g&&(g.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",g),g.isElse=true),o.push(g));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Gs.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let f=0;f<o.length;++f){let g=o[f],p=f===o.length-1;g.ownExpression?(g.matchingEquality=true,h=true):h&&p?(g.matchingEquality=true,g.isElse=true):!p&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",g):f===0?g.isTrueBranch=true:g.isElse=true;}}else {for(let h=0;h<o.length;++h){let f=o[h],g=h===o.length-1;if(f.ownExpression===null)if(g)f.isElse=true;else if(f.isElse){let p=o[o.length-1];p.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",p):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 bN.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 Gs.ConditionalSingleBranch(s[0]);if(u.isTrueBranch=true,o.push(u),s.length>1){let l=new Gs.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(ot.StatementLevel.InnerBlock);s===null&&u===null&&(this.Error("expected content for the conditional branch following '-'"),u=[new _n.Text("")]),this.MultilineWhitespace();let l=new Gs.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:bn.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 _n.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 Dr.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof _i.Tag&&s[0].isStart||s.push(new _n.Text(`
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 _n.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new Ge.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new Ge.CharacterSet(`{}|
40
+ \r\\#`),this._notTextEndCharactersChoice=new Ge.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new Ge.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 dC.TunnelOnwards;if(l<u.length-1){let g=(0, Jn.asOrNull)(u[l+1],Dr.Divert);f.divertAfter=g;}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 Dr.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 Dr.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 IN.Path(s);return new Dr.Divert(u,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof dC.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 ul.IncDecExpression(o,c,u):new Cp.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof ul.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 lC.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=RN.UnaryExpression.WithInner(u,o)),this.Whitespace();let l=this.OneOf([this.String("++"),this.String("--")]);if(l!==null){let c=l==="++";if(!(u instanceof bp.VariableReference))this.Error(`can only increment and decrement variables, but saw '${u}'.`);else {let h=u;u=new ul.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 vp.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new Si.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new Si.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 _n.Text("")]:o.find(u=>u instanceof Dr.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Hs.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new Si.NumberExpression(true,"bool"):s==="false"?new Si.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 ol.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||hC.Story.IsReservedKeyword(s[0].name)?null:new bp.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 yN.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 oC.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 PN.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 iC.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 iC.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(at.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new DN.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 Ws.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new rC.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(at.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new NN.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 rC.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Me.CharacterSet("="),null),[new Sn.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 dN.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 Ws.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(Hn.filterUndef);return new _N.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 bt.ContentList;o instanceof bN.Expression&&!(o instanceof al.FunctionCall||o instanceof ol.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
42
+ `),new aC.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 aC.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(ot.StatementLevel.Knot),u=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new ON.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 Js.Identifier("")),this.Whitespace();let l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new sC.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(ot.StatementLevel.Stitch),u=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new kN.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 sC.FlowDecl(o,u,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new Ge.CharacterSet("="),null),[new _n.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 mN.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 Js.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(Jn.filterUndef);return new wN.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 bt.ContentList;o instanceof EN.Expression&&!(o instanceof ol.FunctionCall||o instanceof ul.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, Hn.asOrNull)(o,al.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(al.FunctionCall)()!==null&&(o=new bt.ContentList(o,new Sn.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 bi.NumberExpression||l instanceof Ms.StringExpression||l instanceof pp.DivertTarget||l instanceof gp.VariableReference||l instanceof sC.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 Ms.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new mp.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 Ws.Identifier(o.name),new mp.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new xN.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 PN.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 bi.NumberExpression||u instanceof pp.DivertTarget||u instanceof Ms.StringExpression?u instanceof Ms.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 vN.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new EN.Glue(new wN.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, Hn.asOrNull)(u,bt.ContentList);return l||(l=new bt.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 uC.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 Ws.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 Me.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=Be.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 uC.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 Be.SequenceType.Once:case Be.SequenceType.Cycle:case Be.SequenceType.Stopping:case Be.SequenceType.Shuffle:case Be.SequenceType.Shuffle|Be.SequenceType.Stopping:case Be.SequenceType.Shuffle|Be.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),Be.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Me.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=Be.SequenceType.Once;break;case "&":s|=Be.SequenceType.Cycle;break;case "~":s|=Be.SequenceType.Shuffle;break;case "$":s|=Be.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=Be.SequenceType.Once;break;case "cycle":s=Be.SequenceType.Cycle;break;case "shuffle":s=Be.SequenceType.Shuffle;break;case "stopping":s=Be.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 bt.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 bt.ContentList(c)),u=true;}return u||o.push(new bt.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(at.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new Sn.Text(`
49
- `)),new bt.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===at.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===at.StatementLevel.Top&&u instanceof oC.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(at.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>=at.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>at.StatementLevel.InnerBlock&&u.push(this.Gather),o>=at.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<=at.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=at.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=at.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(),_n.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 bt.ContentList;o.AddContent(new Ci.Tag(false)),o.AddContent(new Ci.Tag(true)),s=o;}else s=new Ci.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new Me.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?_n.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?_n.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?_n.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?_n.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?_n.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 IN.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 gN.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(sl.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(sl.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(sl.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(sl.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Me.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 bt.ContentList?e.AddContent(new Ci.Tag(false)):e.push(new Ci.Tag(false))),this.tagActive=false);}};ul.InkParser=ve;ve.LatinBasic=Gt.CharacterRange.Define("A","z",new Me.CharacterSet().AddRange("[","`"));ve.LatinExtendedA=Gt.CharacterRange.Define("\u0100","\u017F");ve.LatinExtendedB=Gt.CharacterRange.Define("\u0180","\u024F");ve.Greek=Gt.CharacterRange.Define("\u0370","\u03FF",new Me.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));ve.Cyrillic=Gt.CharacterRange.Define("\u0400","\u04FF",new Me.CharacterSet().AddRange("\u0482","\u0489"));ve.Armenian=Gt.CharacterRange.Define("\u0530","\u058F",new Me.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));ve.Hebrew=Gt.CharacterRange.Define("\u0590","\u05FF",new Me.CharacterSet);ve.Arabic=Gt.CharacterRange.Define("\u0600","\u06FF",new Me.CharacterSet);ve.Korean=Gt.CharacterRange.Define("\uAC00","\uD7AF",new Me.CharacterSet);ve.Latin1Supplement=Gt.CharacterRange.Define("\x80","\xFF",new Me.CharacterSet);ve.Chinese=Gt.CharacterRange.Define("\u4E00","\u9FFF",new Me.CharacterSet);ve.ListAllCharacterRanges=()=>[ve.LatinBasic,ve.LatinExtendedA,ve.LatinExtendedB,ve.Arabic,ve.Armenian,ve.Cyrillic,ve.Greek,ve.Hebrew,ve.Korean,ve.Latin1Supplement,ve.Chinese];});var dC=w(ll=>{Object.defineProperty(ll,"__esModule",{value:true});ll.GenerateStoryStats=void 0;var kN=ai(),RN=ci(),$N=Ss(),VN=kf(),jN=qf(),LN=qn();function qN(n){let e=n.FindAll(LN.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(VN.Knot)(),i=n.FindAll(jN.Stitch)(),a=n.FindAll(kN.Choice)(),s=n.FindAll($N.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(RN.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}}ll.GenerateStoryStats=qN;});var fC=w(cl=>{Object.defineProperty(cl,"__esModule",{value:true});cl.JsonFileHandler=void 0;var vp=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}.`)};}};cl.JsonFileHandler=vp;});var mC=w(tt=>{Object.defineProperty(tt,"__esModule",{value:true});tt.Compiler=tt.Story=tt.InkList=tt.JsonFileHandler=tt.StatementLevel=tt.InkParser=tt.CompilerOptions=void 0;var BN=td(),MN=Ev(),Cp=dr(),WN=yp(),GN=Oe(),HN=fe(),JN=dC(),zN=td();Object.defineProperty(tt,"CompilerOptions",{enumerable:true,get:function(){return zN.CompilerOptions}});var UN=yp();Object.defineProperty(tt,"InkParser",{enumerable:true,get:function(){return UN.InkParser}});var KN=jf();Object.defineProperty(tt,"StatementLevel",{enumerable:true,get:function(){return KN.StatementLevel}});var XN=fC();Object.defineProperty(tt,"JsonFileHandler",{enumerable:true,get:function(){return XN.JsonFileHandler}});var pC=Fs();Object.defineProperty(tt,"InkList",{enumerable:true,get:function(){return pC.InkList}});Object.defineProperty(tt,"Story",{enumerable:true,get:function(){return pC.Story}});var bp=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 WN.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, HN.asOrNull)(i,GN.StringValue);if(a!==null){let s=new MN.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, JN.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 Cp.ErrorType.Author:this._authorMessages.push(r);break;case Cp.ErrorType.Warning:this._warnings.push(r);break;case Cp.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new BN.CompilerOptions;}};tt.Compiler=bp;});var $C=w((xB,Tp)=>{var Cl=process||{},kC=Cl.argv||[],vl=Cl.env||{},jF=!(vl.NO_COLOR||kC.includes("--no-color"))&&(!!vl.FORCE_COLOR||kC.includes("--color")||Cl.platform==="win32"||(Cl.stdout||{}).isTTY&&vl.TERM!=="dumb"||!!vl.CI),LF=(n,e,t=n)=>r=>{let i=""+r,a=i.indexOf(e,n.length);return ~a?n+qF(i,e,t,a)+e:n+i+e},qF=(n,e,t,r)=>{let i="",a=0;do i+=n.substring(a,r)+t,a=r+e.length,r=n.indexOf(e,a);while(~r);return i+n.substring(a)},RC=(n=jF)=>{let e=n?LF:()=>String;return {isColorSupported:n,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};Tp.exports=RC();Tp.exports.createColors=RC;});var zs=w((VB,QC)=>{var UC="[^\\\\/]",qI="(?=.)",KC="[^/]",Ip="(?:\\/|$)",XC="(?:^|\\/)",kp=`\\.{1,2}${Ip}`,BI="(?!\\.)",MI=`(?!${XC}${kp})`,WI=`(?!\\.{0,1}${Ip})`,GI=`(?!${kp})`,HI="[^.\\/]",JI=`${KC}*?`,zI="/",YC={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:qI,QMARK:KC,END_ANCHOR:Ip,DOTS_SLASH:kp,NO_DOT:BI,NO_DOTS:MI,NO_DOT_SLASH:WI,NO_DOTS_SLASH:GI,QMARK_NO_DOT:HI,STAR:JI,START_ANCHOR:XC,SEP:zI},UI={...YC,SLASH_LITERAL:"[\\\\/]",QMARK:UC,STAR:`${UC}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},KI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};QC.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:KI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(n){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===true?UI:YC}};});var Us=w(Et=>{var{REGEX_BACKSLASH:XI,REGEX_REMOVE_BACKSLASH:YI,REGEX_SPECIAL_CHARS:QI,REGEX_SPECIAL_CHARS_GLOBAL:ZI}=zs();Et.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Et.hasRegexChars=n=>QI.test(n);Et.isRegexChar=n=>n.length===1&&Et.hasRegexChars(n);Et.escapeRegex=n=>n.replace(ZI,"\\$1");Et.toPosixSlashes=n=>n.replace(XI,"/");Et.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let n=navigator.platform.toLowerCase();return n==="win32"||n==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Et.removeBackslashes=n=>n.replace(YI,e=>e==="\\"?"":e);Et.escapeLast=(n,e,t)=>{let r=n.lastIndexOf(e,t);return r===-1?n:n[r-1]==="\\"?Et.escapeLast(n,e,r-1):`${n.slice(0,r)}\\${n.slice(r)}`};Et.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Et.wrapOutput=(n,e={},t={})=>{let r=t.contains?"":"^",i=t.contains?"":"$",a=`${r}(?:${n})${i}`;return e.negated===true&&(a=`(?:^(?!${a}).*$)`),a};Et.basename=(n,{windows:e}={})=>{let t=n.split(e?/[\\/]/:"/"),r=t[t.length-1];return r===""?t[t.length-2]:r};});var ab=w((LB,sb)=>{var ZC=Us(),{CHAR_ASTERISK:Rp,CHAR_AT:ek,CHAR_BACKWARD_SLASH:Ks,CHAR_COMMA:tk,CHAR_DOT:$p,CHAR_EXCLAMATION_MARK:Vp,CHAR_FORWARD_SLASH:ib,CHAR_LEFT_CURLY_BRACE:jp,CHAR_LEFT_PARENTHESES:Lp,CHAR_LEFT_SQUARE_BRACKET:nk,CHAR_PLUS:rk,CHAR_QUESTION_MARK:eb,CHAR_RIGHT_CURLY_BRACE:ik,CHAR_RIGHT_PARENTHESES:tb,CHAR_RIGHT_SQUARE_BRACKET:sk}=zs(),nb=n=>n===ib||n===Ks,rb=n=>{n.isPrefix!==true&&(n.depth=n.isGlobstar?1/0:1);},ak=(n,e)=>{let t=e||{},r=n.length-1,i=t.parts===true||t.scanToEnd===true,a=[],s=[],o=[],u=n,l=-1,c=0,h=0,d=false,g=false,f=false,m=false,b=false,_=false,y=false,p=false,v=false,C=false,S=0,D,O,A={value:"",depth:0,isGlob:false},E=()=>l>=r,F=()=>u.charCodeAt(l+1),R=()=>(D=O,u.charCodeAt(++l));for(;l<r;){O=R();let j;if(O===Ks){y=A.backslashes=true,O=R(),O===jp&&(_=true);continue}if(_===true||O===jp){for(S++;E()!==true&&(O=R());){if(O===Ks){y=A.backslashes=true,R();continue}if(O===jp){S++;continue}if(_!==true&&O===$p&&(O=R())===$p){if(d=A.isBrace=true,f=A.isGlob=true,C=true,i===true)continue;break}if(_!==true&&O===tk){if(d=A.isBrace=true,f=A.isGlob=true,C=true,i===true)continue;break}if(O===ik&&(S--,S===0)){_=false,d=A.isBrace=true,C=true;break}}if(i===true)continue;break}if(O===ib){if(a.push(l),s.push(A),A={value:"",depth:0,isGlob:false},C===true)continue;if(D===$p&&l===c+1){c+=2;continue}h=l+1;continue}if(t.noext!==true&&(O===rk||O===ek||O===Rp||O===eb||O===Vp)===true&&F()===Lp){if(f=A.isGlob=true,m=A.isExtglob=true,C=true,O===Vp&&l===c&&(v=true),i===true){for(;E()!==true&&(O=R());){if(O===Ks){y=A.backslashes=true,O=R();continue}if(O===tb){f=A.isGlob=true,C=true;break}}continue}break}if(O===Rp){if(D===Rp&&(b=A.isGlobstar=true),f=A.isGlob=true,C=true,i===true)continue;break}if(O===eb){if(f=A.isGlob=true,C=true,i===true)continue;break}if(O===nk){for(;E()!==true&&(j=R());){if(j===Ks){y=A.backslashes=true,R();continue}if(j===sk){g=A.isBracket=true,f=A.isGlob=true,C=true;break}}if(i===true)continue;break}if(t.nonegate!==true&&O===Vp&&l===c){p=A.negated=true,c++;continue}if(t.noparen!==true&&O===Lp){if(f=A.isGlob=true,i===true){for(;E()!==true&&(O=R());){if(O===Lp){y=A.backslashes=true,O=R();continue}if(O===tb){C=true;break}}continue}break}if(f===true){if(C=true,i===true)continue;break}}t.noext===true&&(m=false,f=false);let k=u,x="",P="";c>0&&(x=u.slice(0,c),u=u.slice(c),h-=c),k&&f===true&&h>0?(k=u.slice(0,h),P=u.slice(h)):f===true?(k="",P=u):k=u,k&&k!==""&&k!=="/"&&k!==u&&nb(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),t.unescape===true&&(P&&(P=ZC.removeBackslashes(P)),k&&y===true&&(k=ZC.removeBackslashes(k)));let Ce={prefix:x,input:n,start:c,base:k,glob:P,isBrace:d,isBracket:g,isGlob:f,isExtglob:m,isGlobstar:b,negated:p,negatedExtglob:v};if(t.tokens===true&&(Ce.maxDepth=0,nb(O)||s.push(A),Ce.tokens=s),t.parts===true||t.tokens===true){let j;for(let X=0;X<a.length;X++){let ut=j?j+1:c,We=a[X],Jt=n.slice(ut,We);t.tokens&&(X===0&&c!==0?(s[X].isPrefix=true,s[X].value=x):s[X].value=Jt,rb(s[X]),Ce.maxDepth+=s[X].depth),(X!==0||Jt!=="")&&o.push(Jt),j=We;}if(j&&j+1<n.length){let X=n.slice(j+1);o.push(X),t.tokens&&(s[s.length-1].value=X,rb(s[s.length-1]),Ce.maxDepth+=s[s.length-1].depth);}Ce.slashes=a,Ce.parts=o;}return Ce};sb.exports=ak;});var cb=w((qB,lb)=>{var Xs=zs(),wt=Us(),{MAX_LENGTH:_l,POSIX_REGEX_SOURCE:ok,REGEX_NON_SPECIAL_CHARS:uk,REGEX_SPECIAL_CHARS_BACKREF:lk,REPLACEMENTS:ob}=Xs,ck=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t);}catch{return n.map(i=>wt.escapeRegex(i)).join("..")}return t},_i=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,ub=n=>{let e=[],t=0,r=0,i=0,a="",s=false;for(let o of n){if(s===true){a+=o,s=false;continue}if(o==="\\"){a+=o,s=true;continue}if(o==='"'){i=i===1?0:1,a+=o;continue}if(i===0){if(o==="[")t++;else if(o==="]"&&t>0)t--;else if(t===0){if(o==="(")r++;else if(o===")"&&r>0)r--;else if(o==="|"&&r===0){e.push(a),a="";continue}}}a+=o;}return e.push(a),e},hk=n=>{let e=false;for(let t of n){if(e===true){e=false;continue}if(t==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(t))return false}return true},Bp=n=>{let e=n.trim(),t=true;for(;t===true;)t=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=true);if(hk(e))return e.replace(/\\(.)/g,"$1")},dk=n=>{let e=n.map(Bp).filter(Boolean);for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++){let i=e[t],a=e[r],s=i[0];if(!(!s||i!==s.repeat(i.length)||a!==s.repeat(a.length))&&(i===a||i.startsWith(a)||a.startsWith(i)))return true}return false},qp=(n,e=true)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,r=0,i=0,a=false;for(let s=1;s<n.length;s++){let o=n[s];if(a===true){a=false;continue}if(o==="\\"){a=true;continue}if(o==='"'){i=i===1?0:1;continue}if(i!==1){if(o==="["){t++;continue}if(o==="]"&&t>0){t--;continue}if(!(t>0)){if(o==="("){r++;continue}if(o===")"&&(r--,r===0))return e===true&&s!==n.length-1?void 0:{type:n[0],body:n.slice(2,s),end:s}}}}},fk=n=>`${n.length===1?wt.escapeRegex(n[0]):`[${n.map(t=>wt.escapeRegex(t)).join("")}]`}*`,pk=n=>{let e=0,t=[];for(;e<n.length;){let r=qp(n.slice(e),false);if(!r||r.type!=="*")return;let i=ub(r.body).map(s=>s.trim());if(i.length!==1)return;let a=Bp(i[0]);if(!a||a.length!==1)return;t.push(a),e+=r.end+1;}if(!(t.length<1))return t},mk=n=>{let e=0,t=n.trim(),r=qp(t);for(;r;)e++,t=r.body.trim(),r=qp(t);return e},gk=(n,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Xs.DEFAULT_MAX_EXTGLOB_RECURSION,r=ub(n).map(o=>o.trim());if(r.length>1&&(r.some(o=>o==="")||r.some(o=>/^[*?]+$/.test(o))||dk(r)))return {risky:true};let i=[],a=false,s=true;for(let o of r){let u=pk(o);if(u){a=true,i.push(...u);continue}let l=Bp(o);if(l&&l.length===1){i.push(l);continue}if(s=false,mk(o)>t)return {risky:true}}return a?s?{risky:true,safeOutput:fk([...new Set(i)])}:{risky:true}:{risky:false}},Mp=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=ob[n]||n;let t={...e},r=typeof t.maxLength=="number"?Math.min(_l,t.maxLength):_l,i=n.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let a={type:"bos",value:"",output:t.prepend||""},s=[a],o=t.capture?"":"?:",u=Xs.globChars(t.windows),l=Xs.extglobChars(u),{DOT_LITERAL:c,PLUS_LITERAL:h,SLASH_LITERAL:d,ONE_CHAR:g,DOTS_SLASH:f,NO_DOT:m,NO_DOT_SLASH:b,NO_DOTS_SLASH:_,QMARK:y,QMARK_NO_DOT:p,STAR:v,START_ANCHOR:C}=u,S=N=>`(${o}(?:(?!${C}${N.dot?f:c}).)*?)`,D=t.dot?"":m,O=t.dot?y:p,A=t.bash===true?S(t):v;t.capture&&(A=`(${A})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let E={input:n,index:-1,start:0,dot:t.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:s};n=wt.removePrefix(n,E),i=n.length;let F=[],R=[],k=[],x=a,P,Ce=()=>E.index===i-1,j=E.peek=(N=1)=>n[E.index+N],X=E.advance=()=>n[++E.index]||"",ut=()=>n.slice(E.index+1),We=(N="",W=0)=>{E.consumed+=N,E.index+=W;},Jt=N=>{E.output+=N.output!=null?N.output:N.value,We(N.value);},Qs=()=>{let N=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)X(),E.start++,N++;return N%2===0?false:(E.negated=true,E.start++,true)},Pr=N=>{E[N]++,k.push(N);},zt=N=>{E[N]--,k.pop();},J=N=>{if(x.type==="globstar"){let W=E.braces>0&&(N.type==="comma"||N.type==="brace"),I=N.extglob===true||F.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!W&&!I&&(E.output=E.output.slice(0,-x.output.length),x.type="star",x.value="*",x.output=A,E.output+=x.output);}if(F.length&&N.type!=="paren"&&(F[F.length-1].inner+=N.value),(N.value||N.output)&&Jt(N),x&&x.type==="text"&&N.type==="text"){x.output=(x.output||x.value)+N.value,x.value+=N.value;return}N.prev=x,s.push(N),x=N;},pe=(N,W)=>{let I={...l[W],conditions:1,inner:""};I.prev=x,I.parens=E.parens,I.output=E.output,I.startIndex=E.index,I.tokensIndex=s.length;let z=(t.capture?"(":"")+I.open;Pr("parens"),J({type:N,value:W,output:E.output?"":g}),J({type:"paren",extglob:true,value:X(),output:z}),F.push(I);},At=N=>{let W=n.slice(N.startIndex,E.index+1),I=n.slice(N.startIndex+2,E.index),z=gk(I,t);if((N.type==="plus"||N.type==="star")&&z.risky){let ge=z.safeOutput?(N.output?"":g)+(t.capture?`(${z.safeOutput})`:z.safeOutput):void 0,Ut=s[N.tokensIndex];Ut.type="text",Ut.value=W,Ut.output=ge||wt.escapeRegex(W);for(let Kt=N.tokensIndex+1;Kt<s.length;Kt++)s[Kt].value="",s[Kt].output="",delete s[Kt].suffix;E.output=N.output+Ut.output,E.backtrack=true,J({type:"paren",extglob:true,value:P,output:""}),zt("parens");return}let be=N.close+(t.capture?")":""),$e;if(N.type==="negate"){let ge=A;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(ge=S(t)),(ge!==A||Ce()||/^\)+$/.test(ut()))&&(be=N.close=`)$))${ge}`),N.inner.includes("*")&&($e=ut())&&/^\.[^\\/.]+$/.test($e)){let Ut=Mp($e,{...e,fastpaths:false}).output;be=N.close=`)${Ut})${ge})`;}N.prev.type==="bos"&&(E.negatedExtglob=true);}J({type:"paren",extglob:true,value:P,output:be}),zt("parens");};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(n)){let N=false,W=n.replace(lk,(I,z,be,$e,ge,Ut)=>$e==="\\"?(N=true,I):$e==="?"?z?z+$e+(ge?y.repeat(ge.length):""):Ut===0?O+(ge?y.repeat(ge.length):""):y.repeat(be.length):$e==="."?c.repeat(be.length):$e==="*"?z?z+$e+(ge?A:""):A:z?I:`\\${I}`);return N===true&&(t.unescape===true?W=W.replace(/\\/g,""):W=W.replace(/\\+/g,I=>I.length%2===0?"\\\\":I?"\\":"")),W===n&&t.contains===true?(E.output=n,E):(E.output=wt.wrapOutput(W,E,e),E)}for(;!Ce();){if(P=X(),P==="\0")continue;if(P==="\\"){let I=j();if(I==="/"&&t.bash!==true||I==="."||I===";")continue;if(!I){P+="\\",J({type:"text",value:P});continue}let z=/^\\+/.exec(ut()),be=0;if(z&&z[0].length>2&&(be=z[0].length,E.index+=be,be%2!==0&&(P+="\\")),t.unescape===true?P=X():P+=X(),E.brackets===0){J({type:"text",value:P});continue}}if(E.brackets>0&&(P!=="]"||x.value==="["||x.value==="[^")){if(t.posix!==false&&P===":"){let I=x.value.slice(1);if(I.includes("[")&&(x.posix=true,I.includes(":"))){let z=x.value.lastIndexOf("["),be=x.value.slice(0,z),$e=x.value.slice(z+2),ge=ok[$e];if(ge){x.value=be+ge,E.backtrack=true,X(),!a.output&&s.indexOf(x)===1&&(a.output=g);continue}}}(P==="["&&j()!==":"||P==="-"&&j()==="]")&&(P=`\\${P}`),P==="]"&&(x.value==="["||x.value==="[^")&&(P=`\\${P}`),t.posix===true&&P==="!"&&x.value==="["&&(P="^"),x.value+=P,Jt({value:P});continue}if(E.quotes===1&&P!=='"'){P=wt.escapeRegex(P),x.value+=P,Jt({value:P});continue}if(P==='"'){E.quotes=E.quotes===1?0:1,t.keepQuotes===true&&J({type:"text",value:P});continue}if(P==="("){Pr("parens"),J({type:"paren",value:P});continue}if(P===")"){if(E.parens===0&&t.strictBrackets===true)throw new SyntaxError(_i("opening","("));let I=F[F.length-1];if(I&&E.parens===I.parens+1){At(F.pop());continue}J({type:"paren",value:P,output:E.parens?")":"\\)"}),zt("parens");continue}if(P==="["){if(t.nobracket===true||!ut().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true)throw new SyntaxError(_i("closing","]"));P=`\\${P}`;}else Pr("brackets");J({type:"bracket",value:P});continue}if(P==="]"){if(t.nobracket===true||x&&x.type==="bracket"&&x.value.length===1){J({type:"text",value:P,output:`\\${P}`});continue}if(E.brackets===0){if(t.strictBrackets===true)throw new SyntaxError(_i("opening","["));J({type:"text",value:P,output:`\\${P}`});continue}zt("brackets");let I=x.value.slice(1);if(x.posix!==true&&I[0]==="^"&&!I.includes("/")&&(P=`/${P}`),x.value+=P,Jt({value:P}),t.literalBrackets===false||wt.hasRegexChars(I))continue;let z=wt.escapeRegex(x.value);if(E.output=E.output.slice(0,-x.value.length),t.literalBrackets===true){E.output+=z,x.value=z;continue}x.value=`(${o}${z}|${x.value})`,E.output+=x.value;continue}if(P==="{"&&t.nobrace!==true){Pr("braces");let I={type:"brace",value:P,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};R.push(I),J(I);continue}if(P==="}"){let I=R[R.length-1];if(t.nobrace===true||!I){J({type:"text",value:P,output:P});continue}let z=")";if(I.dots===true){let be=s.slice(),$e=[];for(let ge=be.length-1;ge>=0&&(s.pop(),be[ge].type!=="brace");ge--)be[ge].type!=="dots"&&$e.unshift(be[ge].value);z=ck($e,t),E.backtrack=true;}if(I.comma!==true&&I.dots!==true){let be=E.output.slice(0,I.outputIndex),$e=E.tokens.slice(I.tokensIndex);I.value=I.output="\\{",P=z="\\}",E.output=be;for(let ge of $e)E.output+=ge.output||ge.value;}J({type:"brace",value:P,output:z}),zt("braces"),R.pop();continue}if(P==="|"){F.length>0&&F[F.length-1].conditions++,J({type:"text",value:P});continue}if(P===","){let I=P,z=R[R.length-1];z&&k[k.length-1]==="braces"&&(z.comma=true,I="|"),J({type:"comma",value:P,output:I});continue}if(P==="/"){if(x.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",s.pop(),x=a;continue}J({type:"slash",value:P,output:d});continue}if(P==="."){if(E.braces>0&&x.type==="dot"){x.value==="."&&(x.output=c);let I=R[R.length-1];x.type="dots",x.output+=P,x.value+=P,I.dots=true;continue}if(E.braces+E.parens===0&&x.type!=="bos"&&x.type!=="slash"){J({type:"text",value:P,output:c});continue}J({type:"dot",value:P,output:c});continue}if(P==="?"){if(!(x&&x.value==="(")&&t.noextglob!==true&&j()==="("&&j(2)!=="?"){pe("qmark",P);continue}if(x&&x.type==="paren"){let z=j(),be=P;(x.value==="("&&!/[!=<:]/.test(z)||z==="<"&&!/<([!=]|\w+>)/.test(ut()))&&(be=`\\${P}`),J({type:"text",value:P,output:be});continue}if(t.dot!==true&&(x.type==="slash"||x.type==="bos")){J({type:"qmark",value:P,output:p});continue}J({type:"qmark",value:P,output:y});continue}if(P==="!"){if(t.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){pe("negate",P);continue}if(t.nonegate!==true&&E.index===0){Qs();continue}}if(P==="+"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){pe("plus",P);continue}if(x&&x.value==="("||t.regex===false){J({type:"plus",value:P,output:h});continue}if(x&&(x.type==="bracket"||x.type==="paren"||x.type==="brace")||E.parens>0){J({type:"plus",value:P});continue}J({type:"plus",value:h});continue}if(P==="@"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){J({type:"at",extglob:true,value:P,output:""});continue}J({type:"text",value:P});continue}if(P!=="*"){(P==="$"||P==="^")&&(P=`\\${P}`);let I=uk.exec(ut());I&&(P+=I[0],E.index+=I[0].length),J({type:"text",value:P});continue}if(x&&(x.type==="globstar"||x.star===true)){x.type="star",x.star=true,x.value+=P,x.output=A,E.backtrack=true,E.globstar=true,We(P);continue}let N=ut();if(t.noextglob!==true&&/^\([^?]/.test(N)){pe("star",P);continue}if(x.type==="star"){if(t.noglobstar===true){We(P);continue}let I=x.prev,z=I.prev,be=I.type==="slash"||I.type==="bos",$e=z&&(z.type==="star"||z.type==="globstar");if(t.bash===true&&(!be||N[0]&&N[0]!=="/")){J({type:"star",value:P,output:""});continue}let ge=E.braces>0&&(I.type==="comma"||I.type==="brace"),Ut=F.length&&(I.type==="pipe"||I.type==="paren");if(!be&&I.type!=="paren"&&!ge&&!Ut){J({type:"star",value:P,output:""});continue}for(;N.slice(0,3)==="/**";){let Kt=n[E.index+4];if(Kt&&Kt!=="/")break;N=N.slice(3),We("/**",3);}if(I.type==="bos"&&Ce()){x.type="globstar",x.value+=P,x.output=S(t),E.output=x.output,E.globstar=true,We(P);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&!$e&&Ce()){E.output=E.output.slice(0,-(I.output+x.output).length),I.output=`(?:${I.output}`,x.type="globstar",x.output=S(t)+(t.strictSlashes?")":"|$)"),x.value+=P,E.globstar=true,E.output+=I.output+x.output,We(P);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&N[0]==="/"){let Kt=N[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(I.output+x.output).length),I.output=`(?:${I.output}`,x.type="globstar",x.output=`${S(t)}${d}|${d}${Kt})`,x.value+=P,E.output+=I.output+x.output,E.globstar=true,We(P+X()),J({type:"slash",value:"/",output:""});continue}if(I.type==="bos"&&N[0]==="/"){x.type="globstar",x.value+=P,x.output=`(?:^|${d}|${S(t)}${d})`,E.output=x.output,E.globstar=true,We(P+X()),J({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-x.output.length),x.type="globstar",x.output=S(t),x.value+=P,E.output+=x.output,E.globstar=true,We(P);continue}let W={type:"star",value:P,output:A};if(t.bash===true){W.output=".*?",(x.type==="bos"||x.type==="slash")&&(W.output=D+W.output),J(W);continue}if(x&&(x.type==="bracket"||x.type==="paren")&&t.regex===true){W.output=P,J(W);continue}(E.index===E.start||x.type==="slash"||x.type==="dot")&&(x.type==="dot"?(E.output+=b,x.output+=b):t.dot===true?(E.output+=_,x.output+=_):(E.output+=D,x.output+=D),j()!=="*"&&(E.output+=g,x.output+=g)),J(W);}for(;E.brackets>0;){if(t.strictBrackets===true)throw new SyntaxError(_i("closing","]"));E.output=wt.escapeLast(E.output,"["),zt("brackets");}for(;E.parens>0;){if(t.strictBrackets===true)throw new SyntaxError(_i("closing",")"));E.output=wt.escapeLast(E.output,"("),zt("parens");}for(;E.braces>0;){if(t.strictBrackets===true)throw new SyntaxError(_i("closing","}"));E.output=wt.escapeLast(E.output,"{"),zt("braces");}if(t.strictSlashes!==true&&(x.type==="star"||x.type==="bracket")&&J({type:"maybe_slash",value:"",output:`${d}?`}),E.backtrack===true){E.output="";for(let N of E.tokens)E.output+=N.output!=null?N.output:N.value,N.suffix&&(E.output+=N.suffix);}return E};Mp.fastpaths=(n,e)=>{let t={...e},r=typeof t.maxLength=="number"?Math.min(_l,t.maxLength):_l,i=n.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);n=ob[n]||n;let{DOT_LITERAL:a,SLASH_LITERAL:s,ONE_CHAR:o,DOTS_SLASH:u,NO_DOT:l,NO_DOTS:c,NO_DOTS_SLASH:h,STAR:d,START_ANCHOR:g}=Xs.globChars(t.windows),f=t.dot?c:l,m=t.dot?h:l,b=t.capture?"":"?:",_={negated:false,prefix:""},y=t.bash===true?".*?":d;t.capture&&(y=`(${y})`);let p=D=>D.noglobstar===true?y:`(${b}(?:(?!${g}${D.dot?u:a}).)*?)`,v=D=>{switch(D){case "*":return `${f}${o}${y}`;case ".*":return `${a}${o}${y}`;case "*.*":return `${f}${y}${a}${o}${y}`;case "*/*":return `${f}${y}${s}${o}${m}${y}`;case "**":return f+p(t);case "**/*":return `(?:${f}${p(t)}${s})?${m}${o}${y}`;case "**/*.*":return `(?:${f}${p(t)}${s})?${m}${y}${a}${o}${y}`;case "**/.*":return `(?:${f}${p(t)}${s})?${a}${o}${y}`;default:{let O=/^(.*?)\.(\w+)$/.exec(D);if(!O)return;let A=v(O[1]);return A?A+a+O[2]:void 0}}},C=wt.removePrefix(n,_),S=v(C);return S&&t.strictSlashes!==true&&(S+=`${s}?`),S};lb.exports=Mp;});var fb=w((BB,db)=>{var yk=ab(),Wp=cb(),hb=Us(),vk=zs(),Ck=n=>n&&typeof n=="object"&&!Array.isArray(n),Ie=(n,e,t=false)=>{if(Array.isArray(n)){let c=n.map(d=>Ie(d,e,t));return d=>{for(let g of c){let f=g(d);if(f)return f}return false}}let r=Ck(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},a=i.windows,s=r?Ie.compileRe(n,e):Ie.makeRe(n,e,false,true),o=s.state;delete s.state;let u=()=>false;if(i.ignore){let c={...e,ignore:null,onMatch:null,onResult:null};u=Ie(i.ignore,c,t);}let l=(c,h=false)=>{let{isMatch:d,match:g,output:f}=Ie.test(c,s,e,{glob:n,posix:a}),m={glob:n,state:o,regex:s,posix:a,input:c,output:f,match:g,isMatch:d};return typeof i.onResult=="function"&&i.onResult(m),d===false?(m.isMatch=false,h?m:false):u(c)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=false,h?m:false):(typeof i.onMatch=="function"&&i.onMatch(m),h?m:true)};return t&&(l.state=o),l};Ie.test=(n,e,t,{glob:r,posix:i}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return {isMatch:false,output:""};let a=t||{},s=a.format||(i?hb.toPosixSlashes:null),o=n===r,u=o&&s?s(n):n;return o===false&&(u=s?s(n):n,o=u===r),(o===false||a.capture===true)&&(a.matchBase===true||a.basename===true?o=Ie.matchBase(n,e,t,i):o=e.exec(u)),{isMatch:!!o,match:o,output:u}};Ie.matchBase=(n,e,t,r=t&&t.windows)=>(e instanceof RegExp?e:Ie.makeRe(e,t)).test(hb.basename(n,{windows:r}));Ie.isMatch=(n,e,t)=>Ie(e,t)(n);Ie.parse=(n,e)=>Array.isArray(n)?n.map(t=>Ie.parse(t,e)):Wp(n,{...e,fastpaths:false});Ie.scan=(n,e)=>yk(n,e);Ie.compileRe=(n,e,t=false,r=false)=>{if(t===true)return n.output;let i=e||{},a=i.contains?"":"^",s=i.contains?"":"$",o=`${a}(?:${n.output})${s}`;n&&n.negated===true&&(o=`^(?!${o}).*$`);let u=Ie.toRegex(o,e);return r===true&&(u.state=n),u};Ie.makeRe=(n,e={},t=false,r=false)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return e.fastpaths!==false&&(n[0]==="."||n[0]==="*")&&(i.output=Wp.fastpaths(n,e)),i.output||(i=Wp(n,e)),Ie.compileRe(i,e,t,r)};Ie.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===true)throw t;return /$^/}};Ie.constants=vk;db.exports=Ie;});var yb=w((MB,gb)=>{var pb=fb(),bk=Us();function mb(n,e,t=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:bk.isWindows()}),pb(n,e,t)}Object.assign(mb,pb);gb.exports=mb;});var wi="/__pixi-vn-ink/hashtag-commands",Zs="/__pixi-vn-ink/text-replaces",wl="/__pixi-vn-ink/info";var ea="global decl",Kn="___external_value___";var ae;(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)))(ae||={});var Bb=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Mb=/[\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]/,Wb=/[\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]/,Al={Space_Separator:Bb,ID_Start:Mb,ID_Continue:Wb},Ne={isSpaceSeparator(n){return typeof n=="string"&&Al.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||Al.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"||Al.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)}},xl,nt,fn,na,An,jt,je,Tl,Di,Gb=function(e,t){xl=String(e),nt="start",fn=[],na=0,An=1,jt=0,je=void 0,Tl=void 0,Di=void 0;do je=Hb(),Ub[nt]();while(je.type!=="eof");return typeof t=="function"?Pl({"":Di},"",t):Di};function Pl(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=Pl(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=Pl(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 H,B,Ai,dn,ee;function Hb(){for(H="default",B="",Ai=false,dn=1;;){ee=pn();let n=Qp[H]();if(n)return n}}function pn(){if(xl[na])return String.fromCodePoint(xl.codePointAt(na))}function T(){let n=pn();return n===`
52
- `?(An++,jt=0):n?jt+=n.length:jt++,n&&(na+=n.length),n}var Qp={default(){switch(ee){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
- `:case "\r":case "\u2028":case "\u2029":T();return;case "/":T(),H="comment";return;case void 0:return T(),_e("eof")}if(Ne.isSpaceSeparator(ee)){T();return}return Qp[nt]()},comment(){switch(ee){case "*":T(),H="multiLineComment";return;case "/":T(),H="singleLineComment";return}throw Se(T())},multiLineComment(){switch(ee){case "*":T(),H="multiLineCommentAsterisk";return;case void 0:throw Se(T())}T();},multiLineCommentAsterisk(){switch(ee){case "*":T();return;case "/":T(),H="default";return;case void 0:throw Se(T())}T(),H="multiLineComment";},singleLineComment(){switch(ee){case `
54
- `:case "\r":case "\u2028":case "\u2029":T(),H="default";return;case void 0:return T(),_e("eof")}T();},value(){switch(ee){case "{":case "[":return _e("punctuator",T());case "n":return T(),Xn("ull"),_e("null",null);case "t":return T(),Xn("rue"),_e("boolean",true);case "f":return T(),Xn("alse"),_e("boolean",false);case "-":case "+":T()==="-"&&(dn=-1),H="sign";return;case ".":B=T(),H="decimalPointLeading";return;case "0":B=T(),H="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":B=T(),H="decimalInteger";return;case "I":return T(),Xn("nfinity"),_e("numeric",1/0);case "N":return T(),Xn("aN"),_e("numeric",NaN);case '"':case "'":Ai=T()==='"',B="",H="string";return}throw Se(T())},identifierNameStartEscape(){if(ee!=="u")throw Se(T());T();let n=Ol();switch(n){case "$":case "_":break;default:if(!Ne.isIdStartChar(n))throw Yp();break}B+=n,H="identifierName";},identifierName(){switch(ee){case "$":case "_":case "\u200C":case "\u200D":B+=T();return;case "\\":T(),H="identifierNameEscape";return}if(Ne.isIdContinueChar(ee)){B+=T();return}return _e("identifier",B)},identifierNameEscape(){if(ee!=="u")throw Se(T());T();let n=Ol();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!Ne.isIdContinueChar(n))throw Yp();break}B+=n,H="identifierName";},sign(){switch(ee){case ".":B=T(),H="decimalPointLeading";return;case "0":B=T(),H="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":B=T(),H="decimalInteger";return;case "I":return T(),Xn("nfinity"),_e("numeric",dn*(1/0));case "N":return T(),Xn("aN"),_e("numeric",NaN)}throw Se(T())},zero(){switch(ee){case ".":B+=T(),H="decimalPoint";return;case "e":case "E":B+=T(),H="decimalExponent";return;case "x":case "X":B+=T(),H="hexadecimal";return}return _e("numeric",dn*0)},decimalInteger(){switch(ee){case ".":B+=T(),H="decimalPoint";return;case "e":case "E":B+=T(),H="decimalExponent";return}if(Ne.isDigit(ee)){B+=T();return}return _e("numeric",dn*Number(B))},decimalPointLeading(){if(Ne.isDigit(ee)){B+=T(),H="decimalFraction";return}throw Se(T())},decimalPoint(){switch(ee){case "e":case "E":B+=T(),H="decimalExponent";return}if(Ne.isDigit(ee)){B+=T(),H="decimalFraction";return}return _e("numeric",dn*Number(B))},decimalFraction(){switch(ee){case "e":case "E":B+=T(),H="decimalExponent";return}if(Ne.isDigit(ee)){B+=T();return}return _e("numeric",dn*Number(B))},decimalExponent(){switch(ee){case "+":case "-":B+=T(),H="decimalExponentSign";return}if(Ne.isDigit(ee)){B+=T(),H="decimalExponentInteger";return}throw Se(T())},decimalExponentSign(){if(Ne.isDigit(ee)){B+=T(),H="decimalExponentInteger";return}throw Se(T())},decimalExponentInteger(){if(Ne.isDigit(ee)){B+=T();return}return _e("numeric",dn*Number(B))},hexadecimal(){if(Ne.isHexDigit(ee)){B+=T(),H="hexadecimalInteger";return}throw Se(T())},hexadecimalInteger(){if(Ne.isHexDigit(ee)){B+=T();return}return _e("numeric",dn*Number(B))},string(){switch(ee){case "\\":T(),B+=Jb();return;case '"':if(Ai)return T(),_e("string",B);B+=T();return;case "'":if(!Ai)return T(),_e("string",B);B+=T();return;case `
55
- `:case "\r":throw Se(T());case "\u2028":case "\u2029":Kb(ee);break;case void 0:throw Se(T())}B+=T();},start(){switch(ee){case "{":case "[":return _e("punctuator",T())}H="value";},beforePropertyName(){switch(ee){case "$":case "_":B=T(),H="identifierName";return;case "\\":T(),H="identifierNameStartEscape";return;case "}":return _e("punctuator",T());case '"':case "'":Ai=T()==='"',H="string";return}if(Ne.isIdStartChar(ee)){B+=T(),H="identifierName";return}throw Se(T())},afterPropertyName(){if(ee===":")return _e("punctuator",T());throw Se(T())},beforePropertyValue(){H="value";},afterPropertyValue(){switch(ee){case ",":case "}":return _e("punctuator",T())}throw Se(T())},beforeArrayValue(){if(ee==="]")return _e("punctuator",T());H="value";},afterArrayValue(){switch(ee){case ",":case "]":return _e("punctuator",T())}throw Se(T())},end(){throw Se(T())}};function _e(n,e){return {type:n,value:e,line:An,column:jt}}function Xn(n){for(let e of n){if(pn()!==e)throw Se(T());T();}}function Jb(){switch(pn()){case "b":return T(),"\b";case "f":return T(),"\f";case "n":return T(),`
56
- `;case "r":return T(),"\r";case "t":return T()," ";case "v":return T(),"\v";case "0":if(T(),Ne.isDigit(pn()))throw Se(T());return "\0";case "x":return T(),zb();case "u":return T(),Ol();case `
57
- `:case "\u2028":case "\u2029":return T(),"";case "\r":return T(),pn()===`
58
- `&&T(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw Se(T());case void 0:throw Se(T())}return T()}function zb(){let n="",e=pn();if(!Ne.isHexDigit(e)||(n+=T(),e=pn(),!Ne.isHexDigit(e)))throw Se(T());return n+=T(),String.fromCodePoint(parseInt(n,16))}function Ol(){let n="",e=4;for(;e-- >0;){let t=pn();if(!Ne.isHexDigit(t))throw Se(T());n+=T();}return String.fromCodePoint(parseInt(n,16))}var Ub={start(){if(je.type==="eof")throw Yn();Dl();},beforePropertyName(){switch(je.type){case "identifier":case "string":Tl=je.value,nt="afterPropertyName";return;case "punctuator":ta();return;case "eof":throw Yn()}},afterPropertyName(){if(je.type==="eof")throw Yn();nt="beforePropertyValue";},beforePropertyValue(){if(je.type==="eof")throw Yn();Dl();},beforeArrayValue(){if(je.type==="eof")throw Yn();if(je.type==="punctuator"&&je.value==="]"){ta();return}Dl();},afterPropertyValue(){if(je.type==="eof")throw Yn();switch(je.value){case ",":nt="beforePropertyName";return;case "}":ta();}},afterArrayValue(){if(je.type==="eof")throw Yn();switch(je.value){case ",":nt="beforeArrayValue";return;case "]":ta();}},end(){}};function Dl(){let n;switch(je.type){case "punctuator":switch(je.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=je.value;break}if(Di===void 0)Di=n;else {let e=fn[fn.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,Tl,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")fn.push(n),Array.isArray(n)?nt="beforeArrayValue":nt="beforePropertyName";else {let e=fn[fn.length-1];e==null?nt="end":Array.isArray(e)?nt="afterArrayValue":nt="afterPropertyValue";}}function ta(){fn.pop();let n=fn[fn.length-1];n==null?nt="end":Array.isArray(n)?nt="afterArrayValue":nt="afterPropertyValue";}function Se(n){return ra(n===void 0?`JSON5: invalid end of input at ${An}:${jt}`:`JSON5: invalid character '${Zp(n)}' at ${An}:${jt}`)}function Yn(){return ra(`JSON5: invalid end of input at ${An}:${jt}`)}function Yp(){return jt-=5,ra(`JSON5: invalid identifier character at ${An}:${jt}`)}function Kb(n){console.warn(`JSON5: '${Zp(n)}' in strings is not valid ECMAScript; consider escaping`);}function Zp(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 ra(n){let e=new SyntaxError(n);return e.lineNumber=An,e.columnNumber=jt,e}var Xb=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 m of t){let b;typeof m=="string"?b=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(b=String(m)),b!==void 0&&s.indexOf(b)<0&&s.push(b);}}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(m,b){let _=b[m];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(m):typeof _.toJSON=="function"&&(_=_.toJSON(m))),o&&(_=o.call(b,m,_)),_ 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(_)?f(_):d(_)}function h(m){let b={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},y="";for(let v=0;v<m.length;v++){let C=m[v];switch(C){case "'":case '"':b[C]++,y+=C;continue;case "\0":if(Ne.isDigit(m[v+1])){y+="\\x00";continue}}if(_[C]){y+=_[C];continue}if(C<" "){let S=C.charCodeAt(0).toString(16);y+="\\x"+("00"+S).substring(S.length);continue}y+=C;}let p=l||Object.keys(b).reduce((v,C)=>b[v]<b[C]?v:C);return y=y.replace(new RegExp(p,"g"),_[p]),p+y+p}function d(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let b=a;a=a+u;let _=s||Object.keys(m),y=[];for(let v of _){let C=c(v,m);if(C!==void 0){let S=g(v)+":";u!==""&&(S+=" "),S+=C,y.push(S);}}let p;if(y.length===0)p="{}";else {let v;if(u==="")v=y.join(","),p="{"+v+"}";else {let C=`,
59
- `+a;v=y.join(C),p=`{
60
- `+a+v+`,
61
- `+b+"}";}}return i.pop(),a=b,p}function g(m){if(m.length===0)return h(m);let b=String.fromCodePoint(m.codePointAt(0));if(!Ne.isIdStartChar(b))return h(m);for(let _=b.length;_<m.length;_++)if(!Ne.isIdContinueChar(String.fromCodePoint(m.codePointAt(_))))return h(m);return m}function f(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let b=a;a=a+u;let _=[];for(let p=0;p<m.length;p++){let v=c(String(p),m);_.push(v!==void 0?v:"null");}let y;if(_.length===0)y="[]";else if(u==="")y="["+_.join(",")+"]";else {let p=`,
62
- `+a,v=_.join(p);y=`[
63
- `+a+v+`,
64
- `+b+"]";}return i.pop(),a=b,y}},Yb={parse:Gb,stringify:Xb},Qb=Yb,xi=Qb;var tm="\xA7SPACE\xA7",nm="\xA7DOUBLE_QUOTES\xA7",rm="\xA7QUOTES\xA7",im="SPECIAL_\xA7QUOTES\xA7",sm="\xA7CURLY_BRACKETS1\xA7",Zb="\xA7INK_VAR\xA7",am="\xA7CURLY_BRACKETS2\xA7",mn;(p=>{let n=[],e=[];async function t(v,C){for(let S=0;S<n.length;S++)try{let{validation:D}=n[S].opts;if(D instanceof RegExp){if(!D.test(v.join(" ")))continue}else if(D instanceof zod.ZodType&&!D.safeParse(v).success)continue;let O=await n[S].fn(v,C,h);if(O===!0||typeof O=="string")return O}catch{}return false}function r(v,C={name:"custom-command",validation:/^/}){n.unshift({fn:v,opts:C});}p.add=r;function i(){return [...e.map(v=>v.opts),...n.map(v=>v.opts)]}p.info=i;function a(v,C){e.unshift({fn:v,opts:C});}p.addMapper=a;function s(){n.length=0;}p.clear=s;function o(){e.length=0;}p.clearMappers=o;async function u(v,C,S){try{let D=l(v),O=await t(D,S);return O===!0?void 0:typeof O=="string"?(O.startsWith("#")&&(O=O.substring(1)),await p.run(O,C,S)):c(D,C)}catch(D){throw ae.error("Error parsing ink hashtag-command",v),D}}p.run=u;function l(v,C){if(v=v.replaceAll('\\"',nm),v=v.replaceAll("\\'",rm),v=v.replaceAll("\\`",im),v=v.replaceAll("\\{",sm),v=v.replaceAll("\\}",am),C?.mergeInkVariables){let A;do A=v,v=v.replace(/\{[^{}:]*\}/g,Zb);while(v!==A)}v=v.replaceAll("{"," { "),v=v.replaceAll("}"," } "),v=v.replaceAll(sm,"{"),v=v.replaceAll(am,"}");let S=[],D,O="";for(let A=0;A<v.length;A++){let E=v[A];E==='"'||E==="'"||E==="`"?D===void 0?(S.push(O),O="",D=E,O+=E):D===E?(D=void 0,O+=E,S.push(O),O=""):O+=E:O+=E;}return O!==""&&S.push(O),S.forEach((A,E)=>{E%2===1&&(S[E]=A.replaceAll(" ",tm));}),v=S.join(""),S=v.split(" ").filter(A=>A!==""),S=S.map(A=>A.replaceAll(tm," ").replaceAll(nm,'"').replaceAll(rm,"'").replaceAll(im,"`")),S=m(S),S=S.flatMap(A=>y(A)),S=S.map(A=>A.startsWith('"')&&A.endsWith('"')||A.startsWith("'")&&A.endsWith("'")||A.startsWith("`")&&A.endsWith("`")?A.slice(1,-1):A),S}p.convertTagTolist=l;function c(v,C,S){for(let D of e){let{validation:O}=D.opts,A=false;if(O instanceof RegExp?A=O.test(v.join(" ")):O instanceof zod.ZodType&&(A=O.safeParse(v).success),A)return D.fn(v,C)}S?.silent||ae.error("The operation is not valid",v);}p.convertOperation=c;function h(v){return d(v)}p.convertListStringToObj=h;function d(v){if(v.length===0)return {};if(v.length%2!==0)throw ae.error("The props list must have a pair number of elements",v),new Error("The props list must have a pair number of elements");let C="{";v.forEach((S,D)=>{if(D%2===0)C+=`"${S}": `;else {switch(S){case "null":case "undefined":case "true":case "false":C+=`${S}`;break;default:f(S)?(S=g(S),C+=`"${S}"`):S.startsWith("{")&&S.endsWith("}")?C+=`${S}`:S.startsWith('"')&&S.endsWith('"')?C+=`${S}`:Number.isNaN(parseFloat(S))?C+=`"${S}"`:C+=`${S}`;}D<v.length-1&&(C+=", ");}}),C+="}";try{return xi.parse(C)}catch(S){throw ae.error("Error parsing ink json",C),S}}function g(v){return v.startsWith('"')&&v.endsWith('"')||v.startsWith("'")&&v.endsWith("'")||v.startsWith("`")&&v.endsWith("`")?v.substring(1,v.length-1):v}function f(v){return !!(v.startsWith('"')&&v.endsWith('"')||v.startsWith("'")&&v.endsWith("'")||v.startsWith("`")&&v.endsWith("`"))}function m(v){return b(v).tokens}p.mergeJsonBlocks=m;function b(v){let C=[],S=false;for(let D=0;D<v.length;D++){let O=v[D];if(O!=="{"){C.push(O);continue}let A=_(v,D);if(A===-1){C.push(O);continue}let E=b(v.slice(D+1,A)),F=["{",...E.tokens,"}"],R=F.join(" ");if(!E.hasInvalidMatchedBlock)try{xi.parse(R),C.push(R),D=A;continue}catch{}S=true,C.push(...F),D=A;}return {tokens:C,hasInvalidMatchedBlock:S}}function _(v,C){let S=0;for(let D=C;D<v.length;D++)if(v[D]==="{")S++;else if(v[D]==="}"&&(S--,S===0))return D;return -1}function y(v){if(v==="["||v==="]")return [v];let C=0,S=v.length,D=[];for(;C<S&&v[C]==="[";)D.push("["),C++;let O=[];for(;S>C&&v[S-1]==="]";)O.unshift("]"),S--;let A=v.slice(C,S);return A===""?[...D,...O]:[...D,A,...O]}})(mn||={});var om=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],um=["+","-","/","*","%","POW","RANDOM","L^"],lm=["INT","FLOOR","FLOAT"];function Or(n,e){if(n.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(n)&&(n=n.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!n.startsWith(".")))return n.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(n)&&n.includes("g-")){let r=n.split("g-");return Nl(e)+"_|_"+"g-"+r[r.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(n);)t++,n=n.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(n)&&e){let r=n.substring(1);return Nl(e,t)+"_|_"+r.replaceAll(".","_|_")}return n.replaceAll(".","_|_")||Nl(e,t).replaceAll(".","_|_")}function Nl(n,e=0){let t=n.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var cm="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Xt(n){return n.startsWith("^")&&(n=n.substring(1)),n=n.replaceAll("\\\\",cm),n=n.replaceAll("\\n",`
65
- `),n=n.replaceAll("\\t"," "),n=n.replaceAll(" "," "),n=n.replaceAll(cm,"\\\\"),n}var e_={version:"1.14.0"};var ia=`https://pixi-vn.com/schemas/${e_.version}/schema.json`,hm=["==","!=","<","<=",">",">=","CONTAINS"];function Dn(n,e,t,r){let{functions:i}=r;n=n.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return n.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else ae.error("Error parsing ink file: Conditional statement is not valid",n);break;default:if(hm.includes(s))if(a.length<2)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(um.includes(s))if(a.length<2)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(lm.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Xt(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),u=o.pop(),l=o.pop();if(l===void 0||u===void 0){ae.error("Error parsing ink file: Conditional statement is not valid",n);return}let c=Number(l),h=o.join(".");if(h.includes("^.")){let g=h.split("."),f=g[g.length-1].replaceAll(".","_|_");g.pop(),h=`${g.join(".")}.${f}`,u.includes("c-")&&(h=h+"_|_"+u);}else h=h.replaceAll(".","_|_");let d=Or(h,e);if(!d)return;a.push({type:"compare",leftValue:Fl(d),operator:">=",rightValue:{type:"value",value:c}});}else {let o=Or(s["CNT?"],e);if(!o)return;a.push(Fl(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Qn({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],u=i.find(c=>c.name===o);if(!u){ae.error(`Error parsing ink file: Function ${o} is not defined`,n);return}let l=[];for(let c=0;c<u.args;c++)a.length!==0&&l.push(a.pop());a.push({type:"function",functionName:o,args:l.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(u=>u);a.push(o);}else a.push(s);}),a}function Il(n,e,t,r){return Dn(n,e,t,r)}function Qn(n,e,t){let{key:r,defaultType:i}=n,a=e.indexOf(r);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:r}}function Pi(n,e,t){let{key:r,value:i,defaultType:a,artmeticValue:s}=n,o=e.indexOf(r);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let u=Object.values(i.list).map(l=>l);return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:u}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(u=>(u.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(t.enums[r])}),Object.entries(t.enums[r]).forEach(([l,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${l}`,value:c});}),u),[]);{let u=new Set,l=Object.entries(i.list).reduce((c,[h,d])=>{let[g,f]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:f,value:d}),u.add(g),c},[]);return u.forEach(c=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),r in t.enums?Object.entries(t.enums[r]).forEach(([c,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${c}`,value:h});}):l.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(i.list)}),l}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[u,l]=i["VAR?"].split(".");if(u in t.enums&&l in t.enums[u])return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:t.enums[u][l]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:Qn({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}function Fl(n){return {type:"value",storageType:"label",storageOperationType:"get",label:n}}function kl(n,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(n)?"call":"jump"}function sa(n,e){if(e){if(typeof e=="string")e.startsWith("^")&&n.push(Xt(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:n.push(e);}}}function Rl(n,e,t,r,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:u=false}=a;return n_(n,e,t,r,i,{isNewLine:s,isHashtagScript:o,isThreads:u})}function n_(n,e,t,r,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:u}=a;if(o){if(Array.isArray(e)&&e.length>0){let l={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"){let h=e[0],d=mn.convertTagTolist(h),g=mn.convertOperation(d,l,{silent:!0});g&&(g.$origin=h,c.push(g));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),n.push({...l,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&!l.labelToOpen&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}typeof e=="string"?n.push(r_(Xt(e),r.characterIds)):n.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")n.push({end:"game_end"});else if(e==="done")n.push({end:"label_end",goNextStep:true});else if(e==="<>")if(n.length>0){let l=n[n.length-1];l.glueEnabled=true,l.labelToOpen||(l.goNextStep=!s),n[n.length-1]=l;}else n.push({glueEnabled:true,goNextStep:true});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Xt(e.value)),n.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":n.push({goNextStep:true,operations:[e]});break;default:if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}n.push({conditionalStep:e});}else if("->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let c=n[n.length-1];c.labelToOpen||(c.goNextStep=true),n[n.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)n.push({labelToOpen:{label:Qn({key:e["->"],defaultType:"storage"},i),type:u?"call":"jump",params:e.params},glueEnabled:l});else {let c=Or(e["->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:kl(c,u),params:e.params},glueEnabled:l});}}else if("->t->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let h=n[n.length-1];h.labelToOpen||(h.goNextStep=true),n[n.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=Or(e["->t->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:l});}}}function r_(n,e){let t;if(n.includes(": ")){let r=n.split(": "),i=r[0],a=r.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,n=a);}return t?{dialogue:{character:t,text:n}}:{dialogue:n}}function $l(n,e,t,r=true,i=false){return i_(n,e,t,r,i)}function i_(n,e,t,r,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?n.push(Xt(e)):n.push(e):typeof e=="object"&&"type"in e&&n.push(e));}function aa(n,e,t,r){if(n.length===0){ae.error("Error parsing ink file: Arithmetic statement is not valid",n);return}let i=Dn(n,e,t,r);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function Tr(n,e,t,r="",i,a,s=void 0){let o=[],u="sequential",l=false,c=true;n.forEach(g=>{g==="%"&&(u="loop"),g==="seq"&&(u="random"),g==="MIN"&&(l=true);});let h=n[n.length-1];return Object.keys(h).forEach(g=>{let f=h[g];if(Array.isArray(f)&&f.length>3){f=f.slice(1,f.length-2);let m=[];xn(f,r,i,m,e,e,t,Nr,s,true,a),m.length===1?o.push(m[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:m});}else Array.isArray(f)&&f.length===3&&(c=false);}),u==="sequential"?{type:"stepswitch",elements:o,choiceType:u,end:c?"lastItem":void 0,nestedId:s}:l&&u==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:u}}function xn(n,e,t,r=[],i,a,s,o,u=void 0,l=true,c=[]){let h=false,d=[],g=false,f=false,m=false,b=[],_=[];if(t.preDialog[e]&&(l=false,i(r,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),t.preDialog[e].glue&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),delete t.preDialog[e]),n.includes("visit")){let p=Tr(n,a,s,e,t,c,u);p&&(!l&&r.length>0&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}));return}let y=n[0];if(y&&typeof y=="object"&&"temp="in y){for(;n[0]&&typeof n[0]=="object"&&"temp="in n[0];)c.push(n[0]["temp="]),n.shift();c=c.reverse();}if(n.forEach((p,v)=>{if(f){if(typeof p=="string"&&p==="/#"){let C=[];xn(_,e,t,C,$l,$l,s,o,u,l),i(r,C,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),f=false,_=[];}else _.push(p);return}else if(h)if(Array.isArray(p))d.push(p);else if(p&&typeof p=="object")"CNT?"in p?v>0&&n[v-1]==="ev"?(g=true,b.push(p)):g?b.push(p):(d.push(p),l=false):"VAR="in p||"temp="in p?Pi({key:"VAR="in p?p["VAR="]:p["temp="],value:n[v-1],defaultType:"VAR="in p?"storage":"tempstorage"},c,t).forEach(S=>{if(S.value&&typeof S.value=="string"&&S.value==="/str"&&(S.value=n[v-2]),S.value&&typeof S.value=="object"&&"^->"in S.value&&(S.value=S.value["^->"]),d.length>1){let D=aa(d,e,c,t);d=[],D&&typeof D=="object"&&"type"in D&&D.type==="value"&&"storageType"in D&&D.storageType==="logic"&&(S.value=D.operation);}(typeof S.key!="string"||!S.key.includes("$r"))&&(i(r,S,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=true);}):"VAR?"in p?d.push(p):"^->"in p?p["^->"].includes("$r")||d.push(p):("f()"in p||"list"in p&&typeof p.list=="object")&&d.push(p);else switch(p){case "/ev":g&&b.push(p),h=false,d.push(p);break;case "out":if(d.length>0){let C=d[d.length-1];if(C&&typeof C=="object"&&"VAR?"in C){d.pop();let S=Qn({key:C["VAR?"],defaultType:"storage"},c);i(r,S,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m});}else {let S=[];for(;d.length>0&&d[d.length-1]!=="/ev";)S.push(d.pop());S=S.reverse();let D=aa(S,e,c,t);d=[],D&&typeof D=="object"&&"type"in D&&D.type==="value"&&"storageType"in D&&D.storageType==="logic"?i(r,{storageOperationType:"get",storageType:"logic",operation:D.operation,type:"value"},e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}):(i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),D=`^${D}`,i(r,D,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}));}l=false;}break;case "pop":{let C=d[d.length-1];if(C&&typeof C=="object"&&"f()"in C){let S=[];for(;d.length>0&&d[d.length-1]!=="/ev";)S.push(d.pop());S=S.reverse();let D=Dn(S,e,c,t);d=[],D.forEach(O=>{O&&typeof O=="object"&&"type"in O&&O.type==="function"?i(r,O,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}):ae.warn("Unhandled case: value is not a function",O);}),l=false;}else d.push(p);return}default:d.push(p);}else if(typeof p=="string")if(p.startsWith("^"))i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=false;else if(p==="ev")h=true;else if(p===`
66
- `)l=true;else if(p==="done"||p==="end")i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=false;else if(p==="<>")i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=false;else if(p==="nop"&&g){let C=dm(b,a,s,e,t,c,u);C&&i(r,C,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),g=false,b=[];}else p==="#"?f=true:p==="thread"&&(m=true);else if(Array.isArray(p))if(g)b.push(p);else if(p.length>1&&typeof p[p.length-2]=="object"&&p[p.length-2]&&"c"in p[p.length-2]&&typeof p[p.length-1]=="object"&&p[p.length-1]&&"b"in p[p.length-1]){d.pop();let C=[],S=[];for(;d.length>0&&d[d.length-1]!=="/ev";)C.push(d.pop());b=[...b,...C.reverse()],g=true,S.push(p.pop()),S.push(p.pop()),b=[...b,...p],b.push(S);}else if(p.length>1&&typeof p[p.length-1]=="object"&&p[p.length-1]&&"#n"in p[p.length-1]){let C=p.pop();if(!C){ae.error("Error parsing ink file: el is undefined");return}let S=C["#n"];delete C["#n"],p.push(C),i(r,{"->":e?e+"_|_"+S:S},e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),s({[S]:p},e,t);}else xn(p,e,t,r,i,a,s,o,u,l,c);else if(p&&typeof p=="object")if("->"in p&&typeof p["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->"])){let C=[];d.length>0&&(C=Il(["ev",...d],e,c,t)),p.params=C,i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=false;}else if("->t->"in p&&typeof p["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->t->"])){let C=[];d.length>0&&(C=Il(["ev",...d],e,c,t)),p.params=C,i(r,p,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m}),l=false;}else if("*"in p&&typeof p["*"]=="string")p["*"].includes("c")&&(d.push(p),l=false);else if("s"in p&&Array.isArray(p.s))d.push(p),l=false;else if("CNT?"in p)d.push(p),l=false;else if("VAR="in p||"temp="in p){let C="VAR="in p?p["VAR="]:p["temp="],S,D=[];if(C!=="$r"){for(d.pop(),d[d.length-1]==="/ev"&&d.pop();d.length>0&&d[d.length-1]!=="/ev";)D.push(d.pop());D=D.reverse(),S=aa(D,e,c,t),d=[],Pi({key:C,value:S,defaultType:"VAR="in p?"storage":"tempstorage",artmeticValue:true},c,t).forEach(A=>{(A.value!==void 0||A.value!==null)&&i(r,A,e,t,c,{isNewLine:l,isHashtagScript:f,isThreads:m});}),l=false;}}else s(p,e,t);}),o(d,r,e,t,c),e.includes("_|_")&&r.length===2){let p=r[0],v=r[1];p&&v&&typeof p=="object"&&"dialogue"in p&&typeof v=="object"&&"labelToOpen"in v&&p.dialogue===" "&&v.labelToOpen&&(r.shift(),delete v.glueEnabled,r[0]=v);}}function jl(n,e,t,r,i,a){if(e.length===0)return;let s=Dn(e,r,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:n,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:n,else:a};return o.else||delete o.else,o}}function dm(n,e,t,r,i,a,s=void 0){if(n.length===0){ae.error("Error parsing ink file: Conditional statement is not valid",n);return}let o=[],u=[];if(n.forEach(h=>{Array.isArray(h)?u.push(h):typeof h=="string"&&h==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),u.length===0){ae.error("Error parsing ink file: Conditional statement is not valid",u);return}let l=Vl(u[0],e,t,`${r}${"_|_"}then`,i,a,`${s||""}then`),c;return u.length===2?c=Vl(u[1],e,t,`${r}${"_|_"}else`,i,a,`${s||""}else`):u.length>2?(u.shift(),u.push("nop"),u=[{b:u}],c=Vl(u,e,t,r,i,a,`${s||""}else`)):c=void 0,i.du=void 0,jl(l,o,a,r,i,c)}function Vl(n,e,t,r,i,a,s=void 0){let o=[];for(let l of n)typeof l=="object"&&"b"in l&&(l.b=l.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),xn(l.b,r,i,o,e,e,t,Nr,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Ll(n="",e=""){let t=Array.isArray(n)?n:[n],r=Array.isArray(e)?e:[e];return [...new Set([...t,...r])]}function Nr(n,e,t,r,i){if(n.length>0){let a={};fm(n,a,i,r);for(let[s,o]of Object.entries(a)){let u=t+"_|_"+s,l={text:o.text.length===1?o.text[0]:o.text,label:u,props:{},type:kl(u,false),oneTime:o.onetime};o.text.length===0&&(l.onlyHaveNoChoice=true,l.autoSelect=true),l.oneTime===false&&delete l.oneTime;let c=jl(l,o.conditions,i,t,r)||l,h=e[e.length-1];if(typeof h=="object"&&h&&"type"in h&&(h={conditionalStep:h}),e.length>0&&typeof h=="object"&&h&&"choices"in h&&h.choices){let d=h.choices;d&&Array.isArray(d)?d.push(c):ae.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,d),h.choices=d.sort((g,f)=>{try{let m=g.label.split("."),b=m[m.length-1].replaceAll(".","_|_"),_=f.label.split("."),y=_[_.length-1].replaceAll(".","_|_");if(b.includes("c-")&&y.includes("c-")){let p=b.split("c-")[1],v=Number(p),C=y.split("c-")[1],S=Number(C);return v-S}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(r.preDialog[u]={...o.preDialog});}}}function fm(n,e,t,r,i){let a=[],s="",o="",u=false,l=[];for(let c=0;c<n.length;c++){let h=n[c];if(typeof h=="string")h.startsWith("^")?a.push(Xt(h)):om.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let d=Tr(h,sa,(g,f,m)=>{},i,r,t);a.push(d);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(s=`c${h["*"].split("c")[1]}`,h.flg&16&&(u=true));else if("s"in h&&Array.isArray(h.s)){let d=pm(h.s),g=h.s.includes("<>");d&&(i&&e[i]?(e[i].preDialog={text:d,glue:g},e[i].text=Ll(d,e[i].text)):(a.push(d),o=d));}else ("CNT?"in h||"VAR?"in h)&&l.push(h);else l.push(h);if(s){e[s]?e[s].text=Ll(a,e[s].text):e[s]={text:a,onetime:u,conditions:l},o&&(e[s].preDialog={text:o,glue:false});let d=n.slice(c+1);fm(d,e,t,r,s);return}}}function pm(n){for(let e of n)if(typeof e=="string"){if(e.startsWith("^"))return Xt(e)}else if(Array.isArray(e)){let t=pm(e);if(t)return t}}var ql;(i=>{function n(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:u=[],enums:l={},functions:c=[],preDialog:h={},characterIds:d}=s,g={$schema:ia};if(g.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:u,enums:l,functions:c,preDialog:h,characterIds:d}),g.labels&&ea in g.labels){let f=g.labels[ea];delete g.labels[ea],f.forEach(m=>{m.operations&&(g.initialOperations=g.initialOperations?[...g.initialOperations,...m.operations]:[...m.operations]);});}if(g.labels&&Kn in g.labels){let f=g.labels[Kn];delete g.labels[Kn],f.forEach(m=>{m.operations&&(g.initialOperations=g.initialOperations?[...g.initialOperations,...m.operations]:[...m.operations]);});}return o.forEach(f=>{g.labels&&f in g.labels&&delete g.labels[f];}),u.forEach(f=>{g.initialOperations&&(g.initialOperations=g.initialOperations.filter(m=>!(m.type==="value"&&m.key===f)));}),g}i.inkToJson=n;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){ae.error("Error parsing ink file",o);}}function t(a,s,o){for(let u of a)if(u)if(Array.isArray(u))if(u.includes("visit")){let l=Tr(u,sa,(c,h,d)=>{},"",o,[]);l&&(o.externalSwitch=l);}else t(u,s,o);else typeof u=="object"&&(u&&"VAR="in u&&o.externalSwitch&&(s[Kn]||(s[Kn]=[]),s[Kn].push({operations:Pi({defaultType:"storage",key:u["VAR="],value:o.externalSwitch},[],o)})),r(u,s,"",o));}function r(a,s,o="",u){if(a!==null){for(let[l,c]of Object.entries(a))if(Array.isArray(c)){let h=[],d={},g=(o?o+"_|_":"")+l;xn(c,g,u,h,Rl,Rl,(f,m,b)=>{r(f,d,m,b);},Nr);for(let[f,m]of Object.entries(d))s[f]=m;h.length>0&&(s[g]=h);}}}})(ql||={});var wp=wn(Jy()),bC=wn(Sv()),_C=wn(mC()),SC=wn(dr()),YN=/(?:^|<>)\s*#\s*([^\r\n]+)/g,QN=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,ZN=new Set(["DONE","END"]),eF="_|_",gC=new Map;function EC(n,e){let t=JSON.stringify([e,n]),r=gC.get(t);if(r)return r;let i=new RegExp(n,e);return gC.set(t,i),i}function Gs(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>Gs(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>Gs(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Gs(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(!EC(t.pattern,"").test(n))return !1}catch{return false}return true}function hl(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>hl(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>hl(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>hl(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(!Gs(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=>Gs(o,t.items))}function _p(n,e){if(e.type==="regexp")try{let t=EC(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:hl(n,e.schema)}function dl(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(dl);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(dl);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return dl(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function yC(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-wC(n,e)/t)}function tF(n,e){if(e&&typeof e=="object"){let t=e;if(typeof t.const=="string")return {weight:2,matched:n===void 0?0:2*yC(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=>yC(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function nF(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=tF(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 rF=.8,vC=new Map;function iF(n){let e=JSON.stringify(n),t=vC.get(e);if(t)return t;let r=new bC.default({strict:false,allErrors:true}).compile(n);return vC.set(e,r),r}function sF(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 aF(n,e){let[t]=gl(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return Ap(n)}function oF(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 Sp(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(YN)){let s=(a[1]??"").trim();if(!s)continue;let o=mn.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function Ap(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 wC(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 uF(n,e){let t,r=1/0;for(let a of e){let s=wC(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 lF(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&uF(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function gl(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function cF(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 gl(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function hF(n,e){let t=gl(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 pl(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]),pl(e[i[1]],e,t))}function ml(n,e){let t=pl(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=ml(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 CC(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 dF(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=ml(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&CC(o,e.type)&&CC(s.properties.operationType,e.operationType)&&r.push(i);}return r}function fF(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new wp.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function pF(n,e,t){let r=n.definitions??{},i=pl(r[e],r);for(let a of gl(t)){let o=ml(i,r)?.properties[a];if(o===void 0)return [];i=pl(o,r);}return Object.keys(ml(i,r)?.properties??{})}function fl(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=`${Ap(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function Ep(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:Ap(r),message:lF(r,t?.(r)),origin:cF(e,r.instancePath)}))}function mF(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?hF(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=Ep(fl(u),e);for(let[c,h]of o){let d=s?dF(s,h.node):[],g=d.length===1?d[0]:void 0;if(!g||!s){l.push(...Ep(fl(h.errors),e));continue}let m=fl(fF(s,g,h.node)).map(b=>({...b,instancePath:`${c}${b.instancePath}`}));l.push(...Ep(m,e,b=>pF(s,g,b.instancePath.slice(c.length))));}return l}var Ht;(h=>{function n(d,g={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let f=[];try{return {json:new _C.Compiler(d,{errorHandler:(y,p)=>{let v=y.replace(/^[A-Z]+: line \d+: ?/,""),C=y.match(/line (\d+)/);f.push({message:v,type:p,line:C?Number(C[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:y=>y,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:f}}catch{let b=false,_={...g,textSource:d};return e(f,()=>{b=true;},_),b?n(_.textSource,g):{issues:f}}}h.compile=n;function e(d,g,f){let{functions:m,initialVarsToRemove:b,labelToRemove:_}=f,y=d.find(p=>p.type===SC.ErrorType.Error);if(y){if(y.message.includes("Divert target not found")){let p=y.message.match(/Divert target not found: '-> (\w+)'/);if(p?.[1]){let v=p[1],C=`
67
-
68
- === ${v} ===
69
-
70
- -> DONE`;return f.textSource=f.textSource.concat(C),_.push(v),g()}}if(y.message.includes("Unresolved variable")){let p=y.message.match(/Unresolved variable: (\w+)/);if(p?.[1]){let v=p[1],C=`VAR ${v} = ""
71
-
72
- `;return f.textSource=C.concat(f.textSource),b.push(v),g()}}if(y.message.includes("Variable could not be found to assign to")){let p=y.message.match(/Variable could not be found to assign to: (\w+)/);if(p?.[1]){let v=p[1],C=`VAR ${v} = ""
73
-
74
- `;return f.textSource=C.concat(f.textSource),b.push(v),g()}}if(y.message.includes("Variable could not be found to assign to")){let p=y.message.match(/Variable could not be found to assign to: '(\w+)'/);if(p?.[1]){let v=p[1],C=`VAR ${v} = ""
75
-
76
- `;return f.textSource=C.concat(f.textSource),b.push(v),g()}}if(y.message.includes("Function call target not found")){let p=y.message.match(/Function call target not found: '-> (\w+)'/);if(p?.[1]){let v=p[1],C=`
77
-
78
- === function ${v}() ===
47
+ ~ myFunction()`);let u=(0, Jn.asOrNull)(o,ol.FunctionCall);return u&&(u.shouldPopReturnedValue=true),o.Find(ol.FunctionCall)()!==null&&(o=new bt.ContentList(o,new _n.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 Si.NumberExpression||l instanceof Hs.StringExpression||l instanceof vp.DivertTarget||l instanceof bp.VariableReference||l instanceof oC.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 Hs.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")),new Cp.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 Js.Identifier(o.name),new Cp.VariableAssignment({variableIdentifier:o,listDef:u})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new TN.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 NN.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 Si.NumberExpression||u instanceof vp.DivertTarget||u instanceof Hs.StringExpression?u instanceof Hs.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 _N.ConstantDeclaration(o,u)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new DN.Glue(new xN.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, Jn.asOrNull)(u,bt.ContentList);return l||(l=new bt.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 cC.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 Js.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 Ge.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=We.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 cC.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 We.SequenceType.Once:case We.SequenceType.Cycle:case We.SequenceType.Stopping:case We.SequenceType.Shuffle:case We.SequenceType.Shuffle|We.SequenceType.Stopping:case We.SequenceType.Shuffle|We.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),We.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new Ge.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let u of o)switch(u){case "!":s|=We.SequenceType.Once;break;case "&":s|=We.SequenceType.Cycle;break;case "~":s|=We.SequenceType.Shuffle;break;case "$":s|=We.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=We.SequenceType.Once;break;case "cycle":s=We.SequenceType.Cycle;break;case "shuffle":s=We.SequenceType.Shuffle;break;case "stopping":s=We.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 bt.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 bt.ContentList(c)),u=true;}return u||o.push(new bt.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(ot.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new _n.Text(`
49
+ `)),new bt.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===ot.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===ot.StatementLevel.Top&&u instanceof lC.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(ot.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>=ot.StatementLevel.Top&&u.push(this.KnotDefinition),u.push(this.Line(this.Choice)),u.push(this.Line(this.AuthorWarning)),o>ot.StatementLevel.InnerBlock&&u.push(this.Gather),o>=ot.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<=ot.StatementLevel.Knot&&l.push(this.KnotDeclaration),o<=ot.StatementLevel.Stitch&&l.push(this.StitchDeclaration),o<=ot.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(),bn.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 bt.ContentList;o.AddContent(new _i.Tag(false)),o.AddContent(new _i.Tag(true)),s=o;}else s=new _i.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new Ge.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?bn.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?bn.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?bn.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?bn.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?bn.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 $N.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 CN.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(al.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(al.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(al.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(al.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new Ge.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 bt.ContentList?e.AddContent(new _i.Tag(false)):e.push(new _i.Tag(false))),this.tagActive=false);}};ll.InkParser=ve;ve.LatinBasic=Gt.CharacterRange.Define("A","z",new Ge.CharacterSet().AddRange("[","`"));ve.LatinExtendedA=Gt.CharacterRange.Define("\u0100","\u017F");ve.LatinExtendedB=Gt.CharacterRange.Define("\u0180","\u024F");ve.Greek=Gt.CharacterRange.Define("\u0370","\u03FF",new Ge.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));ve.Cyrillic=Gt.CharacterRange.Define("\u0400","\u04FF",new Ge.CharacterSet().AddRange("\u0482","\u0489"));ve.Armenian=Gt.CharacterRange.Define("\u0530","\u058F",new Ge.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));ve.Hebrew=Gt.CharacterRange.Define("\u0590","\u05FF",new Ge.CharacterSet);ve.Arabic=Gt.CharacterRange.Define("\u0600","\u06FF",new Ge.CharacterSet);ve.Korean=Gt.CharacterRange.Define("\uAC00","\uD7AF",new Ge.CharacterSet);ve.Latin1Supplement=Gt.CharacterRange.Define("\x80","\xFF",new Ge.CharacterSet);ve.Chinese=Gt.CharacterRange.Define("\u4E00","\u9FFF",new Ge.CharacterSet);ve.ListAllCharacterRanges=()=>[ve.LatinBasic,ve.LatinExtendedA,ve.LatinExtendedB,ve.Arabic,ve.Armenian,ve.Cyrillic,ve.Greek,ve.Hebrew,ve.Korean,ve.Latin1Supplement,ve.Chinese];});var pC=S(cl=>{Object.defineProperty(cl,"__esModule",{value:true});cl.GenerateStoryStats=void 0;var VN=ui(),jN=di(),LN=As(),qN=jf(),BN=Gf(),MN=Bn();function WN(n){let e=n.FindAll(MN.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(qN.Knot)(),i=n.FindAll(BN.Stitch)(),a=n.FindAll(VN.Choice)(),s=n.FindAll(LN.Gather)(u=>u.debugMetadata!=null),o=n.FindAll(jN.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}}cl.GenerateStoryStats=WN;});var mC=S(hl=>{Object.defineProperty(hl,"__esModule",{value:true});hl.JsonFileHandler=void 0;var Sp=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}.`)};}};hl.JsonFileHandler=Sp;});var yC=S(nt=>{Object.defineProperty(nt,"__esModule",{value:true});nt.Compiler=nt.Story=nt.InkList=nt.JsonFileHandler=nt.StatementLevel=nt.InkParser=nt.CompilerOptions=void 0;var GN=sd(),HN=Av(),Ep=pr(),JN=_p(),zN=Te(),UN=fe(),KN=pC(),XN=sd();Object.defineProperty(nt,"CompilerOptions",{enumerable:true,get:function(){return XN.CompilerOptions}});var YN=_p();Object.defineProperty(nt,"InkParser",{enumerable:true,get:function(){return YN.InkParser}});var QN=Mf();Object.defineProperty(nt,"StatementLevel",{enumerable:true,get:function(){return QN.StatementLevel}});var ZN=mC();Object.defineProperty(nt,"JsonFileHandler",{enumerable:true,get:function(){return ZN.JsonFileHandler}});var gC=Rs();Object.defineProperty(nt,"InkList",{enumerable:true,get:function(){return gC.InkList}});Object.defineProperty(nt,"Story",{enumerable:true,get:function(){return gC.Story}});var wp=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 JN.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, UN.asOrNull)(i,zN.StringValue);if(a!==null){let s=new HN.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, KN.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 Ep.ErrorType.Author:this._authorMessages.push(r);break;case Ep.ErrorType.Warning:this._warnings.push(r);break;case Ep.ErrorType.Error:this._errors.push(r);break}this.options.errorHandler!==null&&this.options.errorHandler(r,i);},this._inputString=e,this._options=t||new GN.CompilerOptions;}};nt.Compiler=wp;});var jC=S((TB,kp)=>{var bl=process||{},$C=bl.argv||[],Cl=bl.env||{},BF=!(Cl.NO_COLOR||$C.includes("--no-color"))&&(!!Cl.FORCE_COLOR||$C.includes("--color")||bl.platform==="win32"||(bl.stdout||{}).isTTY&&Cl.TERM!=="dumb"||!!Cl.CI),MF=(n,e,t=n)=>r=>{let i=""+r,a=i.indexOf(e,n.length);return ~a?n+WF(i,e,t,a)+e:n+i+e},WF=(n,e,t,r)=>{let i="",a=0;do i+=n.substring(a,r)+t,a=r+e.length,r=n.indexOf(e,a);while(~r);return i+n.substring(a)},VC=(n=BF)=>{let e=n?MF:()=>String;return {isColorSupported:n,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};kp.exports=VC();kp.exports.createColors=VC;});var Xs=S((qB,eb)=>{var XC="[^\\\\/]",WI="(?=.)",YC="[^/]",Vp="(?:\\/|$)",QC="(?:^|\\/)",jp=`\\.{1,2}${Vp}`,GI="(?!\\.)",HI=`(?!${QC}${jp})`,JI=`(?!\\.{0,1}${Vp})`,zI=`(?!${jp})`,UI="[^.\\/]",KI=`${YC}*?`,XI="/",ZC={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:WI,QMARK:YC,END_ANCHOR:Vp,DOTS_SLASH:jp,NO_DOT:GI,NO_DOTS:HI,NO_DOT_SLASH:JI,NO_DOTS_SLASH:zI,QMARK_NO_DOT:UI,STAR:KI,START_ANCHOR:QC,SEP:XI},YI={...ZC,SLASH_LITERAL:"[\\\\/]",QMARK:XC,STAR:`${XC}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},QI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};eb.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:QI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(n){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===true?YI:ZC}};});var Ys=S(Et=>{var{REGEX_BACKSLASH:ZI,REGEX_REMOVE_BACKSLASH:ek,REGEX_SPECIAL_CHARS:tk,REGEX_SPECIAL_CHARS_GLOBAL:nk}=Xs();Et.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Et.hasRegexChars=n=>tk.test(n);Et.isRegexChar=n=>n.length===1&&Et.hasRegexChars(n);Et.escapeRegex=n=>n.replace(nk,"\\$1");Et.toPosixSlashes=n=>n.replace(ZI,"/");Et.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let n=navigator.platform.toLowerCase();return n==="win32"||n==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Et.removeBackslashes=n=>n.replace(ek,e=>e==="\\"?"":e);Et.escapeLast=(n,e,t)=>{let r=n.lastIndexOf(e,t);return r===-1?n:n[r-1]==="\\"?Et.escapeLast(n,e,r-1):`${n.slice(0,r)}\\${n.slice(r)}`};Et.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Et.wrapOutput=(n,e={},t={})=>{let r=t.contains?"":"^",i=t.contains?"":"$",a=`${r}(?:${n})${i}`;return e.negated===true&&(a=`(?:^(?!${a}).*$)`),a};Et.basename=(n,{windows:e}={})=>{let t=n.split(e?/[\\/]/:"/"),r=t[t.length-1];return r===""?t[t.length-2]:r};});var ub=S((MB,ob)=>{var tb=Ys(),{CHAR_ASTERISK:Lp,CHAR_AT:rk,CHAR_BACKWARD_SLASH:Ei,CHAR_COMMA:ik,CHAR_DOT:qp,CHAR_EXCLAMATION_MARK:Bp,CHAR_FORWARD_SLASH:ab,CHAR_LEFT_CURLY_BRACE:Mp,CHAR_LEFT_PARENTHESES:Sl,CHAR_LEFT_SQUARE_BRACKET:sk,CHAR_PLUS:ak,CHAR_QUESTION_MARK:nb,CHAR_RIGHT_CURLY_BRACE:ok,CHAR_RIGHT_PARENTHESES:rb,CHAR_RIGHT_SQUARE_BRACKET:uk}=Xs(),ib=n=>n===ab||n===Ei,sb=n=>{n.isPrefix!==true&&(n.depth=n.isGlobstar?1/0:1);},lk=(n,e)=>{let t=e||{},r=n.length-1,i=t.parts===true||t.tokens===true||t.scanToEnd===true,a=[],s=[],o=[],u=n,l=-1,c=0,h=0,f=false,g=false,p=false,m=false,C=false,b=false,y=false,d=false,_=false,v=false,w=0,D,O,P={value:"",depth:0,isGlob:false},E=()=>l>=r,F=()=>u.charCodeAt(l+1),R=()=>(D=O,u.charCodeAt(++l));for(;l<r;){O=R();let j;if(O===Ei){y=P.backslashes=true,O=R(),O===Mp&&(b=true);continue}if(b===true||O===Mp){for(w++;E()!==true&&(O=R());){if(O===Ei){y=P.backslashes=true,R();continue}if(O===Mp){w++;continue}if(b!==true&&O===qp&&(O=R())===qp){if(f=P.isBrace=true,p=P.isGlob=true,v=true,i===true)continue;break}if(b!==true&&O===ik){if(f=P.isBrace=true,p=P.isGlob=true,v=true,i===true)continue;break}if(O===ok&&(w--,w===0)){b=false,f=P.isBrace=true,v=true;break}}if(i===true)continue;break}if(O===ab){if(a.push(l),s.push(P),P={value:"",depth:0,isGlob:false},v===true)continue;if(D===qp&&l===c+1){c+=2;continue}h=l+1;continue}if(t.noext!==true&&(O===ak||O===rk||O===Lp||O===nb||O===Bp)===true&&F()===Sl){if(p=P.isGlob=true,m=P.isExtglob=true,v=true,O===Bp&&l===c&&(_=true),i===true){let Le=0;for(;E()!==true&&(O=R());){if(O===Ei){y=P.backslashes=true,R();continue}if(O===Sl){Le++;continue}if(O===rb&&--Le===0){v=true;break}}continue}break}if(O===Lp){if(D===Lp&&(C=P.isGlobstar=true),p=P.isGlob=true,v=true,i===true)continue;break}if(O===nb){if(p=P.isGlob=true,v=true,i===true)continue;break}if(O===sk){for(;E()!==true&&(j=R());){if(j===Ei){y=P.backslashes=true,R();continue}if(j===uk){g=P.isBracket=true,p=P.isGlob=true,v=true;break}}if(i===true)continue;break}if(t.nonegate!==true&&O===Bp&&l===c){d=P.negated=true,c++;continue}if(t.noparen!==true&&O===Sl){if(p=P.isGlob=true,i===true){let ce=1;for(;E()!==true&&(O=R());){if(O===Ei){y=P.backslashes=true,R();continue}if(O===Sl){ce++;continue}if(O===rb&&--ce===0){v=true;break}}continue}break}if(p===true){if(v=true,i===true)continue;break}}t.noext===true&&(m=false,p=false);let k=u,A="",x="";c>0&&(A=u.slice(0,c),u=u.slice(c),h-=c),k&&p===true&&h>0?(k=u.slice(0,h),x=u.slice(h)):p===true?(k="",x=u):k=u,k&&k!==""&&k!=="/"&&k!==u&&ib(k.charCodeAt(k.length-1))&&(k=k.slice(0,-1)),t.unescape===true&&(x&&(x=tb.removeBackslashes(x)),k&&y===true&&(k=tb.removeBackslashes(k)));let Ce={prefix:A,input:n,start:c,base:k,glob:x,isBrace:f,isBracket:g,isGlob:p,isExtglob:m,isGlobstar:C,negated:d,negatedExtglob:_};if(t.tokens===true&&(Ce.maxDepth=0,ib(O)||s.push(P),Ce.tokens=s),t.parts===true||t.tokens===true){let j;for(let xe=0;xe<a.length;xe++){let En=j!==void 0?j+1:c,wn=a[xe],cn=n.slice(En,wn);t.tokens&&(xe===0&&c!==0?(s[xe].isPrefix=true,s[xe].value=A):s[xe].value=cn,sb(s[xe]),Ce.maxDepth+=s[xe].depth),wn>=c&&(o.push(cn),j=wn);}let ce=j!==void 0?j+1:c,Le=n.slice(ce);o.push(Le),t.tokens&&j&&j+1<n.length&&(s[s.length-1].value=Le,sb(s[s.length-1]),Ce.maxDepth+=s[s.length-1].depth),Ce.slashes=a,Ce.parts=o;}return Ce};ob.exports=lk;});var db=S((WB,hb)=>{var Qs=Xs(),wt=Ys(),{MAX_LENGTH:El,POSIX_REGEX_SOURCE:ck,REGEX_NON_SPECIAL_CHARS:hk,REGEX_SPECIAL_CHARS_BACKREF:dk,REPLACEMENTS:lb}=Qs,fk=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t);}catch{return n.map(i=>wt.escapeRegex(i)).join("..")}return t},wi=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,cb=n=>{let e=[],t=0,r=0,i=0,a="",s=false;for(let o of n){if(s===true){a+=o,s=false;continue}if(o==="\\"){a+=o,s=true;continue}if(o==='"'){i=i===1?0:1,a+=o;continue}if(i===0){if(o==="[")t++;else if(o==="]"&&t>0)t--;else if(t===0){if(o==="(")r++;else if(o===")"&&r>0)r--;else if(o==="|"&&r===0){e.push(a),a="";continue}}}a+=o;}return e.push(a),e},pk=n=>{let e=false;for(let t of n){if(e===true){e=false;continue}if(t==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(t))return false}return true},Gp=n=>{let e=n.trim(),t=true;for(;t===true;)t=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=true);if(pk(e))return e.replace(/\\(.)/g,"$1")},mk=n=>{let e=n.map(Gp).filter(Boolean);for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++){let i=e[t],a=e[r],s=i[0];if(!(!s||i!==s.repeat(i.length)||a!==s.repeat(a.length))&&(i===a||i.startsWith(a)||a.startsWith(i)))return true}return false},Wp=(n,e=true)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,r=0,i=0,a=false;for(let s=1;s<n.length;s++){let o=n[s];if(a===true){a=false;continue}if(o==="\\"){a=true;continue}if(o==='"'){i=i===1?0:1;continue}if(i!==1){if(o==="["){t++;continue}if(o==="]"&&t>0){t--;continue}if(!(t>0)){if(o==="("){r++;continue}if(o===")"&&(r--,r===0))return e===true&&s!==n.length-1?void 0:{type:n[0],body:n.slice(2,s),end:s}}}}},gk=n=>`${n.length===1?wt.escapeRegex(n[0]):`[${n.map(t=>wt.escapeRegex(t)).join("")}]`}*`,yk=n=>{let e=0,t=[];for(;e<n.length;){let r=Wp(n.slice(e),false);if(!r||r.type!=="*")return;let i=cb(r.body).map(s=>s.trim());if(i.length!==1)return;let a=Gp(i[0]);if(!a||a.length!==1)return;t.push(a),e+=r.end+1;}if(!(t.length<1))return t},vk=n=>{let e=0,t=n.trim(),r=Wp(t);for(;r;)e++,t=r.body.trim(),r=Wp(t);return e},Ck=(n,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Qs.DEFAULT_MAX_EXTGLOB_RECURSION,r=cb(n).map(o=>o.trim());if(r.length>1&&(r.some(o=>o==="")||r.some(o=>/^[*?]+$/.test(o))||mk(r)))return {risky:true};let i=[],a=false,s=true;for(let o of r){let u=yk(o);if(u){a=true,i.push(...u);continue}let l=Gp(o);if(l&&l.length===1){i.push(l);continue}if(s=false,vk(o)>t)return {risky:true}}return a?s?{risky:true,safeOutput:gk([...new Set(i)])}:{risky:true}:{risky:false}},Hp=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=lb[n]||n;let t={...e},r=typeof t.maxLength=="number"?Math.min(El,t.maxLength):El,i=n.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let a={type:"bos",value:"",output:t.prepend||""},s=[a],o=t.capture?"":"?:",u=Qs.globChars(t.windows),l=Qs.extglobChars(u),{DOT_LITERAL:c,PLUS_LITERAL:h,SLASH_LITERAL:f,ONE_CHAR:g,DOTS_SLASH:p,NO_DOT:m,NO_DOT_SLASH:C,NO_DOTS_SLASH:b,QMARK:y,QMARK_NO_DOT:d,STAR:_,START_ANCHOR:v}=u,w=N=>`(${o}(?:(?!${v}${N.dot?p:c}).)*?)`,D=t.dot?"":m,O=t.dot?y:d,P=t.bash===true?w(t):_;t.capture&&(P=`(${P})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let E={input:n,index:-1,start:0,dot:t.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:s};n=wt.removePrefix(n,E),i=n.length;let F=[],R=[],k=[],A=a,x,Ce=()=>E.index===i-1,j=E.peek=(N=1)=>n[E.index+N],ce=E.advance=()=>n[++E.index]||"",Le=()=>n.slice(E.index+1),xe=(N="",W=0)=>{E.consumed+=N,E.index+=W;},En=N=>{E.output+=N.output!=null?N.output:N.value,xe(N.value);},wn=()=>{let N=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)ce(),E.start++,N++;return N%2===0?false:(E.negated=true,E.start++,true)},cn=N=>{E[N]++,k.push(N);},Jt=N=>{E[N]--,k.pop();},J=N=>{if(A.type==="globstar"){let W=E.braces>0&&(N.type==="comma"||N.type==="brace"),I=N.extglob===true||F.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!W&&!I&&(E.output=E.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=P,E.output+=A.output);}if(F.length&&N.type!=="paren"&&(F[F.length-1].inner+=N.value),(N.value||N.output)&&En(N),A&&A.type==="text"&&N.type==="text"){A.output=(A.output||A.value)+N.value,A.value+=N.value;return}N.prev=A,s.push(N),A=N;},pe=(N,W)=>{let I={...l[W],conditions:1,inner:""};I.prev=A,I.parens=E.parens,I.output=E.output,I.startIndex=E.index,I.tokensIndex=s.length;let z=(t.capture?"(":"")+I.open;cn("parens"),J({type:N,value:W,output:E.output?"":g}),J({type:"paren",extglob:true,value:ce(),output:z}),F.push(I);},At=N=>{let W=n.slice(N.startIndex,E.index+1),I=n.slice(N.startIndex+2,E.index),z=Ck(I,t);if((N.type==="plus"||N.type==="star")&&z.risky){let ge=z.safeOutput?(N.output?"":g)+(t.capture?`(${z.safeOutput})`:z.safeOutput):void 0,zt=s[N.tokensIndex];zt.type="text",zt.value=W,zt.output=ge||wt.escapeRegex(W);for(let Kn=N.tokensIndex+1;Kn<s.length;Kn++)s[Kn].value="",s[Kn].output="",delete s[Kn].suffix;E.output=N.output+zt.output,E.backtrack=true,J({type:"paren",extglob:true,value:x,output:""}),Jt("parens");return}let be=N.close+(t.capture?")":""),Ve;if(N.type==="negate"){let ge=P;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(ge=w(t)),(ge!==P||Ce()||/^\)+$/.test(Le()))&&(be=N.close=`)$))${ge}`),N.inner.includes("*")&&(Ve=Le())&&/^\.[^\\/.]+$/.test(Ve)){let zt=Hp(Ve,{...e,fastpaths:false}).output;be=N.close=`)${zt})${ge})`;}N.prev.type==="bos"&&(E.negatedExtglob=true);}J({type:"paren",extglob:true,value:x,output:be}),Jt("parens");};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(n)){let N=false,W=n.replace(dk,(I,z,be,Ve,ge,zt)=>Ve==="\\"?(N=true,I):Ve==="?"?z?z+Ve+(ge?y.repeat(ge.length):""):zt===0?O+(ge?y.repeat(ge.length):""):y.repeat(be.length):Ve==="."?c.repeat(be.length):Ve==="*"?z?z+Ve+(ge?P:""):P:z?I:`\\${I}`);return N===true&&(t.unescape===true?W=W.replace(/\\/g,""):W=W.replace(/\\+/g,I=>I.length%2===0?"\\\\":I?"\\":"")),W===n&&t.contains===true?(E.output=n,E):(E.output=wt.wrapOutput(W,E,e),E)}for(;!Ce();){if(x=ce(),x==="\0")continue;if(x==="\\"){let I=j();if(I==="/"&&t.bash!==true||I==="."||I===";")continue;if(!I){x+="\\",J({type:"text",value:x});continue}let z=/^\\+/.exec(Le()),be=0;if(z&&z[0].length>2&&(be=z[0].length,E.index+=be,be%2!==0&&(x+="\\")),t.unescape===true?x=ce():x+=ce(),E.brackets===0){J({type:"text",value:x});continue}}if(E.brackets>0&&(x!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==false&&x===":"){let I=A.value.slice(1);if(I.includes("[")&&(A.posix=true,I.includes(":"))){let z=A.value.lastIndexOf("["),be=A.value.slice(0,z),Ve=A.value.slice(z+2),ge=ck[Ve];if(ge){A.value=be+ge,E.backtrack=true,ce(),!a.output&&s.indexOf(A)===1&&(a.output=g);continue}}}(x==="["&&j()!==":"||x==="-"&&j()==="]")&&(x=`\\${x}`),x==="]"&&(A.value==="["||A.value==="[^")&&(x=`\\${x}`),t.posix===true&&x==="!"&&A.value==="["&&(x="^"),A.value+=x,En({value:x});continue}if(E.quotes===1&&x!=='"'){x=wt.escapeRegex(x),A.value+=x,En({value:x});continue}if(x==='"'){E.quotes=E.quotes===1?0:1,t.keepQuotes===true&&J({type:"text",value:x});continue}if(x==="("){cn("parens"),J({type:"paren",value:x});continue}if(x===")"){if(E.parens===0&&t.strictBrackets===true)throw new SyntaxError(wi("opening","("));let I=F[F.length-1];if(I&&E.parens===I.parens+1){At(F.pop());continue}J({type:"paren",value:x,output:E.parens?")":"\\)"}),Jt("parens");continue}if(x==="["){if(t.nobracket===true||!Le().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true)throw new SyntaxError(wi("closing","]"));x=`\\${x}`;}else cn("brackets");J({type:"bracket",value:x});continue}if(x==="]"){if(t.nobracket===true||A&&A.type==="bracket"&&A.value.length===1){J({type:"text",value:x,output:`\\${x}`});continue}if(E.brackets===0){if(t.strictBrackets===true)throw new SyntaxError(wi("opening","["));J({type:"text",value:x,output:`\\${x}`});continue}Jt("brackets");let I=A.value.slice(1);if(A.posix!==true&&I[0]==="^"&&!I.includes("/")&&(x=`/${x}`),A.value+=x,En({value:x}),t.literalBrackets===false||wt.hasRegexChars(I))continue;let z=wt.escapeRegex(A.value);if(E.output=E.output.slice(0,-A.value.length),t.literalBrackets===true){E.output+=z,A.value=z;continue}A.value=`(${o}${z}|${A.value})`,E.output+=A.value;continue}if(x==="{"&&t.nobrace!==true){cn("braces");let I={type:"brace",value:x,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};R.push(I),J(I);continue}if(x==="}"){let I=R[R.length-1];if(t.nobrace===true||!I){J({type:"text",value:x,output:x});continue}let z=")";if(I.dots===true){let be=s.slice(),Ve=[];for(let ge=be.length-1;ge>=0&&(s.pop(),be[ge].type!=="brace");ge--)be[ge].type!=="dots"&&Ve.unshift(be[ge].value);z=fk(Ve,t),E.backtrack=true;}if(I.comma!==true&&I.dots!==true){let be=E.output.slice(0,I.outputIndex),Ve=E.tokens.slice(I.tokensIndex);I.value=I.output="\\{",x=z="\\}",E.output=be;for(let ge of Ve)E.output+=ge.output||ge.value;}J({type:"brace",value:x,output:z}),Jt("braces"),R.pop();continue}if(x==="|"){F.length>0&&F[F.length-1].conditions++,J({type:"text",value:x});continue}if(x===","){let I=x,z=R[R.length-1];z&&k[k.length-1]==="braces"&&(z.comma=true,I="|"),J({type:"comma",value:x,output:I});continue}if(x==="/"){if(A.type==="dot"&&E.index===E.start+1){E.start=E.index+1,E.consumed="",E.output="",s.pop(),A=a;continue}J({type:"slash",value:x,output:f});continue}if(x==="."){if(E.braces>0&&A.type==="dot"){A.value==="."&&(A.output=c);let I=R[R.length-1];A.type="dots",A.output+=x,A.value+=x,I.dots=true;continue}if(E.braces+E.parens===0&&A.type!=="bos"&&A.type!=="slash"){J({type:"text",value:x,output:c});continue}J({type:"dot",value:x,output:c});continue}if(x==="?"){if(!(A&&A.value==="(")&&t.noextglob!==true&&j()==="("&&j(2)!=="?"){pe("qmark",x);continue}if(A&&A.type==="paren"){let z=j(),be=x;(A.value==="("&&!/[!=<:]/.test(z)||z==="<"&&!/<([!=]|\w+>)/.test(Le()))&&(be=`\\${x}`),J({type:"text",value:x,output:be});continue}if(t.dot!==true&&(A.type==="slash"||A.type==="bos")){J({type:"qmark",value:x,output:d});continue}J({type:"qmark",value:x,output:y});continue}if(x==="!"){if(t.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){pe("negate",x);continue}if(t.nonegate!==true&&E.index===0){wn();continue}}if(x==="+"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){pe("plus",x);continue}if(A&&A.value==="("||t.regex===false){J({type:"plus",value:x,output:h});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||E.parens>0){J({type:"plus",value:x});continue}J({type:"plus",value:h});continue}if(x==="@"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){J({type:"at",extglob:true,value:x,output:""});continue}J({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let I=hk.exec(Le());I&&(x+=I[0],E.index+=I[0].length),J({type:"text",value:x});continue}if(A&&(A.type==="globstar"||A.star===true)){A.type="star",A.star=true,A.value+=x,A.output=P,E.backtrack=true,E.globstar=true,xe(x);continue}let N=Le();if(t.noextglob!==true&&/^\([^?]/.test(N)){pe("star",x);continue}if(A.type==="star"){if(t.noglobstar===true){xe(x);continue}let I=A.prev,z=I.prev,be=I.type==="slash"||I.type==="bos",Ve=z&&(z.type==="star"||z.type==="globstar");if(t.bash===true&&(!be||N[0]&&N[0]!=="/")){J({type:"star",value:x,output:""});continue}let ge=E.braces>0&&(I.type==="comma"||I.type==="brace"),zt=F.length&&(I.type==="pipe"||I.type==="paren");if(!be&&I.type!=="paren"&&!ge&&!zt){J({type:"star",value:x,output:""});continue}for(;N.slice(0,3)==="/**";){let Tr=n[E.index+4];if(Tr&&Tr!=="/")break;N=N.slice(3),xe("/**",3);}let Kn=Ce()||E.parens>0&&N===")".repeat(E.parens)&&!F.some(Tr=>Tr.type==="negate");if(I.type==="bos"&&Ce()){A.type="globstar",A.value+=x,A.output=w(t),E.output=A.output,E.globstar=true,xe(x);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&!Ve&&Kn){E.output=E.output.slice(0,-(I.output+A.output).length),I.output=`(?:${I.output}`,A.type="globstar",A.output=w(t)+(t.strictSlashes?")":"|$)"),A.value+=x,E.globstar=true,E.output+=I.output+A.output,xe(x);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&N[0]==="/"){let Tr=N[1]!==void 0?"|$":"";E.output=E.output.slice(0,-(I.output+A.output).length),I.output=`(?:${I.output}`,A.type="globstar",A.output=`${w(t)}${f}|${f}${Tr})`,A.value+=x,E.output+=I.output+A.output,E.globstar=true,xe(x+ce()),J({type:"slash",value:"/",output:""});continue}if(I.type==="bos"&&N[0]==="/"){A.type="globstar",A.value+=x,A.output=`(?:^|${f}|${w(t)}${f})`,E.output=A.output,E.globstar=true,xe(x+ce()),J({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-A.output.length),A.type="globstar",A.output=w(t),A.value+=x,E.output+=A.output,E.globstar=true,xe(x);continue}let W={type:"star",value:x,output:P};if(t.bash===true){W.output=".*?",(A.type==="bos"||A.type==="slash")&&(W.output=D+W.output),J(W);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===true){W.output=x,J(W);continue}(E.index===E.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(E.output+=C,A.output+=C):t.dot===true?(E.output+=b,A.output+=b):(E.output+=D,A.output+=D),j()!=="*"&&(E.output+=g,A.output+=g)),J(W);}for(;E.brackets>0;){if(t.strictBrackets===true)throw new SyntaxError(wi("closing","]"));E.output=wt.escapeLast(E.output,"["),Jt("brackets");}for(;E.parens>0;){if(t.strictBrackets===true)throw new SyntaxError(wi("closing",")"));E.output=wt.escapeLast(E.output,"("),Jt("parens");}for(;E.braces>0;){if(t.strictBrackets===true)throw new SyntaxError(wi("closing","}"));E.output=wt.escapeLast(E.output,"{"),Jt("braces");}if(t.strictSlashes!==true&&(A.type==="star"||A.type==="bracket")&&J({type:"maybe_slash",value:"",output:`${f}?`}),E.backtrack===true){E.output="";for(let N of E.tokens)E.output+=N.output!=null?N.output:N.value,N.suffix&&(E.output+=N.suffix);}return E};Hp.fastpaths=(n,e)=>{let t={...e},r=typeof t.maxLength=="number"?Math.min(El,t.maxLength):El,i=n.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);n=lb[n]||n;let{DOT_LITERAL:a,SLASH_LITERAL:s,ONE_CHAR:o,DOTS_SLASH:u,NO_DOT:l,NO_DOTS:c,NO_DOTS_SLASH:h,STAR:f,START_ANCHOR:g}=Qs.globChars(t.windows),p=t.dot?c:l,m=t.dot?h:l,C=t.capture?"":"?:",b={negated:false,prefix:""},y=t.bash===true?".*?":f;t.capture&&(y=`(${y})`);let d=D=>D.noglobstar===true?y:`(${C}(?:(?!${g}${D.dot?u:a}).)*?)`,_=D=>{switch(D){case "*":return `${p}${o}${y}`;case ".*":return `${a}${o}${y}`;case "*.*":return `${p}${y}${a}${o}${y}`;case "*/*":return `${p}${y}${s}${o}${m}${y}`;case "**":return p+d(t);case "**/*":return `(?:${p}${d(t)}${s})?${m}${o}${y}`;case "**/*.*":return `(?:${p}${d(t)}${s})?${m}${y}${a}${o}${y}`;case "**/.*":return `(?:${p}${d(t)}${s})?${a}${o}${y}`;default:{let O=/^(.*?)\.(\w+)$/.exec(D);if(!O)return;let P=_(O[1]);return P?P+a+O[2]:void 0}}},v=wt.removePrefix(n,b),w=_(v);return w&&t.strictSlashes!==true&&(w+=`${s}?`),w};hb.exports=Hp;});var mb=S((GB,pb)=>{var bk=ub(),Jp=db(),fb=Ys(),_k=Xs(),Sk=n=>n&&typeof n=="object"&&!Array.isArray(n),ke=(n,e,t=false)=>{if(Array.isArray(n)){let c=n.map(f=>ke(f,e,t));return f=>{for(let g of c){let p=g(f);if(p)return p}return false}}let r=Sk(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},a=i.windows,s=r?ke.compileRe(n,e):ke.makeRe(n,e,false,true),o=s.state;delete s.state;let u=()=>false;if(i.ignore){let c={...e,ignore:null,onMatch:null,onResult:null};u=ke(i.ignore,c,t);}let l=(c,h=false)=>{let{isMatch:f,match:g,output:p}=ke.test(c,s,e,{glob:n,posix:a}),m={glob:n,state:o,regex:s,posix:a,input:c,output:p,match:g,isMatch:f};return typeof i.onResult=="function"&&i.onResult(m),f===false?(m.isMatch=false,h?m:false):u(c)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=false,h?m:false):(typeof i.onMatch=="function"&&i.onMatch(m),h?m:true)};return t&&(l.state=o),l};ke.test=(n,e,t,{glob:r,posix:i}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return {isMatch:false,output:""};let a=t||{},s=a.format||(i?fb.toPosixSlashes:null),o=n===r,u=o&&s?s(n):n;return o===false&&(u=s?s(n):n,o=u===r),(o===false||a.capture===true)&&(a.matchBase===true||a.basename===true?o=ke.matchBase(n,e,t,i):o=e.exec(u)),{isMatch:!!o,match:o,output:u}};ke.matchBase=(n,e,t,r=t&&t.windows)=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(fb.basename(n,{windows:r}));ke.isMatch=(n,e,t)=>ke(e,t)(n);ke.parse=(n,e)=>Array.isArray(n)?n.map(t=>ke.parse(t,e)):Jp(n,{...e,fastpaths:false});ke.scan=(n,e)=>bk(n,e);ke.compileRe=(n,e,t=false,r=false)=>{if(t===true)return n.output;let i=e||{},a=i.contains?"":"^",s=i.contains?"":"$",o=`${a}(?:${n.output})${s}`;n&&n.negated===true&&(o=`^(?!${o}).*$`);let u=ke.toRegex(o,e);return r===true&&(u.state=n),u};ke.makeRe=(n,e={},t=false,r=false)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return e.fastpaths!==false&&(n[0]==="."||n[0]==="*")&&(i.output=Jp.fastpaths(n,e)),i.output||(i=Jp(n,e)),ke.compileRe(i,e,t,r)};ke.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===true)throw t;return /$^/}};ke.constants=_k;pb.exports=ke;});var Cb=S((HB,vb)=>{var gb=mb(),Ek=Ys();function yb(n,e,t=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:Ek.isWindows()}),gb(n,e,t)}Object.assign(yb,gb);vb.exports=yb;});var xi="/__pixi-vn-ink/hashtag-commands",ea="/__pixi-vn-ink/text-replaces",Dl="/__pixi-vn-ink/info";var ta="global decl",Yn="___external_value___";var ae;(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)))(ae||={});var Wb=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,Gb=/[\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]/,Hb=/[\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]/,xl={Space_Separator:Wb,ID_Start:Gb,ID_Continue:Hb},Fe={isSpaceSeparator(n){return typeof n=="string"&&xl.Space_Separator.test(n)},isIdStartChar(n){return typeof n=="string"&&(n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="$"||n==="_"||xl.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"||xl.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)}},Ol,rt,dn,ra,Dn,jt,qe,Fl,Oi,Jb=function(e,t){Ol=String(e),rt="start",dn=[],ra=0,Dn=1,jt=0,qe=void 0,Fl=void 0,Oi=void 0;do qe=zb(),Xb[rt]();while(qe.type!=="eof");return typeof t=="function"?Tl({"":Oi},"",t):Oi};function Tl(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=Tl(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=Tl(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 H,B,Pi,hn,Z;function zb(){for(H="default",B="",Pi=false,hn=1;;){Z=fn();let n=tm[H]();if(n)return n}}function fn(){if(Ol[ra])return String.fromCodePoint(Ol.codePointAt(ra))}function T(){let n=fn();return n===`
52
+ `?(Dn++,jt=0):n?jt+=n.length:jt++,n&&(ra+=n.length),n}var tm={default(){switch(Z){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
53
+ `:case "\r":case "\u2028":case "\u2029":T();return;case "/":T(),H="comment";return;case void 0:return T(),_e("eof")}if(Fe.isSpaceSeparator(Z)){T();return}return tm[rt]()},comment(){switch(Z){case "*":T(),H="multiLineComment";return;case "/":T(),H="singleLineComment";return}throw Se(T())},multiLineComment(){switch(Z){case "*":T(),H="multiLineCommentAsterisk";return;case void 0:throw Se(T())}T();},multiLineCommentAsterisk(){switch(Z){case "*":T();return;case "/":T(),H="default";return;case void 0:throw Se(T())}T(),H="multiLineComment";},singleLineComment(){switch(Z){case `
54
+ `:case "\r":case "\u2028":case "\u2029":T(),H="default";return;case void 0:return T(),_e("eof")}T();},value(){switch(Z){case "{":case "[":return _e("punctuator",T());case "n":return T(),Qn("ull"),_e("null",null);case "t":return T(),Qn("rue"),_e("boolean",true);case "f":return T(),Qn("alse"),_e("boolean",false);case "-":case "+":T()==="-"&&(hn=-1),H="sign";return;case ".":B=T(),H="decimalPointLeading";return;case "0":B=T(),H="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":B=T(),H="decimalInteger";return;case "I":return T(),Qn("nfinity"),_e("numeric",1/0);case "N":return T(),Qn("aN"),_e("numeric",NaN);case '"':case "'":Pi=T()==='"',B="",H="string";return}throw Se(T())},identifierNameStartEscape(){if(Z!=="u")throw Se(T());T();let n=Nl();switch(n){case "$":case "_":break;default:if(!Fe.isIdStartChar(n))throw em();break}B+=n,H="identifierName";},identifierName(){switch(Z){case "$":case "_":case "\u200C":case "\u200D":B+=T();return;case "\\":T(),H="identifierNameEscape";return}if(Fe.isIdContinueChar(Z)){B+=T();return}return _e("identifier",B)},identifierNameEscape(){if(Z!=="u")throw Se(T());T();let n=Nl();switch(n){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!Fe.isIdContinueChar(n))throw em();break}B+=n,H="identifierName";},sign(){switch(Z){case ".":B=T(),H="decimalPointLeading";return;case "0":B=T(),H="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":B=T(),H="decimalInteger";return;case "I":return T(),Qn("nfinity"),_e("numeric",hn*(1/0));case "N":return T(),Qn("aN"),_e("numeric",NaN)}throw Se(T())},zero(){switch(Z){case ".":B+=T(),H="decimalPoint";return;case "e":case "E":B+=T(),H="decimalExponent";return;case "x":case "X":B+=T(),H="hexadecimal";return}return _e("numeric",hn*0)},decimalInteger(){switch(Z){case ".":B+=T(),H="decimalPoint";return;case "e":case "E":B+=T(),H="decimalExponent";return}if(Fe.isDigit(Z)){B+=T();return}return _e("numeric",hn*Number(B))},decimalPointLeading(){if(Fe.isDigit(Z)){B+=T(),H="decimalFraction";return}throw Se(T())},decimalPoint(){switch(Z){case "e":case "E":B+=T(),H="decimalExponent";return}if(Fe.isDigit(Z)){B+=T(),H="decimalFraction";return}return _e("numeric",hn*Number(B))},decimalFraction(){switch(Z){case "e":case "E":B+=T(),H="decimalExponent";return}if(Fe.isDigit(Z)){B+=T();return}return _e("numeric",hn*Number(B))},decimalExponent(){switch(Z){case "+":case "-":B+=T(),H="decimalExponentSign";return}if(Fe.isDigit(Z)){B+=T(),H="decimalExponentInteger";return}throw Se(T())},decimalExponentSign(){if(Fe.isDigit(Z)){B+=T(),H="decimalExponentInteger";return}throw Se(T())},decimalExponentInteger(){if(Fe.isDigit(Z)){B+=T();return}return _e("numeric",hn*Number(B))},hexadecimal(){if(Fe.isHexDigit(Z)){B+=T(),H="hexadecimalInteger";return}throw Se(T())},hexadecimalInteger(){if(Fe.isHexDigit(Z)){B+=T();return}return _e("numeric",hn*Number(B))},string(){switch(Z){case "\\":T(),B+=Ub();return;case '"':if(Pi)return T(),_e("string",B);B+=T();return;case "'":if(!Pi)return T(),_e("string",B);B+=T();return;case `
55
+ `:case "\r":throw Se(T());case "\u2028":case "\u2029":Yb(Z);break;case void 0:throw Se(T())}B+=T();},start(){switch(Z){case "{":case "[":return _e("punctuator",T())}H="value";},beforePropertyName(){switch(Z){case "$":case "_":B=T(),H="identifierName";return;case "\\":T(),H="identifierNameStartEscape";return;case "}":return _e("punctuator",T());case '"':case "'":Pi=T()==='"',H="string";return}if(Fe.isIdStartChar(Z)){B+=T(),H="identifierName";return}throw Se(T())},afterPropertyName(){if(Z===":")return _e("punctuator",T());throw Se(T())},beforePropertyValue(){H="value";},afterPropertyValue(){switch(Z){case ",":case "}":return _e("punctuator",T())}throw Se(T())},beforeArrayValue(){if(Z==="]")return _e("punctuator",T());H="value";},afterArrayValue(){switch(Z){case ",":case "]":return _e("punctuator",T())}throw Se(T())},end(){throw Se(T())}};function _e(n,e){return {type:n,value:e,line:Dn,column:jt}}function Qn(n){for(let e of n){if(fn()!==e)throw Se(T());T();}}function Ub(){switch(fn()){case "b":return T(),"\b";case "f":return T(),"\f";case "n":return T(),`
56
+ `;case "r":return T(),"\r";case "t":return T()," ";case "v":return T(),"\v";case "0":if(T(),Fe.isDigit(fn()))throw Se(T());return "\0";case "x":return T(),Kb();case "u":return T(),Nl();case `
57
+ `:case "\u2028":case "\u2029":return T(),"";case "\r":return T(),fn()===`
58
+ `&&T(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw Se(T());case void 0:throw Se(T())}return T()}function Kb(){let n="",e=fn();if(!Fe.isHexDigit(e)||(n+=T(),e=fn(),!Fe.isHexDigit(e)))throw Se(T());return n+=T(),String.fromCodePoint(parseInt(n,16))}function Nl(){let n="",e=4;for(;e-- >0;){let t=fn();if(!Fe.isHexDigit(t))throw Se(T());n+=T();}return String.fromCodePoint(parseInt(n,16))}var Xb={start(){if(qe.type==="eof")throw Zn();Pl();},beforePropertyName(){switch(qe.type){case "identifier":case "string":Fl=qe.value,rt="afterPropertyName";return;case "punctuator":na();return;case "eof":throw Zn()}},afterPropertyName(){if(qe.type==="eof")throw Zn();rt="beforePropertyValue";},beforePropertyValue(){if(qe.type==="eof")throw Zn();Pl();},beforeArrayValue(){if(qe.type==="eof")throw Zn();if(qe.type==="punctuator"&&qe.value==="]"){na();return}Pl();},afterPropertyValue(){if(qe.type==="eof")throw Zn();switch(qe.value){case ",":rt="beforePropertyName";return;case "}":na();}},afterArrayValue(){if(qe.type==="eof")throw Zn();switch(qe.value){case ",":rt="beforeArrayValue";return;case "]":na();}},end(){}};function Pl(){let n;switch(qe.type){case "punctuator":switch(qe.value){case "{":n={};break;case "[":n=[];break}break;case "null":case "boolean":case "numeric":case "string":n=qe.value;break}if(Oi===void 0)Oi=n;else {let e=dn[dn.length-1];Array.isArray(e)?e.push(n):Object.defineProperty(e,Fl,{value:n,writable:true,enumerable:true,configurable:true});}if(n!==null&&typeof n=="object")dn.push(n),Array.isArray(n)?rt="beforeArrayValue":rt="beforePropertyName";else {let e=dn[dn.length-1];e==null?rt="end":Array.isArray(e)?rt="afterArrayValue":rt="afterPropertyValue";}}function na(){dn.pop();let n=dn[dn.length-1];n==null?rt="end":Array.isArray(n)?rt="afterArrayValue":rt="afterPropertyValue";}function Se(n){return ia(n===void 0?`JSON5: invalid end of input at ${Dn}:${jt}`:`JSON5: invalid character '${nm(n)}' at ${Dn}:${jt}`)}function Zn(){return ia(`JSON5: invalid end of input at ${Dn}:${jt}`)}function em(){return jt-=5,ia(`JSON5: invalid identifier character at ${Dn}:${jt}`)}function Yb(n){console.warn(`JSON5: '${nm(n)}' in strings is not valid ECMAScript; consider escaping`);}function nm(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 ia(n){let e=new SyntaxError(n);return e.lineNumber=Dn,e.columnNumber=jt,e}var Qb=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 m of t){let C;typeof m=="string"?C=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(C=String(m)),C!==void 0&&s.indexOf(C)<0&&s.push(C);}}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(m,C){let b=C[m];switch(b!=null&&(typeof b.toJSON5=="function"?b=b.toJSON5(m):typeof b.toJSON=="function"&&(b=b.toJSON(m))),o&&(b=o.call(C,m,b)),b instanceof Number?b=Number(b):b instanceof String?b=String(b):b instanceof Boolean&&(b=b.valueOf()),b){case null:return "null";case true:return "true";case false:return "false"}if(typeof b=="string")return h(b);if(typeof b=="number")return String(b);if(typeof b=="object")return Array.isArray(b)?p(b):f(b)}function h(m){let C={"'":.1,'"':.2},b={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},y="";for(let _=0;_<m.length;_++){let v=m[_];switch(v){case "'":case '"':C[v]++,y+=v;continue;case "\0":if(Fe.isDigit(m[_+1])){y+="\\x00";continue}}if(b[v]){y+=b[v];continue}if(v<" "){let w=v.charCodeAt(0).toString(16);y+="\\x"+("00"+w).substring(w.length);continue}y+=v;}let d=l||Object.keys(C).reduce((_,v)=>C[_]<C[v]?_:v);return y=y.replace(new RegExp(d,"g"),b[d]),d+y+d}function f(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let C=a;a=a+u;let b=s||Object.keys(m),y=[];for(let _ of b){let v=c(_,m);if(v!==void 0){let w=g(_)+":";u!==""&&(w+=" "),w+=v,y.push(w);}}let d;if(y.length===0)d="{}";else {let _;if(u==="")_=y.join(","),d="{"+_+"}";else {let v=`,
59
+ `+a;_=y.join(v),d=`{
60
+ `+a+_+`,
61
+ `+C+"}";}}return i.pop(),a=C,d}function g(m){if(m.length===0)return h(m);let C=String.fromCodePoint(m.codePointAt(0));if(!Fe.isIdStartChar(C))return h(m);for(let b=C.length;b<m.length;b++)if(!Fe.isIdContinueChar(String.fromCodePoint(m.codePointAt(b))))return h(m);return m}function p(m){if(i.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");i.push(m);let C=a;a=a+u;let b=[];for(let d=0;d<m.length;d++){let _=c(String(d),m);b.push(_!==void 0?_:"null");}let y;if(b.length===0)y="[]";else if(u==="")y="["+b.join(",")+"]";else {let d=`,
62
+ `+a,_=b.join(d);y=`[
63
+ `+a+_+`,
64
+ `+C+"]";}return i.pop(),a=C,y}},Zb={parse:Jb,stringify:Qb},e_=Zb,Ti=e_;var im="\xA7SPACE\xA7",sm="\xA7DOUBLE_QUOTES\xA7",am="\xA7QUOTES\xA7",om="SPECIAL_\xA7QUOTES\xA7",um="\xA7CURLY_BRACKETS1\xA7",t_="\xA7INK_VAR\xA7",lm="\xA7CURLY_BRACKETS2\xA7",pn;(y=>{let n=[],e=[];async function t(d,_){for(let v=0;v<n.length;v++)try{let{validation:w}=n[v].opts;if(w instanceof RegExp){if(!w.test(d.join(" ")))continue}else if(w instanceof zod.ZodType&&!w.safeParse(d).success)continue;let D=await n[v].fn(d,_,h);if(D===!0||typeof D=="string")return D}catch{}return false}function r(d,_={name:"custom-command",validation:/^/}){n.unshift({fn:d,opts:_});}y.add=r;function i(){return [...e.map(d=>d.opts),...n.map(d=>d.opts)]}y.info=i;function a(d,_){e.unshift({fn:d,opts:_});}y.addMapper=a;function s(){n.length=0;}y.clear=s;function o(){e.length=0;}y.clearMappers=o;async function u(d,_,v){try{let w=l(d),D=await t(w,v);return D===!0?void 0:typeof D=="string"?(D.startsWith("#")&&(D=D.substring(1)),await y.run(D,_,v)):c(w,_)}catch(w){throw ae.error("Error parsing ink hashtag-command",d),w}}y.run=u;function l(d,_){if(d=d.replaceAll('\\"',sm),d=d.replaceAll("\\'",am),d=d.replaceAll("\\`",om),d=d.replaceAll("\\{",um),d=d.replaceAll("\\}",lm),_?.mergeInkVariables){let O;do O=d,d=d.replace(/\{[^{}:]*\}/g,t_);while(d!==O)}d=d.replaceAll("{"," { "),d=d.replaceAll("}"," } "),d=d.replaceAll(um,"{"),d=d.replaceAll(lm,"}");let v=[],w,D="";for(let O=0;O<d.length;O++){let P=d[O];P==='"'||P==="'"||P==="`"?w===void 0?(v.push(D),D="",w=P,D+=P):w===P?(w=void 0,D+=P,v.push(D),D=""):D+=P:D+=P;}return D!==""&&v.push(D),v.forEach((O,P)=>{P%2===1&&(v[P]=O.replaceAll(" ",im));}),d=v.join(""),v=d.split(" ").filter(O=>O!==""),v=v.map(O=>O.replaceAll(im," ").replaceAll(sm,'"').replaceAll(am,"'").replaceAll(om,"`")),v=p(v),v=v.flatMap(O=>b(O)),v=v.map(O=>O.startsWith('"')&&O.endsWith('"')||O.startsWith("'")&&O.endsWith("'")||O.startsWith("`")&&O.endsWith("`")?O.slice(1,-1):O),v}y.convertTagTolist=l;function c(d,_,v){for(let w of e){let{validation:D}=w.opts,O=false;if(D instanceof RegExp?O=D.test(d.join(" ")):D instanceof zod.ZodType&&(O=D.safeParse(d).success),O)return w.fn(d,_)}v?.silent||ae.error("The operation is not valid",d);}y.convertOperation=c;function h(d){if(d.length===0)return {};if(d.length%2!==0)throw ae.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 _="{";d.forEach((v,w)=>{if(w%2===0)_+=`"${v}": `;else {switch(v){case "null":case "undefined":case "true":case "false":_+=`${v}`;break;default:g(v)?(v=f(v),_+=`"${v}"`):v.startsWith("{")&&v.endsWith("}")?_+=`${v}`:v.startsWith('"')&&v.endsWith('"')?_+=`${v}`:Number.isNaN(parseFloat(v))?_+=`"${v}"`:_+=`${v}`;}w<d.length-1&&(_+=", ");}}),_+="}";try{return Ti.parse(_)}catch(v){throw ae.error("Error parsing ink json",_),v}}y.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 g(d){return !!(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")||d.startsWith("`")&&d.endsWith("`"))}function p(d){return m(d).tokens}y.mergeJsonBlocks=p;function m(d){let _=[],v=false;for(let w=0;w<d.length;w++){let D=d[w];if(D!=="{"){_.push(D);continue}let O=C(d,w);if(O===-1){_.push(D);continue}let P=m(d.slice(w+1,O)),E=["{",...P.tokens,"}"],F=E.join(" ");if(!P.hasInvalidMatchedBlock)try{Ti.parse(F),_.push(F),w=O;continue}catch{}v=true,_.push(...E),w=O;}return {tokens:_,hasInvalidMatchedBlock:v}}function C(d,_){let v=0;for(let w=_;w<d.length;w++)if(d[w]==="{")v++;else if(d[w]==="}"&&(v--,v===0))return w;return -1}function b(d){if(d==="["||d==="]")return [d];let _=0,v=d.length,w=[];for(;_<v&&d[_]==="[";)w.push("["),_++;let D=[];for(;v>_&&d[v-1]==="]";)D.unshift("]"),v--;let O=d.slice(_,v);return O===""?[...w,...D]:[...w,O,...D]}})(pn||={});var cm=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],hm=["+","-","/","*","%","POW","RANDOM","L^"],dm=["INT","FLOOR","FLOAT"];function Nr(n,e){if(n.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(n)&&(n=n.split(".").filter(i=>!i.match(/^[0-9]+$/)).join("."),!n.startsWith(".")))return n.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(n)&&n.includes("g-")){let r=n.split("g-");return Il(e)+"_|_"+"g-"+r[r.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(n);)t++,n=n.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(n)&&e){let r=n.substring(1);return Il(e,t)+"_|_"+r.replaceAll(".","_|_")}return n.replaceAll(".","_|_")||Il(e,t).replaceAll(".","_|_")}function Il(n,e=0){let t=n.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var fm="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function Ut(n){return n.startsWith("^")&&(n=n.substring(1)),n=n.replaceAll("\\\\",fm),n=n.replaceAll("\\n",`
65
+ `),n=n.replaceAll("\\t"," "),n=n.replaceAll(" "," "),n=n.replaceAll(fm,"\\\\"),n}var n_={version:"1.14.0"};var sa=`https://pixi-vn.com/schemas/${n_.version}/schema.json`,pm=["==","!=","<","<=",">",">=","CONTAINS"];function xn(n,e,t,r){let{functions:i}=r;n=n.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return n.forEach(s=>{if(typeof s=="string")switch(s){case "&&":case "||":if(a.length>=2){let o={type:"union",unionType:s==="&&"?"and":"or",conditions:[a[a.length-2],a[a.length-1]]};a.pop(),a.pop(),a.push(o);}break;case "!":if(a.length===0)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"union",unionType:"not",condition:a[a.length-1]};a[a.length-1]=o;}break;case "!?":if(a.length>1){let o={type:"union",unionType:"not",condition:{type:"compare",operator:"CONTAINS",leftValue:a[a.length-2],rightValue:a[a.length-1]}};a.pop(),a.pop(),a.push(o);}else ae.error("Error parsing ink file: Conditional statement is not valid",n);break;default:if(pm.includes(s))if(a.length<2)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {let o={type:"compare",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(hm.includes(s))if(a.length<2)ae.error("Error parsing ink file: Conditional statement is not valid",n);else {s==="L^"&&(s="INTERSECTION");let o={type:"arithmetic",operator:s,rightValue:a[a.length-1],leftValue:a[a.length-2]};a.pop(),a.pop(),a.push(o);}else if(dm.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(Ut(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),u=o.pop(),l=o.pop();if(l===void 0||u===void 0){ae.error("Error parsing ink file: Conditional statement is not valid",n);return}let c=Number(l),h=o.join(".");if(h.includes("^.")){let g=h.split("."),p=g[g.length-1].replaceAll(".","_|_");g.pop(),h=`${g.join(".")}.${p}`,u.includes("c-")&&(h=h+"_|_"+u);}else h=h.replaceAll(".","_|_");let f=Nr(h,e);if(!f)return;a.push({type:"compare",leftValue:kl(f),operator:">=",rightValue:{type:"value",value:c}});}else {let o=Nr(s["CNT?"],e);if(!o)return;a.push(kl(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(er({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],u=i.find(c=>c.name===o);if(!u){ae.error(`Error parsing ink file: Function ${o} is not defined`,n);return}let l=[];for(let c=0;c<u.args;c++)a.length!==0&&l.push(a.pop());a.push({type:"function",functionName:o,args:l.reverse()});}else if(typeof s=="object"&&"^->"in s)s["^->"].includes("$r")||a.push(s["^->"]);else if(typeof s=="object"&&"list"in s){let o=Object.values(s.list).map(u=>u);a.push(o);}else a.push(s);}),a}function Rl(n,e,t,r){return xn(n,e,t,r)}function er(n,e,t){let{key:r,defaultType:i}=n,a=e.indexOf(r);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:i,key:r}}function Ni(n,e,t){let{key:r,value:i,defaultType:a,artmeticValue:s}=n,o=e.indexOf(r);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:i}];if(s){if(typeof i=="object"&&"list"in i){let u=Object.values(i.list).map(l=>l);return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:u}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}else if(typeof i=="object"){if("list"in i&&typeof i.list=="object"){if("origins"in i&&Array.isArray(i.origins)&&i.origins.length>0)return i.origins.reduce(u=>(u.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(t.enums[r])}),Object.entries(t.enums[r]).forEach(([l,c])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${l}`,value:c});}),u),[]);{let u=new Set,l=Object.entries(i.list).reduce((c,[h,f])=>{let[g,p]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:p,value:f}),u.add(g),c},[]);return u.forEach(c=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),r in t.enums?Object.entries(t.enums[r]).forEach(([c,h])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${r}.${c}`,value:h});}):l.push({type:"value",storageOperationType:"set",storageType:a,key:r,value:Object.values(i.list)}),l}}else if(typeof i=="object"&&"VAR?"in i){if(typeof i["VAR?"]=="string"&&i["VAR?"].includes(".")){let[u,l]=i["VAR?"].split(".");if(u in t.enums&&l in t.enums[u])return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:t.enums[u][l]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:er({key:i["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:r,value:i}]}function kl(n){return {type:"value",storageType:"label",storageOperationType:"get",label:n}}function $l(n,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(n)?"call":"jump"}function aa(n,e){if(e){if(typeof e=="string")e.startsWith("^")&&n.push(Ut(e));else if(typeof e=="object"&&"type"in e)switch(e.type){case "value":case "function":console.warn("Warning: trying to add a value or function operation as text. This is likely a mistake, so it will be ignored.");break;default:n.push(e);}}}function Vl(n,e,t,r,i,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:u=false}=a;return i_(n,e,t,r,i,{isNewLine:s,isHashtagScript:o,isThreads:u})}function i_(n,e,t,r,i,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:u}=a;if(o){if(Array.isArray(e)&&e.length>0){let l={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"){let h=e[0],f=pn.convertTagTolist(h),g=pn.convertOperation(f,l,{silent:!0});g&&(g.$origin=h,c.push(g));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),n.push({...l,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&!l.labelToOpen&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}typeof e=="string"?n.push(s_(Ut(e),r.characterIds)):n.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")n.push({end:"game_end"});else if(e==="done")n.push({end:"label_end",goNextStep:true});else if(e==="<>")if(n.length>0){let l=n[n.length-1];l.glueEnabled=true;let c=l.operations!==void 0&&l.dialogue===void 0;l.labelToOpen||(l.goNextStep=c?true:!s),n[n.length-1]=l;}else n.push({glueEnabled:true,goNextStep:true});}else if(typeof e=="object"){if("type"in e)switch(e.type){case "value":e.storageOperationType==="set"?(typeof e.value=="string"&&e.value.startsWith("^")&&(e.value=Ut(e.value)),n.push({goNextStep:true,operations:[e]})):console.warn("Warning: trying to add a value get operation as step. This is likely a mistake, so it will be ignored.");break;case "function":n.push({goNextStep:true,operations:[e]});break;default:if(!s&&n.length>0){let l=n[n.length-1];!l.glueEnabled&&!l.operations&&(l.glueEnabled=true,l.labelToOpen||(l.goNextStep=true)),n[n.length-1]=l;}n.push({conditionalStep:e});}else if("->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let c=n[n.length-1];c.labelToOpen||(c.goNextStep=true),n[n.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)n.push({labelToOpen:{label:er({key:e["->"],defaultType:"storage"},i),type:u?"call":"jump",params:e.params},glueEnabled:l});else {let c=Nr(e["->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:$l(c,u),params:e.params},glueEnabled:l});}}else if("->t->"in e){let l=s?void 0:true;if(l&&t.includes("c-")&&n.length>0&&n[n.length-1]?.dialogue===void 0&&(l=void 0),!s&&n.length>0){let h=n[n.length-1];h.labelToOpen||(h.goNextStep=true),n[n.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=Nr(e["->t->"],t);if(!c)return;n.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:l});}}}function s_(n,e){let t;if(n.includes(": ")){let r=n.split(": "),i=r[0],a=r.slice(1).join(": ");(e?.has(i)||characters.RegisteredCharacters.has(i))&&(t=i,n=a);}return t?{dialogue:{character:t,text:n}}:{dialogue:n}}function jl(n,e,t,r=true,i=false){return a_(n,e,t,r,i)}function a_(n,e,t,r,i=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?n.push(Ut(e)):n.push(e):typeof e=="object"&&"type"in e&&n.push(e));}function oa(n,e,t,r){if(n.length===0){ae.error("Error parsing ink file: Arithmetic statement is not valid",n);return}let i=xn(n,e,t,r);if(i.length===1){let a=i[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function Fr(n,e,t,r="",i,a,s=void 0){let o=[],u="sequential",l=false,c=true;n.forEach(g=>{g==="%"&&(u="loop"),g==="seq"&&(u="random"),g==="MIN"&&(l=true);});let h=n[n.length-1];return Object.keys(h).forEach(g=>{let p=h[g];if(Array.isArray(p)&&p.length>3){p=p.slice(1,p.length-2);let m=[];Pn(p,r,i,m,e,e,t,Ir,s,true,a),m.length===1?o.push(m[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:m});}else Array.isArray(p)&&p.length===3&&(c=false);}),u==="sequential"?{type:"stepswitch",elements:o,choiceType:u,end:c?"lastItem":void 0,nestedId:s}:l&&u==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:u}}function Pn(n,e,t,r=[],i,a,s,o,u=void 0,l=true,c=[]){let h=false,f=[],g=false,p=false,m=false,C=[],b=[];if(t.preDialog[e]&&(l=false,i(r,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),t.preDialog[e].glue&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),delete t.preDialog[e]),n.includes("visit")){let d=Fr(n,a,s,e,t,c,u);d&&(!l&&r.length>0&&i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}));return}let y=n[0];if(y&&typeof y=="object"&&"temp="in y){for(;n[0]&&typeof n[0]=="object"&&"temp="in n[0];)c.push(n[0]["temp="]),n.shift();c=c.reverse();}if(n.forEach((d,_)=>{if(p){if(typeof d=="string"&&d==="/#"){let v=[];Pn(b,e,t,v,jl,jl,s,o,u,l),i(r,v,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),p=false,b=[];}else b.push(d);return}else if(h)if(Array.isArray(d))f.push(d);else if(d&&typeof d=="object")"CNT?"in d?_>0&&n[_-1]==="ev"?(g=true,C.push(d)):g?C.push(d):(f.push(d),l=false):"VAR="in d||"temp="in d?Ni({key:"VAR="in d?d["VAR="]:d["temp="],value:n[_-1],defaultType:"VAR="in d?"storage":"tempstorage"},c,t).forEach(w=>{if(w.value&&typeof w.value=="string"&&w.value==="/str"&&(w.value=n[_-2]),w.value&&typeof w.value=="object"&&"^->"in w.value&&(w.value=w.value["^->"]),f.length>1){let D=oa(f,e,c,t);f=[],D&&typeof D=="object"&&"type"in D&&D.type==="value"&&"storageType"in D&&D.storageType==="logic"&&(w.value=D.operation);}(typeof w.key!="string"||!w.key.includes("$r"))&&(i(r,w,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=true);}):"VAR?"in d?f.push(d):"^->"in d?d["^->"].includes("$r")||f.push(d):("f()"in d||"list"in d&&typeof d.list=="object")&&f.push(d);else switch(d){case "/ev":g&&C.push(d),h=false,f.push(d);break;case "out":if(f.length>0){let v=f[f.length-1];if(v&&typeof v=="object"&&"VAR?"in v){f.pop();let w=er({key:v["VAR?"],defaultType:"storage"},c);i(r,w,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m});}else {let w=[];for(;f.length>0&&f[f.length-1]!=="/ev";)w.push(f.pop());w=w.reverse();let D=oa(w,e,c,t);f=[],D&&typeof D=="object"&&"type"in D&&D.type==="value"&&"storageType"in D&&D.storageType==="logic"?i(r,{storageOperationType:"get",storageType:"logic",operation:D.operation,type:"value"},e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}):(i(r,"<>",e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),D=`^${D}`,i(r,D,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}));}l=false;}break;case "pop":{let v=f[f.length-1];if(v&&typeof v=="object"&&"f()"in v){let w=[];for(;f.length>0&&f[f.length-1]!=="/ev";)w.push(f.pop());w=w.reverse();let D=xn(w,e,c,t);f=[],D.forEach(O=>{O&&typeof O=="object"&&"type"in O&&O.type==="function"?i(r,O,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}):ae.warn("Unhandled case: value is not a function",O);}),l=false;}else f.push(d);return}default:f.push(d);}else if(typeof d=="string")if(d.startsWith("^"))i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=false;else if(d==="ev")h=true;else if(d===`
66
+ `)l=true;else if(d==="done"||d==="end")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=false;else if(d==="<>")i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=false;else if(d==="nop"&&g){let v=mm(C,a,s,e,t,c,u);v&&i(r,v,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),g=false,C=[];}else d==="#"?p=true:d==="thread"&&(m=true);else if(Array.isArray(d))if(g)C.push(d);else if(d.length>1&&typeof d[d.length-2]=="object"&&d[d.length-2]&&"c"in d[d.length-2]&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"b"in d[d.length-1]){f.pop();let v=[],w=[];for(;f.length>0&&f[f.length-1]!=="/ev";)v.push(f.pop());C=[...C,...v.reverse()],g=true,w.push(d.pop()),w.push(d.pop()),C=[...C,...d],C.push(w);}else if(d.length>1&&typeof d[d.length-1]=="object"&&d[d.length-1]&&"#n"in d[d.length-1]){let v=d.pop();if(!v){ae.error("Error parsing ink file: el is undefined");return}let w=v["#n"];delete v["#n"],d.push(v),i(r,{"->":e?e+"_|_"+w:w},e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),s({[w]:d},e,t);}else Pn(d,e,t,r,i,a,s,o,u,l,c);else if(d&&typeof d=="object")if("->"in d&&typeof d["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->"])){let v=[];f.length>0&&(v=Rl(["ev",...f],e,c,t)),d.params=v,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=false;}else if("->t->"in d&&typeof d["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(d["->t->"])){let v=[];f.length>0&&(v=Rl(["ev",...f],e,c,t)),d.params=v,i(r,d,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m}),l=false;}else if("*"in d&&typeof d["*"]=="string")d["*"].includes("c")&&(f.push(d),l=false);else if("s"in d&&Array.isArray(d.s))f.push(d),l=false;else if("CNT?"in d)f.push(d),l=false;else if("VAR="in d||"temp="in d){let v="VAR="in d?d["VAR="]:d["temp="],w,D=[];if(v!=="$r"){for(f.pop(),f[f.length-1]==="/ev"&&f.pop();f.length>0&&f[f.length-1]!=="/ev";)D.push(f.pop());D=D.reverse(),w=oa(D,e,c,t),f=[],Ni({key:v,value:w,defaultType:"VAR="in d?"storage":"tempstorage",artmeticValue:true},c,t).forEach(P=>{(P.value!==void 0||P.value!==null)&&i(r,P,e,t,c,{isNewLine:l,isHashtagScript:p,isThreads:m});}),l=false;}}else s(d,e,t);}),o(f,r,e,t,c),e.includes("_|_")&&r.length===2){let d=r[0],_=r[1];d&&_&&typeof d=="object"&&"dialogue"in d&&typeof _=="object"&&"labelToOpen"in _&&d.dialogue===" "&&_.labelToOpen&&(r.shift(),delete _.glueEnabled,r[0]=_);}}function ql(n,e,t,r,i,a){if(e.length===0)return;let s=xn(e,r,t,i);if(s.length===1){let o={type:"ifelse",condition:s[0],then:n,else:a};return o.else||delete o.else,o}else if(s.length>1){let o={type:"ifelse",condition:{type:"union",unionType:"and",conditions:s},then:n,else:a};return o.else||delete o.else,o}}function mm(n,e,t,r,i,a,s=void 0){if(n.length===0){ae.error("Error parsing ink file: Conditional statement is not valid",n);return}let o=[],u=[];if(n.forEach(h=>{Array.isArray(h)?u.push(h):typeof h=="string"&&h==="du"?i.du?o.push(i.du):i.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),u.length===0){ae.error("Error parsing ink file: Conditional statement is not valid",u);return}let l=Ll(u[0],e,t,`${r}${"_|_"}then`,i,a,`${s||""}then`),c;return u.length===2?c=Ll(u[1],e,t,`${r}${"_|_"}else`,i,a,`${s||""}else`):u.length>2?(u.shift(),u.push("nop"),u=[{b:u}],c=Ll(u,e,t,r,i,a,`${s||""}else`)):c=void 0,i.du=void 0,ql(l,o,a,r,i,c)}function Ll(n,e,t,r,i,a,s=void 0){let o=[];for(let l of n)typeof l=="object"&&"b"in l&&(l.b=l.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),Pn(l.b,r,i,o,e,e,t,Ir,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Bl(n="",e=""){let t=Array.isArray(n)?n:[n],r=Array.isArray(e)?e:[e];return [...new Set([...t,...r])]}function Ir(n,e,t,r,i){if(n.length>0){let a={};gm(n,a,i,r);for(let[s,o]of Object.entries(a)){let u=t+"_|_"+s,l={text:o.text.length===1?o.text[0]:o.text,label:u,props:{},type:$l(u,false),oneTime:o.onetime};o.text.length===0&&(l.onlyHaveNoChoice=true,l.autoSelect=true),l.oneTime===false&&delete l.oneTime;let c=ql(l,o.conditions,i,t,r)||l,h=e[e.length-1];if(typeof h=="object"&&h&&"type"in h&&(h={conditionalStep:h}),e.length>0&&typeof h=="object"&&h&&"choices"in h&&h.choices){let f=h.choices;f&&Array.isArray(f)?f.push(c):ae.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),h.choices=f.sort((g,p)=>{try{let m=g.label.split("."),C=m[m.length-1].replaceAll(".","_|_"),b=p.label.split("."),y=b[b.length-1].replaceAll(".","_|_");if(C.includes("c-")&&y.includes("c-")){let d=C.split("c-")[1],_=Number(d),v=y.split("c-")[1],w=Number(v);return _-w}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(r.preDialog[u]={...o.preDialog});}}}function gm(n,e,t,r,i){let a=[],s="",o="",u=false,l=[];for(let c=0;c<n.length;c++){let h=n[c];if(typeof h=="string")h.startsWith("^")?a.push(Ut(h)):cm.includes(h)&&l.push(h);else if(Array.isArray(h)&&h.includes("visit")){let f=Fr(h,aa,(g,p,m)=>{},i,r,t);a.push(f);}else if(h&&typeof h=="object")if("*"in h&&typeof h["*"]&&typeof h["*"]=="string")h["*"].includes("c")&&(s=`c${h["*"].split("c")[1]}`,h.flg&16&&(u=true));else if("s"in h&&Array.isArray(h.s)){let f=ym(h.s),g=h.s.includes("<>");f&&(i&&e[i]?(e[i].preDialog={text:f,glue:g},e[i].text=Bl(f,e[i].text)):(a.push(f),o=f));}else ("CNT?"in h||"VAR?"in h)&&l.push(h);else l.push(h);if(s){e[s]?e[s].text=Bl(a,e[s].text):e[s]={text:a,onetime:u,conditions:l},o&&(e[s].preDialog={text:o,glue:false});let f=n.slice(c+1);gm(f,e,t,r,s);return}}}function ym(n){for(let e of n)if(typeof e=="string"){if(e.startsWith("^"))return Ut(e)}else if(Array.isArray(e)){let t=ym(e);if(t)return t}}var Ml;(i=>{function n(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:u=[],enums:l={},functions:c=[],preDialog:h={},characterIds:f}=s,g={$schema:sa};if(g.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:u,enums:l,functions:c,preDialog:h,characterIds:f}),g.labels&&ta in g.labels){let p=g.labels[ta];delete g.labels[ta],p.forEach(m=>{m.operations&&(g.initialOperations=g.initialOperations?[...g.initialOperations,...m.operations]:[...m.operations]);});}if(g.labels&&Yn in g.labels){let p=g.labels[Yn];delete g.labels[Yn],p.forEach(m=>{m.operations&&(g.initialOperations=g.initialOperations?[...g.initialOperations,...m.operations]:[...m.operations]);});}return o.forEach(p=>{g.labels&&p in g.labels&&delete g.labels[p];}),u.forEach(p=>{g.initialOperations&&(g.initialOperations=g.initialOperations.filter(m=>!(m.type==="value"&&m.key===p)));}),g}i.inkToJson=n;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){ae.error("Error parsing ink file",o);}}function t(a,s,o){for(let u of a)if(u)if(Array.isArray(u))if(u.includes("visit")){let l=Fr(u,aa,(c,h,f)=>{},"",o,[]);l&&(o.externalSwitch=l);}else t(u,s,o);else typeof u=="object"&&(u&&"VAR="in u&&o.externalSwitch&&(s[Yn]||(s[Yn]=[]),s[Yn].push({operations:Ni({defaultType:"storage",key:u["VAR="],value:o.externalSwitch},[],o)})),r(u,s,"",o));}function r(a,s,o="",u){if(a!==null){for(let[l,c]of Object.entries(a))if(Array.isArray(c)){let h=[],f={},g=(o?o+"_|_":"")+l;Pn(c,g,u,h,Vl,Vl,(p,m,C)=>{r(p,f,m,C);},Ir);for(let[p,m]of Object.entries(f))s[p]=m;h.length>0&&(s[g]=h);}}}})(Ml||={});var Pp=An(Uy()),SC=An(wv()),EC=An(yC()),wC=An(pr()),eF=/(?:^|<>)\s*#\s*([^\r\n]+)/g,tF=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,nF=new Set(["DONE","END"]),rF="_|_",vC=new Map;function AC(n,e){let t=JSON.stringify([e,n]),r=vC.get(t);if(r)return r;let i=new RegExp(n,e);return vC.set(t,i),i}function zs(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(s=>zs(n,s));let i=t.oneOf;if(Array.isArray(i))return i.some(s=>zs(n,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>zs(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(!AC(t.pattern,"").test(n))return !1}catch{return false}return true}function dl(n,e){if(!e||typeof e!="object")return false;let t=e,r=t.anyOf;if(Array.isArray(r))return r.some(o=>dl(n,o));let i=t.oneOf;if(Array.isArray(i))return i.some(o=>dl(n,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>dl(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(!zs(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=>zs(o,t.items))}function Ap(n,e){if(e.type==="regexp")try{let t=AC(e.source,e.flags);return t.lastIndex=0,t.test(n.join(" "))}catch{return false}return e.type==="literal"?n.join(" ")===e.value:dl(n,e.schema)}function fl(n){if(!n||typeof n!="object")return [];let e=n;if(Array.isArray(e.anyOf))return e.anyOf.flatMap(fl);if(Array.isArray(e.oneOf))return e.oneOf.flatMap(fl);if(Array.isArray(e.allOf)){let t={};for(let r of e.allOf)r&&typeof r=="object"&&Object.assign(t,r);return fl(t)}return e.type==="array"&&Array.isArray(e.prefixItems)?[e]:[]}function CC(n,e){if(n===e)return 1;let t=Math.max(n.length,e.length);return t===0?1:Math.max(0,1-DC(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*CC(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=>CC(n,i))))}}return {weight:1,matched:n===void 0?0:1}}function sF(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 aF=.8,bC=new Map;function oF(n){let e=JSON.stringify(n),t=bC.get(e);if(t)return t;let r=new SC.default({strict:false,allErrors:true}).compile(n);return bC.set(e,r),r}function uF(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 lF(n,e){let[t]=yl(n.instancePath);if(t!==void 0&&/^\d+$/.test(t)){let r=Number(t);if(r<e.length)return e[r]}return Op(n)}function cF(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 Dp(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(eF)){let s=(a[1]??"").trim();if(!s)continue;let o=pn.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:r+1,command:s,tokens:o});}}return t}function Op(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 DC(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 hF(n,e){let t,r=1/0;for(let a of e){let s=DC(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 dF(n,e){if(n.keyword==="additionalProperties"&&typeof n.params?.additionalProperty=="string"){let t=n.params.additionalProperty,r=e&&hF(t,e),i=r?` (did you mean "${r}"?)`:"";return `has an unrecognised property "${t}"${i}`}return n.message??"invalid value"}function yl(n){return n.split("/").filter(Boolean).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~"))}function fF(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 yl(e)){if(t===null||typeof t!="object")break;t=t[a],i(t);}return r}function pF(n,e){let t=yl(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 ml(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]),ml(e[i[1]],e,t))}function gl(n,e){let t=ml(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=gl(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 _C(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 mF(n,e){let t=n.definitions??{},r=[];for(let[i,a]of Object.entries(t)){let s=gl(a,t);if(!s)continue;let o=s.properties.type;o&&typeof o=="object"&&("const"in o||Array.isArray(o.enum))&&_C(o,e.type)&&_C(s.properties.operationType,e.operationType)&&r.push(i);}return r}function gF(n,e,t){let r=n.definitions??{},i={definitions:r,...r[e]},a=new Pp.default({strict:false,allErrors:true}).compile(i);return a(t)?[]:a.errors??[]}function yF(n,e,t){let r=n.definitions??{},i=ml(r[e],r);for(let a of yl(t)){let o=gl(i,r)?.properties[a];if(o===void 0)return [];i=ml(o,r);}return Object.keys(gl(i,r)?.properties??{})}function pl(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=`${Op(o)}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}function xp(n,e,t){return n.map(r=>({instancePath:r.instancePath||"(root)",element:Op(r),message:dF(r,t?.(r)),origin:fF(e,r.instancePath)}))}function vF(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?pF(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=xp(pl(u),e);for(let[c,h]of o){let f=s?mF(s,h.node):[],g=f.length===1?f[0]:void 0;if(!g||!s){l.push(...xp(pl(h.errors),e));continue}let m=pl(gF(s,g,h.node)).map(C=>({...C,instancePath:`${c}${C.instancePath}`}));l.push(...xp(m,e,C=>yF(s,g,C.instancePath.slice(c.length))));}return l}var Ht;(h=>{function n(f,g={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let p=[];try{return {json:new EC.Compiler(f,{errorHandler:(y,d)=>{let _=y.replace(/^[A-Z]+: line \d+: ?/,""),v=y.match(/line (\d+)/);p.push({message:_,type:d,line:v?Number(v[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:y=>y,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:p}}catch{let C=false,b={...g,textSource:f};return e(p,()=>{C=true;},b),C?n(b.textSource,g):{issues:p}}}h.compile=n;function e(f,g,p){let{functions:m,initialVarsToRemove:C,labelToRemove:b}=p,y=f.find(d=>d.type===wC.ErrorType.Error);if(y){if(y.message.includes("Divert target not found")){let d=y.message.match(/Divert target not found: '-> (\w+)'/);if(d?.[1]){let _=d[1],v=`
67
+
68
+ === ${_} ===
69
+
70
+ -> DONE`;return p.textSource=p.textSource.concat(v),b.push(_),g()}}if(y.message.includes("Unresolved variable")){let d=y.message.match(/Unresolved variable: (\w+)/);if(d?.[1]){let _=d[1],v=`VAR ${_} = ""
71
+
72
+ `;return p.textSource=v.concat(p.textSource),C.push(_),g()}}if(y.message.includes("Variable could not be found to assign to")){let d=y.message.match(/Variable could not be found to assign to: (\w+)/);if(d?.[1]){let _=d[1],v=`VAR ${_} = ""
73
+
74
+ `;return p.textSource=v.concat(p.textSource),C.push(_),g()}}if(y.message.includes("Variable could not be found to assign to")){let d=y.message.match(/Variable could not be found to assign to: '(\w+)'/);if(d?.[1]){let _=d[1],v=`VAR ${_} = ""
75
+
76
+ `;return p.textSource=v.concat(p.textSource),C.push(_),g()}}if(y.message.includes("Function call target not found")){let d=y.message.match(/Function call target not found: '-> (\w+)'/);if(d?.[1]){let _=d[1],v=`
77
+
78
+ === function ${_}() ===
79
79
 
80
80
  ~ return
81
81
 
82
- `;return f.textSource=f.textSource.concat(C),m.push({name:v,args:0}),_.push(v),g()}}if(y.message.includes(" arguments, but got ")){let p=y.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(p?.[1]){let v=p[1],C=parseInt(p[3]||"0",10),S=C>0?Array.from({length:C},(A,E)=>`arg${E+1}`).join(", "):"",D=`
82
+ `;return p.textSource=p.textSource.concat(v),m.push({name:_,args:0}),b.push(_),g()}}if(y.message.includes(" arguments, but got ")){let d=y.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);if(d?.[1]){let _=d[1],v=parseInt(d[3]||"0",10),w=v>0?Array.from({length:v},(P,E)=>`arg${E+1}`).join(", "):"",D=`
83
83
 
84
- === function ${v}(${S}) ===
84
+ === function ${_}(${w}) ===
85
85
 
86
86
  ~ return
87
87
 
88
- `;f.textSource=f.textSource.replaceAll(`
88
+ `;p.textSource=p.textSource.replaceAll(`
89
89
 
90
- === function ${v}() ===
90
+ === function ${_}() ===
91
91
 
92
92
  ~ return
93
93
 
94
- `,""),f.textSource=f.textSource.concat(D);let O=m.find(A=>A.name===v);return O?O.args=C:(m.push({name:v,args:C}),_.push(v)),g()}}if(y.message.includes("Could not find target for read count")){let p=y.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(p?.[1]){let v=p[1],[C,S]=v.split("."),D=`
94
+ `,""),p.textSource=p.textSource.concat(D);let O=m.find(P=>P.name===_);return O?O.args=v:(m.push({name:_,args:v}),b.push(_)),g()}}if(y.message.includes("Could not find target for read count")){let d=y.message.match(/Could not find target for read count: -> (\w+\.\w+)/);if(d?.[1]){let _=d[1],[v,w]=_.split("."),D=`
95
95
 
96
- LIST ${C} = ${S}
96
+ LIST ${v} = ${w}
97
97
 
98
- `;return f.textSource=f.textSource.concat(D),f.initialVarsToRemove.push(C),f.initialVarsToRemove.push(`${C}.${S}`),g()}}if(y.message.includes("variable for increment could not be found")){let p=y.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(p?.[1]){let v=p[1],C=`VAR ${v} = 0
98
+ `;return p.textSource=p.textSource.concat(D),p.initialVarsToRemove.push(v),p.initialVarsToRemove.push(`${v}.${w}`),g()}}if(y.message.includes("variable for increment could not be found")){let d=y.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(d?.[1]){let _=d[1],v=`VAR ${_} = 0
99
99
 
100
- `;return f.textSource=C.concat(f.textSource),f.initialVarsToRemove.push(v),g()}}return d.forEach(p=>{let v=p.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);v?.[1]&&(p.message=`The function '${v[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,g){return Sp(d).filter(({tokens:f})=>!g.some(({validation:m})=>_p(f,m)))}h.getUnknownHashtagCommands=t;function r(d,g){let f=g.filter(b=>b.validation.type==="zod");if(f.length===0)return [];let m=[];for(let b of Sp(d)){if(g.some(({validation:p})=>_p(b.tokens,p)))continue;let _;for(let p of f)for(let v of dl(p.validation.schema)){let{score:C,hasDiscriminant:S}=nF(b.tokens,v);S&&(!_||C>_.score)&&(_={command:p,branch:v,score:C});}if(!_||_.score<rF)continue;let y=iF(sF(_.branch));if(!y(b.tokens))for(let p of fl(y.errors??[]))m.push({line:b.line,command:b.command,handlerName:_.command.name,instancePath:p.instancePath||"(root)",element:aF(p,b.tokens),message:oF(p),score:_.score});}return m}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(d,g){let f=new Set;for(let p of d.matchAll(QN))p[1]&&f.add(p[1]);let m=new Set(g),b=new Set,_=d.split(/\r?\n/),y=[];for(let p=0;p<_.length;p++){let v=(_[p]??"").replace(/\/\/.*$/,"");for(let C of v.matchAll(/->[ \t]+(\w[\w.]*)/g)){let S=C[1];if(!S)continue;let D=S.split(".")[0]??S;ZN.has(D)||f.has(D)||m.has(S)||m.has(S.replaceAll(".",eF))||m.has(D)||b.has(S)||(b.add(S),y.push({line:p+1,target:S}));}}return y}h.getUnknownDivertTargets=i;function a(d){return new wp.default({strict:false,allErrors:true}).compile(d)}h.getSchemaValidator=a;function s(d,g){let f=typeof g=="function"?g:a(g);return f(d)?[]:mF(f.errors??[],d,f.schema)}h.validateAgainstJsonSchema=s;function o(d,g){let f=new Set,m=[];for(let p of g){let v=u(p);v!==void 0?m.push(v):f.add(String(p));}m.sort((p,v)=>v-p);let b=[],_=d.length;for(let p=d.length-1;p>=0;p--)f.has(d[p])&&(b.push({key:d[p],sectionTokens:d.slice(p+1,_)}),_=p);b.reverse();let y=[];for(let p of m)p<0||p>=_||(y.push({key:p,sectionTokens:d.slice(p,_)}),_=p-1);return y.reverse(),[...y,...b]}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,g){let f=o(d,Object.keys(g)),m=[];for(let{key:b,sectionTokens:_}of f){let y;try{y=mn.convertListStringToObj(_);}catch(v){m.push({key:b,instancePath:"(root)",element:String(b),message:`could not parse "${b}" section into key/value pairs: ${v instanceof Error?v.message:String(v)}`});continue}let p=s(y,g[b]);m.push(...p.map(v=>({...v,key:b})));}return m}h.validateKeyedJsonSchemas=l;function c(d,g){let f=[];for(let m of Sp(d)){let b=g.find(({validation:y})=>_p(m.tokens,y));if(!b?.keySchemas)continue;let _=l(m.tokens,b.keySchemas);f.push(..._.map(y=>({...y,line:m.line,command:m.command})));}return f}h.getHashtagKeySchemaIssues=c;})(Ht||={});var Dp=wn(dr());function AC(n){if(!n||n.length===0)return;let e=new Set;for(let t of n){let r=typeof t=="string"?t:t?.id;typeof r=="string"&&r.length>0&&e.add(r);}return e.size>0?e:void 0}function Hs(n,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:n},{json:r,issues:i}=Ht.compile(n,t);if(i.forEach(({message:s,type:o})=>{o===Dp.ErrorType.Error?ae.error(`Ink compilation error: ${s}`):o===Dp.ErrorType.Warning?ae.warn(`Ink compilation warning: ${s}`):ae.info(`Ink compilation info: ${s}`);}),!r){ae.error("No JSON generated from ink file");return}let a;try{a=xi.parse(r);}catch{ae.error("Error parsing ink file");return}return t.enums=a.listDefs||{},ql.inkToJson(a,{...t,characterIds:AC(e.characters)})}var ot;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(ot||={});var se=class ue{static init(e){e.loadAssets&&(ue._loadAssets=e.loadAssets),e.soundOperation&&(ue._soundOperation=e.soundOperation),e.imageOperation&&(ue._imageOperation=e.imageOperation),e.videoOperation&&(ue._videoOperation=e.videoOperation),e.imageContainerOperation&&(ue._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(ue._textOperation=e.textOperation),e.canvasElementOperation&&(ue._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(ue._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(ue._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(ue._narrationOperation=e.narrationOperation),e.effectOperation&&(ue._effectOperation=e.effectOperation),e.animateOperation&&(ue._animateOperation=e.animateOperation),e.canvasOperation&&(ue._canvasOperation=e.canvasOperation),e.getLogichValue&&(ue._getLogichValue=e.getLogichValue),e.getConditionalStep&&(ue._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return ue._loadAssets}static _soundOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return ue._soundOperation}static _imageOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return ue._imageOperation}static _videoOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return ue._videoOperation}static _imageContainerOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return ue._imageContainerOperation}static _textOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return ue._textOperation}static _canvasElementOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return ue._canvasElementOperation}static _setStorageValue=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return ue._setStorageValue}static _setInitialStorageValue=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return ue._setInitialStorageValue}static _narrationOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return ue._narrationOperation}static _effectOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return ue._effectOperation}static _animateOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return ue._animateOperation}static _canvasOperation=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return ue._canvasOperation}static _getLogichValue=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return ue._getLogichValue}static _getConditionalStep=()=>{throw ot.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return ue._getConditionalStep}};var Ar;(n=>{n.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(l,c){e.unshift({fn:l,opts:c});}n.add=t;function r(l){let c=e.findIndex(h=>h.fn===l);c!==-1&&e.splice(c,1);}n.remove=r;function i(){return e.map(l=>l.opts)}n.info=i;function a(l,c){let h=e.filter(d=>(d.opts.type??"after-translation")===c.type);for(let d of h)l=u(l,d.fn,d.opts.validation);return l}n.replace=a;function s(l){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)l=o(l,h.fn,h.opts);return l}n.runI18nPreStep=s;function o(l,c,h){let{validation:d}=h,g=new RegExp(n.options.replaceRegex.source,"g"),f=[...l.matchAll(g)],m=new Set,b=[];for(let _ of f)m.has(_[1])||(m.add(_[1]),b.push(_[1]));for(let _ of b){if(d==="characterId"){if(!characters.RegisteredCharacters.has(_))continue}else if(d!=="all"){if(d instanceof RegExp){if(!d.test(_))continue}else if(d instanceof zod.ZodType&&!d.safeParse(_).success)continue}c(_)!==void 0&&(l.includes(`{{[${_}]}}`)||(l=l.replaceAll(`[${_}]`,`{{[${_}]}}`)));}return l}function u(l,c,h){let d=new RegExp(n.options.replaceRegex.source,"g"),g=[...l.matchAll(d)],f=new Set,m=[];for(let b of g)f.has(b[1])||(f.add(b[1]),m.push(b[1]));for(let b of m){if(h==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(b))continue}else if(h instanceof zod.ZodType&&!h.safeParse(b).success)continue}let _=c(b);_!==void 0&&(l=l.replaceAll(`[${b}]`,_));}return l}})(Ar||={});function gF(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=se.getLogichValue(r,e);t+=`${i}`;}}),t}var PC;(n=>{let e=u=>u;function t(u){return Array.isArray(u)?u.map(l=>r(`${l}`)):r(`${u}`)}n.t=t;function r(u){let l=u;return n.beforeToTranslate&&(l=(0, n.beforeToTranslate)(l)),l=Ar.replace(l,{type:"before-translation"}),l=e(l),n.afterToTranslate&&(l=(0, n.afterToTranslate)(l)),l=Ar.replace(l,{type:"after-translation"}),l}n.translate=r;function i(u){e=u;}n.setTranslate=i;function a(u,l,c){let{defaultValue:h="empty_string"}=c;typeof l=="string"&&(l=[l]),Array.isArray(l)&&l.forEach(d=>{let g=d;if(n.beforeToTranslate&&(g=(0, n.beforeToTranslate)(g)),h==="empty_string")u[g]===void 0&&(u[g]="");else if(h==="copy_key"){let f=d;n.beforeToTranslate&&(f=(0, n.beforeToTranslate)(f));let m=Ar.runI18nPreStep(f);m=Ar.replace(m,{type:"before-translation"}),u[g]=m;}});}function s(u,l=[]){if(typeof u=="object"&&u&&"type"in u)if(u.type==="ifelse")u.then&&s(u.then,l),u.else&&s(u.else,l);else if(u.type==="stepswitch"){if(u.elements)if(Array.isArray(u.elements))u.elements.forEach(c=>{s(c,l);});else if(u.elements.type==="ifelse"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else if(u.elements.type==="stepswitch"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else s(u.elements,l);}else u.type==="resulttocombine"?(u.firstItem&&s(u.firstItem,l),u.secondConditionalItem&&u.secondConditionalItem.forEach(c=>{s(c,l);})):l.push(u);else u&&l.push(u);return l}async function o(u,l={},c={}){let{defaultValue:h="copy_key",operationStringConvert:d}=c,g=u.map(async f=>{if(f.choices){let m=[];Array.isArray(f.choices)?m=[f.choices]:m=s(f.choices),m.forEach(b=>{b.forEach(_=>{if("type"in _){let y=[];_.type==="ifelse"||_.type==="stepswitch"?s(_,y):y=[_],y.map(p=>s(p.text)).forEach(p=>{Array.isArray(p)&&p.forEach(v=>{Array.isArray(v)?v.forEach(C=>{typeof C=="string"?a(l,C,{defaultValue:h}):s(C).forEach(S=>{Array.isArray(S)?S.forEach(D=>{typeof D=="string"&&a(l,D,{defaultValue:h});}):typeof S=="string"&&a(l,S,{defaultValue:h});});}):typeof v=="string"&&a(l,v,{defaultValue:h});});});}});});}if(f.dialogue){let m=[];Array.isArray(f.dialogue)?m=[f.dialogue]:m=s(f.dialogue),m.forEach(b=>{if(typeof b=="string")a(l,b,{defaultValue:h});else if("text"in b){let _=s(b.text);typeof _=="string"&&(_=[_]),_.forEach(y=>{typeof y=="string"?a(l,y,{defaultValue:h}):s(y).forEach(p=>{typeof p=="string"?a(l,p,{defaultValue:h}):Array.isArray(p)&&p.forEach(v=>{typeof v=="string"?a(l,v,{defaultValue:h}):s(v).forEach(C=>{typeof C=="string"&&a(l,C,{defaultValue:h});});});});});}});}if(f.operations)for(let m of f.operations){if(m.type==="operationtoconvert"&&d){let b=gF(m),_=await d(b,f,{});if(!_)return;m=_;}m.type==="text"&&m.operationType==="show"&&a(l,m.text,{defaultValue:h});}f.conditionalStep&&s(f.conditionalStep).forEach(m=>{Array.isArray(m)?o(m,l,c):o([m],l,c);});});return await Promise.all(g),l}n.generateJsonTranslation=o;})(PC||={});var Js=PC;var Pe;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Pe||={});var vF="___param___",CF=class le{static init(e){e.loadAssets&&(le._loadAssets=e.loadAssets),e.soundOperation&&(le._soundOperation=e.soundOperation),e.imageOperation&&(le._imageOperation=e.imageOperation),e.videoOperation&&(le._videoOperation=e.videoOperation),e.imageContainerOperation&&(le._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(le._textOperation=e.textOperation),e.canvasElementOperation&&(le._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(le._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(le._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(le._narrationOperation=e.narrationOperation),e.effectOperation&&(le._effectOperation=e.effectOperation),e.animateOperation&&(le._animateOperation=e.animateOperation),e.canvasOperation&&(le._canvasOperation=e.canvasOperation),e.getLogichValue&&(le._getLogichValue=e.getLogichValue),e.getConditionalStep&&(le._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return le._loadAssets}static _soundOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return le._soundOperation}static _imageOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return le._imageOperation}static _videoOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return le._videoOperation}static _imageContainerOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return le._imageContainerOperation}static _textOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return le._textOperation}static _canvasElementOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return le._canvasElementOperation}static _setStorageValue=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return le._setStorageValue}static _setInitialStorageValue=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return le._setInitialStorageValue}static _narrationOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return le._narrationOperation}static _effectOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return le._effectOperation}static _animateOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return le._animateOperation}static _canvasOperation=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return le._canvasOperation}static _getLogichValue=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return le._getLogichValue}static _getConditionalStep=()=>{throw Pe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return le._getConditionalStep}};function bF(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>CF.getLogichValue(i,e));return t(...r)}else Pe.warn(`getLogichValue function ${n.functionName} not found in props`);}}function OC(n,e={}){let t=TC(n,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return SF(t,e);case "arithmetic":case "arithmeticsingle":return _F(t,e);case "compare":case "union":return EF(t,e);case "function":return bF(t,e)}return t}function _F(n,e){let t=se.getLogichValue(n.leftValue,e);switch(n.type){case "arithmetic":{let r=se.getLogichValue(n.rightValue,e);switch(n.operator){case "*":return t*r;case "/":return t/r;case "+":return typeof t=="string"||typeof r=="string"?`${t}${r}`:Array.isArray(t)&&Array.isArray(r)?[...t,...r]:Array.isArray(t)?[...t,r]:Array.isArray(r)?[t,...r]:t+r;case "-":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>!r.includes(i));if(Array.isArray(t))return t.filter(i=>i!==r);if(Array.isArray(r)){Pe.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-r;case "%":return t%r;case "POW":return t**r;case "RANDOM":return narration.narration.getRandomNumber(t,r);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>r.includes(i));Pe.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:Pe.warn("getValueFromArithmeticOperations unknown operator",n);return}}case "arithmeticsingle":switch(n.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function SF(n,e){if(n&&typeof n=="object"&&"type"in n&&n.type==="value"&&n.storageOperationType==="get")switch(n.storageType){case "storage":case "tempstorage":return n.key==="_input_value_"?narration.narration.input.value:storage.storage.get(n.key);case "flagStorage":return storage.storage.flags.get(n.key);case "label":return narration.narration.queries.timesLabelOpened(n.label);case "choice":return narration.narration.queries.timesChoiceMade(n.index);case "logic":return se.getLogichValue(n.operation,e);case "params":{let t=storage.storage.get(`${vF}${narration.narration.labels.opened.length-1}`)||[];if(t&&t.length>n.key)return t[n.key];Pe.warn("getValue params not found");return}}return n}function EF(n,e){if(!n)return false;if(typeof n!="object"||!("type"in n))return !!n;switch(n.type){case "compare":{let t=se.getLogichValue(n.leftValue,e),r=se.getLogichValue(n.rightValue,e);switch(n.operator){case "==":return Array.isArray(t)&&Array.isArray(r)?t.length===r.length&&t.every(i=>r.includes(i)):t===r;case "!=":return Array.isArray(t)&&Array.isArray(r)?t.length!==r.length||!t.every(i=>r.includes(i)):t!==r;case "<":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<0:Array.isArray(t)&&Array.isArray(r)?t.length<r.length:t<r;case "<=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<=0:Array.isArray(t)&&Array.isArray(r)?t.length<=r.length:t<=r;case ">":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>0:Array.isArray(t)&&Array.isArray(r)?t.length>r.length:t>r;case ">=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>=0:Array.isArray(t)&&Array.isArray(r)?t.length>=r.length:t>=r;case "CONTAINS":return Array.isArray(t)&&Array.isArray(r)?r.every(i=>t.includes(i)):Array.isArray(t)?t.includes(r):t.toString().includes(r.toString())}break}case "value":{let t=se.getLogichValue(n,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return wF(n,e)}return !!n}function wF(n,e){if(n.unionType==="not"){let r=OC(n.condition,e);return Array.isArray(r)?r.length===0:r&&typeof r=="object"?Object.keys(r).length===0:!r}let t=r=>se.getLogichValue(r,e)||false;return n.unionType==="and"?n.conditions.every(t):n.conditions.some(t)}function AF(n,e){return Math.floor(Math.random()*(e-n+1)+n)}function TC(n,e={}){if(Array.isArray(n)||!n)return n;if(n&&typeof n=="object"&&"type"in n)switch(n.type){case "resulttocombine":return DF(n,e);case "ifelse":return se.getLogichValue(n.condition,e)?se.getLogichValue(n.then,e):se.getLogichValue(n.else,e);case "stepswitch":{let t=se.getLogichValue(n.elements,e)||[];if(t.length===0){Pe.error("getValueFromConditionalStatements elements.length === 0");return}switch(n.choiceType){case "random":{let r=AF(0,t.length-1);return se.getLogichValue(t[r],e)}case "loop":{let r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return r>t.length-1?(r=r%t.length,se.getLogichValue(t[r],e)):se.getLogichValue(t[r],e)}case "sequential":{let r,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return n.end==="lastItem"&&(r=se.getLogichValue(t[t.length-1],e)),i>t.length-1?r:se.getLogichValue(t[i],e)}case "sequentialrandom":{let r=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:n.nestedId,onceOnly:true});if(r===void 0&&n.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(n.nestedId);if(!i?.usedRandomNumbers){Pe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return se.getLogichValue(t[a[a.length-1]],e)}if(r===void 0){Pe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return se.getLogichValue(t[r],e)}}}}return n}function Pp(n,e={}){if(n.conditionalStep){let t=pixiVn.createExportableElement(se.getLogichValue(n.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let r={...n,conditionalStep:void 0,...t};return Pp(r,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return n}function DF(n,e){let t=n.firstItem,r=(n.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>se.getLogichValue(s,e)):[se.getLogichValue(a,e)]),i=t?[t,...r]:r;if(i.length===0){Pe.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return Js.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,u=a.map((y,p)=>{y=Pp(y,e);let v=se.getLogichValue(y.dialogue,e)||"";return p===0?(s=se.getLogichValue(y.glueEnabled,e)||false,v):(typeof v=="object"&&"text"in v&&(v=`${v.character}: ${v.text}`),s===false&&o&&(v=`
100
+ `;return p.textSource=v.concat(p.textSource),p.initialVarsToRemove.push(_),g()}}return f.forEach(d=>{let _=d.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);_?.[1]&&(d.message=`The function '${_[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,g){return Dp(f).filter(({tokens:p})=>!g.some(({validation:m})=>Ap(p,m)))}h.getUnknownHashtagCommands=t;function r(f,g){let p=g.filter(C=>C.validation.type==="zod");if(p.length===0)return [];let m=[];for(let C of Dp(f)){if(g.some(({validation:d})=>Ap(C.tokens,d)))continue;let b;for(let d of p)for(let _ of fl(d.validation.schema)){let{score:v,hasDiscriminant:w}=sF(C.tokens,_);w&&(!b||v>b.score)&&(b={command:d,branch:_,score:v});}if(!b||b.score<aF)continue;let y=oF(uF(b.branch));if(!y(C.tokens))for(let d of pl(y.errors??[]))m.push({line:C.line,command:C.command,handlerName:b.command.name,instancePath:d.instancePath||"(root)",element:lF(d,C.tokens),message:cF(d),score:b.score});}return m}h.getLikelyUnknownHashtagCommandSchemaIssues=r;function i(f,g){let p=new Set;for(let d of f.matchAll(tF))d[1]&&p.add(d[1]);let m=new Set(g),C=new Set,b=f.split(/\r?\n/),y=[];for(let d=0;d<b.length;d++){let _=(b[d]??"").replace(/\/\/.*$/,"");for(let v of _.matchAll(/->[ \t]+(\w[\w.]*)/g)){let w=v[1];if(!w)continue;let D=w.split(".")[0]??w;nF.has(D)||p.has(D)||m.has(w)||m.has(w.replaceAll(".",rF))||m.has(D)||C.has(w)||(C.add(w),y.push({line:d+1,target:w}));}}return y}h.getUnknownDivertTargets=i;function a(f){return new Pp.default({strict:false,allErrors:true}).compile(f)}h.getSchemaValidator=a;function s(f,g){let p=typeof g=="function"?g:a(g);return p(f)?[]:vF(p.errors??[],f,p.schema)}h.validateAgainstJsonSchema=s;function o(f,g){let p=new Set,m=[];for(let d of g){let _=u(d);_!==void 0?m.push(_):p.add(String(d));}m.sort((d,_)=>_-d);let C=[],b=f.length;for(let d=f.length-1;d>=0;d--)p.has(f[d])&&(C.push({key:f[d],sectionTokens:f.slice(d+1,b)}),b=d);C.reverse();let y=[];for(let d of m)d<0||d>=b||(y.push({key:d,sectionTokens:f.slice(d,b)}),b=d-1);return y.reverse(),[...y,...C]}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,g){let p=o(f,Object.keys(g)),m=[];for(let{key:C,sectionTokens:b}of p){let y;try{y=pn.convertListStringToObj(b);}catch(_){m.push({key:C,instancePath:"(root)",element:String(C),message:`could not parse "${C}" section into key/value pairs: ${_ instanceof Error?_.message:String(_)}`});continue}let d=s(y,g[C]);m.push(...d.map(_=>({..._,key:C})));}return m}h.validateKeyedJsonSchemas=l;function c(f,g){let p=[];for(let m of Dp(f)){let C=g.find(({validation:y})=>Ap(m.tokens,y));if(!C?.keySchemas)continue;let b=l(m.tokens,C.keySchemas);p.push(...b.map(y=>({...y,line:m.line,command:m.command})));}return p}h.getHashtagKeySchemaIssues=c;})(Ht||={});var Tp=An(pr());function xC(n){if(!n||n.length===0)return;let e=new Set;for(let t of n){let r=typeof t=="string"?t:t?.id;typeof r=="string"&&r.length>0&&e.add(r);}return e.size>0?e:void 0}function Us(n,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:n},{json:r,issues:i}=Ht.compile(n,t);if(i.forEach(({message:s,type:o})=>{o===Tp.ErrorType.Error?ae.error(`Ink compilation error: ${s}`):o===Tp.ErrorType.Warning?ae.warn(`Ink compilation warning: ${s}`):ae.info(`Ink compilation info: ${s}`);}),!r){ae.error("No JSON generated from ink file");return}let a;try{a=Ti.parse(r);}catch{ae.error("Error parsing ink file");return}return t.enums=a.listDefs||{},Ml.inkToJson(a,{...t,characterIds:xC(e.characters)})}var ut;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(ut||={});var se=class ue{static init(e){e.loadAssets&&(ue._loadAssets=e.loadAssets),e.soundOperation&&(ue._soundOperation=e.soundOperation),e.imageOperation&&(ue._imageOperation=e.imageOperation),e.videoOperation&&(ue._videoOperation=e.videoOperation),e.imageContainerOperation&&(ue._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(ue._textOperation=e.textOperation),e.canvasElementOperation&&(ue._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(ue._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(ue._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(ue._narrationOperation=e.narrationOperation),e.effectOperation&&(ue._effectOperation=e.effectOperation),e.animateOperation&&(ue._animateOperation=e.animateOperation),e.canvasOperation&&(ue._canvasOperation=e.canvasOperation),e.getLogichValue&&(ue._getLogichValue=e.getLogichValue),e.getConditionalStep&&(ue._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return ue._loadAssets}static _soundOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return ue._soundOperation}static _imageOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return ue._imageOperation}static _videoOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return ue._videoOperation}static _imageContainerOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return ue._imageContainerOperation}static _textOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return ue._textOperation}static _canvasElementOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return ue._canvasElementOperation}static _setStorageValue=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return ue._setStorageValue}static _setInitialStorageValue=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return ue._setInitialStorageValue}static _narrationOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return ue._narrationOperation}static _effectOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return ue._effectOperation}static _animateOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return ue._animateOperation}static _canvasOperation=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return ue._canvasOperation}static _getLogichValue=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return ue._getLogichValue}static _getConditionalStep=()=>{throw ut.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return ue._getConditionalStep}};var xr;(n=>{n.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(l,c){e.unshift({fn:l,opts:c});}n.add=t;function r(l){let c=e.findIndex(h=>h.fn===l);c!==-1&&e.splice(c,1);}n.remove=r;function i(){return e.map(l=>l.opts)}n.info=i;function a(l,c){let h=e.filter(f=>(f.opts.type??"after-translation")===c.type);for(let f of h)l=u(l,f.fn,f.opts.validation);return l}n.replace=a;function s(l){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)l=o(l,h.fn,h.opts);return l}n.runI18nPreStep=s;function o(l,c,h){let{validation:f}=h,g=new RegExp(n.options.replaceRegex.source,"g"),p=[...l.matchAll(g)],m=new Set,C=[];for(let b of p)m.has(b[1])||(m.add(b[1]),C.push(b[1]));for(let b of C){if(f==="characterId"){if(!characters.RegisteredCharacters.has(b))continue}else if(f!=="all"){if(f instanceof RegExp){if(!f.test(b))continue}else if(f instanceof zod.ZodType&&!f.safeParse(b).success)continue}c(b)!==void 0&&(l.includes(`{{[${b}]}}`)||(l=l.replaceAll(`[${b}]`,`{{[${b}]}}`)));}return l}function u(l,c,h){let f=new RegExp(n.options.replaceRegex.source,"g"),g=[...l.matchAll(f)],p=new Set,m=[];for(let C of g)p.has(C[1])||(p.add(C[1]),m.push(C[1]));for(let C of m){if(h==="characterId"){if(!characters.RegisteredCharacters.has(C))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(C))continue}else if(h instanceof zod.ZodType&&!h.safeParse(C).success)continue}let b=c(C);b!==void 0&&(l=l.replaceAll(`[${C}]`,b));}return l}})(xr||={});function CF(n,e={}){let t="";return n.values.forEach(r=>{if(typeof r=="string")t+=r;else {let i=se.getLogichValue(r,e);t+=`${i}`;}}),t}var TC;(n=>{let e=u=>u;function t(u){return Array.isArray(u)?u.map(l=>r(`${l}`)):r(`${u}`)}n.t=t;function r(u){let l=u;return n.beforeToTranslate&&(l=(0, n.beforeToTranslate)(l)),l=xr.replace(l,{type:"before-translation"}),l=e(l),n.afterToTranslate&&(l=(0, n.afterToTranslate)(l)),l=xr.replace(l,{type:"after-translation"}),l}n.translate=r;function i(u){e=u;}n.setTranslate=i;function a(u,l,c){let{defaultValue:h="empty_string"}=c;typeof l=="string"&&(l=[l]),Array.isArray(l)&&l.forEach(f=>{let g=f;if(n.beforeToTranslate&&(g=(0, n.beforeToTranslate)(g)),h==="empty_string")u[g]===void 0&&(u[g]="");else if(h==="copy_key"){let p=f;n.beforeToTranslate&&(p=(0, n.beforeToTranslate)(p));let m=xr.runI18nPreStep(p);m=xr.replace(m,{type:"before-translation"}),u[g]=m;}});}function s(u,l=[]){if(typeof u=="object"&&u&&"type"in u)if(u.type==="ifelse")u.then&&s(u.then,l),u.else&&s(u.else,l);else if(u.type==="stepswitch"){if(u.elements)if(Array.isArray(u.elements))u.elements.forEach(c=>{s(c,l);});else if(u.elements.type==="ifelse"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else if(u.elements.type==="stepswitch"){let c=[];s(u.elements,c),c.forEach(h=>{l.push(...h);});}else s(u.elements,l);}else u.type==="resulttocombine"?(u.firstItem&&s(u.firstItem,l),u.secondConditionalItem&&u.secondConditionalItem.forEach(c=>{s(c,l);})):l.push(u);else u&&l.push(u);return l}async function o(u,l={},c={}){let{defaultValue:h="copy_key",operationStringConvert:f}=c,g=u.map(async p=>{if(p.choices){let m=[];Array.isArray(p.choices)?m=[p.choices]:m=s(p.choices),m.forEach(C=>{C.forEach(b=>{if("type"in b){let y=[];b.type==="ifelse"||b.type==="stepswitch"?s(b,y):y=[b],y.map(d=>s(d.text)).forEach(d=>{Array.isArray(d)&&d.forEach(_=>{Array.isArray(_)?_.forEach(v=>{typeof v=="string"?a(l,v,{defaultValue:h}):s(v).forEach(w=>{Array.isArray(w)?w.forEach(D=>{typeof D=="string"&&a(l,D,{defaultValue:h});}):typeof w=="string"&&a(l,w,{defaultValue:h});});}):typeof _=="string"&&a(l,_,{defaultValue:h});});});}});});}if(p.dialogue){let m=[];Array.isArray(p.dialogue)?m=[p.dialogue]:m=s(p.dialogue),m.forEach(C=>{if(typeof C=="string")a(l,C,{defaultValue:h});else if("text"in C){let b=s(C.text);typeof b=="string"&&(b=[b]),b.forEach(y=>{typeof y=="string"?a(l,y,{defaultValue:h}):s(y).forEach(d=>{typeof d=="string"?a(l,d,{defaultValue:h}):Array.isArray(d)&&d.forEach(_=>{typeof _=="string"?a(l,_,{defaultValue:h}):s(_).forEach(v=>{typeof v=="string"&&a(l,v,{defaultValue:h});});});});});}});}if(p.operations)for(let m of p.operations){if(m.type==="operationtoconvert"&&f){let C=CF(m),b=await f(C,p,{});if(!b)return;m=b;}m.type==="text"&&m.operationType==="show"&&a(l,m.text,{defaultValue:h});}p.conditionalStep&&s(p.conditionalStep).forEach(m=>{Array.isArray(m)?o(m,l,c):o([m],l,c);});});return await Promise.all(g),l}n.generateJsonTranslation=o;})(TC||={});var Ks=TC;var Oe;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Oe||={});var _F="___param___",SF=class le{static init(e){e.loadAssets&&(le._loadAssets=e.loadAssets),e.soundOperation&&(le._soundOperation=e.soundOperation),e.imageOperation&&(le._imageOperation=e.imageOperation),e.videoOperation&&(le._videoOperation=e.videoOperation),e.imageContainerOperation&&(le._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(le._textOperation=e.textOperation),e.canvasElementOperation&&(le._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(le._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(le._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(le._narrationOperation=e.narrationOperation),e.effectOperation&&(le._effectOperation=e.effectOperation),e.animateOperation&&(le._animateOperation=e.animateOperation),e.canvasOperation&&(le._canvasOperation=e.canvasOperation),e.getLogichValue&&(le._getLogichValue=e.getLogichValue),e.getConditionalStep&&(le._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return le._loadAssets}static _soundOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get soundOperation(){return le._soundOperation}static _imageOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageOperation(){return le._imageOperation}static _videoOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get videoOperation(){return le._videoOperation}static _imageContainerOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get imageContainerOperation(){return le._imageContainerOperation}static _textOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get textOperation(){return le._textOperation}static _canvasElementOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasElementOperation(){return le._canvasElementOperation}static _setStorageValue=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setStorageValue(){return le._setStorageValue}static _setInitialStorageValue=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get setInitialStorageValue(){return le._setInitialStorageValue}static _narrationOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get narrationOperation(){return le._narrationOperation}static _effectOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get effectOperation(){return le._effectOperation}static _animateOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get animateOperation(){return le._animateOperation}static _canvasOperation=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get canvasOperation(){return le._canvasOperation}static _getLogichValue=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getLogichValue(){return le._getLogichValue}static _getConditionalStep=()=>{throw Oe.error("An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue."),new pixiVn.PixiError("invalid_usage","An error occurred! pixi-vn-json was not initialized. Please contact the Pixi'VN team to report the issue.")};static get getConditionalStep(){return le._getConditionalStep}};function EF(n,e){if(e&&typeof e=="object"&&typeof n.functionName=="string"&&n.functionName in e){let t=e[n.functionName];if(typeof t=="function"){let r=n.args.map(i=>SF.getLogichValue(i,e));return t(...r)}else Oe.warn(`getLogichValue function ${n.functionName} not found in props`);}}function NC(n,e={}){let t=FC(n,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return AF(t,e);case "arithmetic":case "arithmeticsingle":return wF(t,e);case "compare":case "union":return DF(t,e);case "function":return EF(t,e)}return t}function wF(n,e){let t=se.getLogichValue(n.leftValue,e);switch(n.type){case "arithmetic":{let r=se.getLogichValue(n.rightValue,e);switch(n.operator){case "*":return t*r;case "/":return t/r;case "+":return typeof t=="string"||typeof r=="string"?`${t}${r}`:Array.isArray(t)&&Array.isArray(r)?[...t,...r]:Array.isArray(t)?[...t,r]:Array.isArray(r)?[t,...r]:t+r;case "-":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>!r.includes(i));if(Array.isArray(t))return t.filter(i=>i!==r);if(Array.isArray(r)){Oe.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-r;case "%":return t%r;case "POW":return t**r;case "RANDOM":return narration.narration.getRandomNumber(t,r);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(r))return t.filter(i=>r.includes(i));Oe.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:Oe.warn("getValueFromArithmeticOperations unknown operator",n);return}}case "arithmeticsingle":switch(n.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function AF(n,e){if(n&&typeof n=="object"&&"type"in n&&n.type==="value"&&n.storageOperationType==="get")switch(n.storageType){case "storage":case "tempstorage":return n.key==="_input_value_"?narration.narration.input.value:storage.storage.get(n.key);case "flagStorage":return storage.storage.flags.get(n.key);case "label":return narration.narration.queries.timesLabelOpened(n.label);case "choice":return narration.narration.queries.timesChoiceMade(n.index);case "logic":return se.getLogichValue(n.operation,e);case "params":{let t=storage.storage.get(`${_F}${narration.narration.labels.opened.length-1}`)||[];if(t&&t.length>n.key)return t[n.key];Oe.warn("getValue params not found");return}}return n}function DF(n,e){if(!n)return false;if(typeof n!="object"||!("type"in n))return !!n;switch(n.type){case "compare":{let t=se.getLogichValue(n.leftValue,e),r=se.getLogichValue(n.rightValue,e);switch(n.operator){case "==":return Array.isArray(t)&&Array.isArray(r)?t.length===r.length&&t.every(i=>r.includes(i)):t===r;case "!=":return Array.isArray(t)&&Array.isArray(r)?t.length!==r.length||!t.every(i=>r.includes(i)):t!==r;case "<":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<0:Array.isArray(t)&&Array.isArray(r)?t.length<r.length:t<r;case "<=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)<=0:Array.isArray(t)&&Array.isArray(r)?t.length<=r.length:t<=r;case ">":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>0:Array.isArray(t)&&Array.isArray(r)?t.length>r.length:t>r;case ">=":return typeof t=="string"&&typeof r=="string"?t.localeCompare(r)>=0:Array.isArray(t)&&Array.isArray(r)?t.length>=r.length:t>=r;case "CONTAINS":return Array.isArray(t)&&Array.isArray(r)?r.every(i=>t.includes(i)):Array.isArray(t)?t.includes(r):t.toString().includes(r.toString())}break}case "value":{let t=se.getLogichValue(n,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return xF(n,e)}return !!n}function xF(n,e){if(n.unionType==="not"){let r=NC(n.condition,e);return Array.isArray(r)?r.length===0:r&&typeof r=="object"?Object.keys(r).length===0:!r}let t=r=>se.getLogichValue(r,e)||false;return n.unionType==="and"?n.conditions.every(t):n.conditions.some(t)}function PF(n,e){return Math.floor(Math.random()*(e-n+1)+n)}function FC(n,e={}){if(Array.isArray(n)||!n)return n;if(n&&typeof n=="object"&&"type"in n)switch(n.type){case "resulttocombine":return OF(n,e);case "ifelse":return se.getLogichValue(n.condition,e)?se.getLogichValue(n.then,e):se.getLogichValue(n.else,e);case "stepswitch":{let t=se.getLogichValue(n.elements,e)||[];if(t.length===0){Oe.error("getValueFromConditionalStatements elements.length === 0");return}switch(n.choiceType){case "random":{let r=PF(0,t.length-1);return se.getLogichValue(t[r],e)}case "loop":{let r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return r>t.length-1?(r=r%t.length,se.getLogichValue(t[r],e)):se.getLogichValue(t[r],e)}case "sequential":{let r,i=narration.NarrationManagerStatic.getCurrentStepTimesCounter(n.nestedId)-1;return n.end==="lastItem"&&(r=se.getLogichValue(t[t.length-1],e)),i>t.length-1?r:se.getLogichValue(t[i],e)}case "sequentialrandom":{let r=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:n.nestedId,onceOnly:true});if(r===void 0&&n.end==="lastItem"){let i=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(n.nestedId);if(!i?.usedRandomNumbers){Oe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=i.usedRandomNumbers[`0-${t.length-1}`];return se.getLogichValue(t[a[a.length-1]],e)}if(r===void 0){Oe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return se.getLogichValue(t[r],e)}}}}return n}function Fp(n,e={}){if(n.conditionalStep){let t=pixiVn.createExportableElement(se.getLogichValue(n.conditionalStep,e));if(t?.glueEnabled===void 0&&delete t?.glueEnabled,t?.goNextStep===void 0&&delete t?.goNextStep,t?.end===void 0&&delete t?.end,t?.choices===void 0&&delete t?.choices,t?.dialogue===void 0&&delete t?.dialogue,t?.labelToOpen===void 0&&delete t?.labelToOpen,t?.operations===void 0&&delete t?.operations,t){let r={...n,conditionalStep:void 0,...t};return Fp(r,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return n}function OF(n,e){let t=n.firstItem,r=(n.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>se.getLogichValue(s,e)):[se.getLogichValue(a,e)]),i=t?[t,...r]:r;if(i.length===0){Oe.warn("combinateResult toCheck.length === 0");return}if(typeof i[0]=="string")return Ks.t(i);if(typeof i[0]=="object"){let a=i,s,o=false,u=a.map((y,d)=>{y=Fp(y,e);let _=se.getLogichValue(y.dialogue,e)||"";return d===0?(s=se.getLogichValue(y.glueEnabled,e)||false,_):(typeof _=="object"&&"text"in _&&(_=`${_.character}: ${_.text}`),s===false&&o&&(_=`
101
101
 
102
- ${v}`),v&&(o=true),s=se.getLogichValue(y.glueEnabled,e)||false,v)}),l=se.getLogichValue(u[0],e),c=typeof l=="object"&&"character"in l?l.character:void 0,h=u.flatMap(y=>{let p;y&&typeof y=="object"&&"text"in y?p=y.text:p=y;let v;return Array.isArray(p)?v=p.map(C=>{let S=se.getLogichValue(C,e);return Js.t(`${S}`)}):v=se.getLogichValue(p,e)||"",Js.t(v)}),d=a.find(y=>y.end),g=a.find(y=>y.choices),f=false,m=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),f=a[a.length-1].glueEnabled,m=a.reverse().find(y=>!(y.operations&&(!y.dialogue||!y.choices)))?.goNextStep);let b=a.find(y=>y.labelToOpen),_=[];return a.forEach(y=>{y.operations&&(_=[..._,...y.operations]);}),{dialogue:c?{character:c,text:h}:h,end:d?.end,choices:g?.choices,glueEnabled:f,goNextStep:m,labelToOpen:b?.labelToOpen,operations:_}}}var Op;(n=>{let e=new Set;function t(a){e.add(a);}n.add=t;function r(){e.clear();}n.clear=r;function i(a,s={}){let o=c=>OC(c,s)??void 0,u=TC(a,s);if(e.size===0)return o(u);let l=o;for(let c of e){let h=l;l=d=>c(d,h)??void 0;}return l(u)}n.getLogichValue=i;})(Op||={});var xF=Object.create,FC=Object.defineProperty,PF=Object.getOwnPropertyDescriptor,OF=Object.getOwnPropertyNames,TF=Object.getPrototypeOf,NF=Object.prototype.hasOwnProperty,NC=(n=>typeof Un<"u"?Un:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof Un<"u"?Un:e)[t]}):n)(function(n){if(typeof Un<"u")return Un.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),IC=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),FF=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of OF(e))!NF.call(n,i)&&i!==t&&FC(n,i,{get:()=>e[i],enumerable:!(r=PF(e,i))||r.enumerable});return n},IF=(n,e,t)=>(t=n!=null?xF(TF(n)):{},FF(FC(t,"default",{value:n,enumerable:true}),n)),kF=IC((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r():typeof define=="function"&&define.amd?define([],r):t.CryptoJS=r();})(n,function(){var t=t||(function(r,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof NC=="function")try{a=NC("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function y(){}return function(p){var v;return y.prototype=p,v=new y,y.prototype=null,v}})(),u={},l=u.lib={},c=l.Base=(function(){return {extend:function(y){var p=o(this);return y&&p.mixIn(y),(!p.hasOwnProperty("init")||this.init===p.init)&&(p.init=function(){p.$super.init.apply(this,arguments);}),p.init.prototype=p,p.$super=this,p},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var p in y)y.hasOwnProperty(p)&&(this[p]=y[p]);y.hasOwnProperty("toString")&&(this.toString=y.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=l.WordArray=c.extend({init:function(y,p){y=this.words=y||[],p!=i?this.sigBytes=p:this.sigBytes=y.length*4;},toString:function(y){return (y||g).stringify(this)},concat:function(y){var p=this.words,v=y.words,C=this.sigBytes,S=y.sigBytes;if(this.clamp(),C%4)for(var D=0;D<S;D++){var O=v[D>>>2]>>>24-D%4*8&255;p[C+D>>>2]|=O<<24-(C+D)%4*8;}else for(var A=0;A<S;A+=4)p[C+A>>>2]=v[A>>>2];return this.sigBytes+=S,this},clamp:function(){var y=this.words,p=this.sigBytes;y[p>>>2]&=4294967295<<32-p%4*8,y.length=r.ceil(p/4);},clone:function(){var y=c.clone.call(this);return y.words=this.words.slice(0),y},random:function(y){for(var p=[],v=0;v<y;v+=4)p.push(s());return new h.init(p,y)}}),d=u.enc={},g=d.Hex={stringify:function(y){for(var p=y.words,v=y.sigBytes,C=[],S=0;S<v;S++){var D=p[S>>>2]>>>24-S%4*8&255;C.push((D>>>4).toString(16)),C.push((D&15).toString(16));}return C.join("")},parse:function(y){for(var p=y.length,v=[],C=0;C<p;C+=2)v[C>>>3]|=parseInt(y.substr(C,2),16)<<24-C%8*4;return new h.init(v,p/2)}},f=d.Latin1={stringify:function(y){for(var p=y.words,v=y.sigBytes,C=[],S=0;S<v;S++){var D=p[S>>>2]>>>24-S%4*8&255;C.push(String.fromCharCode(D));}return C.join("")},parse:function(y){for(var p=y.length,v=[],C=0;C<p;C++)v[C>>>2]|=(y.charCodeAt(C)&255)<<24-C%4*8;return new h.init(v,p)}},m=d.Utf8={stringify:function(y){try{return decodeURIComponent(escape(f.stringify(y)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(y){return f.parse(unescape(encodeURIComponent(y)))}},b=l.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(y){typeof y=="string"&&(y=m.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes;},_process:function(y){var p,v=this._data,C=v.words,S=v.sigBytes,D=this.blockSize,O=D*4,A=S/O;y?A=r.ceil(A):A=r.max((A|0)-this._minBufferSize,0);var E=A*D,F=r.min(E*4,S);if(E){for(var R=0;R<E;R+=D)this._doProcessBlock(C,R);p=C.splice(0,E),v.sigBytes-=F;}return new h.init(p,F)},clone:function(){var y=c.clone.call(this);return y._data=this._data.clone(),y},_minBufferSize:0});l.Hasher=b.extend({cfg:c.extend(),init:function(y){this.cfg=this.cfg.extend(y),this.reset();},reset:function(){b.reset.call(this),this._doReset();},update:function(y){return this._append(y),this._process(),this},finalize:function(y){y&&this._append(y);var p=this._doFinalize();return p},blockSize:16,_createHelper:function(y){return function(p,v){return new y.init(v).finalize(p)}},_createHmacHelper:function(y){return function(p,v){return new _.HMAC.init(y,v).finalize(p)}}});var _=u.algo={};return u})(Math);return t});}),RF=IC((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r(kF()):typeof define=="function"&&define.amd?define(["./core"],r):r(t.CryptoJS);})(n,function(t){return (function(){var r=t,i=r.lib,a=i.WordArray,s=i.Hasher,o=r.algo,u=[],l=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(c,h){for(var d=this._hash.words,g=d[0],f=d[1],m=d[2],b=d[3],_=d[4],y=0;y<80;y++){if(y<16)u[y]=c[h+y]|0;else {var p=u[y-3]^u[y-8]^u[y-14]^u[y-16];u[y]=p<<1|p>>>31;}var v=(g<<5|g>>>27)+_+u[y];y<20?v+=(f&m|~f&b)+1518500249:y<40?v+=(f^m^b)+1859775393:y<60?v+=(f&m|f&b|m&b)-1894007588:v+=(f^m^b)-899497514,_=b,b=m,m=f<<30|f>>>2,f=g,g=v;}d[0]=d[0]+g|0,d[1]=d[1]+f|0,d[2]=d[2]+m|0,d[3]=d[3]+b|0,d[4]=d[4]+_|0;},_doFinalize:function(){var c=this._data,h=c.words,d=this._nDataBytes*8,g=c.sigBytes*8;return h[g>>>5]|=128<<24-g%32,h[(g+64>>>9<<4)+14]=Math.floor(d/4294967296),h[(g+64>>>9<<4)+15]=d,c.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var c=s.clone.call(this);return c._hash=this._hash.clone(),c}});r.SHA1=s._createHelper(l),r.HmacSHA1=s._createHmacHelper(l);})(),t.SHA1});});var $F;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))($F||={});IF(RF());var Kp=wn(dr()),xr=wn($C());var VC=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('vite.cjs', document.baseURI).href)));function zF(n){let e=ce.normalize(n);return e.length>1&&e[e.length-1]===ce.sep&&(e=e.substring(0,e.length-1)),e}var UF=/[\\/]/g;function qC(n,e){return n.replace(UF,e)}var KF=/^[a-z]:[\\/]$/i;function XF(n){return n==="/"||KF.test(n)}function Np(n,e){let{resolvePaths:t,normalizePath:r,pathSeparator:i}=e,a=process.platform==="win32"&&n.includes("/")||n.startsWith(".");if(t&&(n=ce.resolve(n)),(r||a)&&(n=zF(n)),n===".")return "";let s=n[n.length-1]!==i;return qC(s?n+i:n,i)}function BC(n,e){return e+n}function YF(n,e){return function(t,r){return r.startsWith(n)?r.slice(n.length)+t:qC(ce.relative(n,r),e.pathSeparator)+e.pathSeparator+t}}function QF(n){return n}function ZF(n,e,t){return e+n+t}function eI(n,e){let{relativePaths:t,includeBasePath:r}=e;return t&&n?YF(n,e):r?BC:QF}function tI(n){return function(e,t){t.push(e.substring(n.length)||".");}}function nI(n){return function(e,t,r){let i=e.substring(n.length)||".";r.every(a=>a(i,true))&&t.push(i);}}var rI=(n,e)=>{e.push(n||".");},iI=(n,e,t)=>{let r=n||".";t.every(i=>i(r,true))&&e.push(r);},sI=()=>{};function aI(n,e){let{includeDirs:t,filters:r,relativePaths:i}=e;return t?i?r&&r.length?nI(n):tI(n):r&&r.length?iI:rI:sI}var oI=(n,e,t,r)=>{r.every(i=>i(n,false))&&t.files++;},uI=(n,e,t,r)=>{r.every(i=>i(n,false))&&e.push(n);},lI=(n,e,t,r)=>{t.files++;},cI=(n,e)=>{e.push(n);},hI=()=>{};function dI(n){let{excludeFiles:e,filters:t,onlyCounts:r}=n;return e?hI:t&&t.length?r?oI:uI:r?lI:cI}var fI=n=>n,pI=()=>[""].slice(0,0);function mI(n){return n.group?pI:fI}var gI=(n,e,t)=>{n.push({directory:e,files:t,dir:e});},yI=()=>{};function vI(n){return n.group?gI:yI}var CI=function(n,e,t){let{queue:r,fs:i,options:{suppressErrors:a}}=e;r.enqueue(),i.realpath(n,(s,o)=>{if(s)return r.dequeue(a?null:s,e);i.stat(o,(u,l)=>{if(u)return r.dequeue(a?null:u,e);if(l.isDirectory()&&MC(n,o,e))return r.dequeue(null,e);t(l,o),r.dequeue(null,e);});});},bI=function(n,e,t){let{queue:r,fs:i,options:{suppressErrors:a}}=e;r.enqueue();try{let s=i.realpathSync(n),o=i.statSync(s);if(o.isDirectory()&&MC(n,s,e))return;t(o,s);}catch(s){if(!a)throw s}};function _I(n,e){return !n.resolveSymlinks||n.excludeSymlinks?null:e?bI:CI}function MC(n,e,t){if(t.options.useRealPaths)return SI(e,t);let r=ce.dirname(n),i=1;for(;r!==t.root&&i<2;){let a=t.symlinks.get(r);!!a&&(a===e||a.startsWith(e)||e.startsWith(a))?i++:r=ce.dirname(r);}return t.symlinks.set(n,e),i>1}function SI(n,e){return e.visited.includes(n+e.options.pathSeparator)}var EI=n=>n.counts,wI=n=>n.groups,AI=n=>n.paths,DI=n=>n.paths.slice(0,n.options.maxFiles),xI=(n,e,t)=>(bl(e,t,n.counts,n.options.suppressErrors),null),PI=(n,e,t)=>(bl(e,t,n.paths,n.options.suppressErrors),null),OI=(n,e,t)=>(bl(e,t,n.paths.slice(0,n.options.maxFiles),n.options.suppressErrors),null),TI=(n,e,t)=>(bl(e,t,n.groups,n.options.suppressErrors),null);function bl(n,e,t,r){e(n&&!r?n:null,t);}function NI(n,e){let{onlyCounts:t,group:r,maxFiles:i}=n;return t?e?EI:xI:r?e?wI:TI:i?e?DI:OI:e?AI:PI}var WC={withFileTypes:true},FI=(n,e,t,r,i)=>{if(n.queue.enqueue(),r<0)return n.queue.dequeue(null,n);let{fs:a}=n;n.visited.push(e),n.counts.directories++,a.readdir(e||".",WC,(s,o=[])=>{i(o,t,r),n.queue.dequeue(n.options.suppressErrors?null:s,n);});},II=(n,e,t,r,i)=>{let{fs:a}=n;if(r<0)return;n.visited.push(e),n.counts.directories++;let s=[];try{s=a.readdirSync(e||".",WC);}catch(o){if(!n.options.suppressErrors)throw o}i(s,t,r);};function kI(n){return n?II:FI}var RI=class{count=0;constructor(n){this.onQueueEmpty=n;}enqueue(){return this.count++,this.count}dequeue(n,e){this.onQueueEmpty&&(--this.count<=0||n)&&(this.onQueueEmpty(n,e),n&&(e.controller.abort(),this.onQueueEmpty=void 0));}},$I=class{_files=0;_directories=0;set files(n){this._files=n;}get files(){return this._files}set directories(n){this._directories=n;}get directories(){return this._directories}get dirs(){return this._directories}},VI=class{aborted=false;abort(){this.aborted=true;}},GC=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(n,e,t){this.isSynchronous=!t,this.callbackInvoker=NI(e,this.isSynchronous),this.root=Np(n,e),this.state={root:XF(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new $I,options:e,queue:new RI((r,i)=>this.callbackInvoker(i,r,t)),symlinks:new Map,visited:[""].slice(0,0),controller:new VI,fs:e.fs||JF__namespace},this.joinPath=eI(this.root,e),this.pushDirectory=aI(this.root,e),this.pushFile=dI(e),this.getArray=mI(e),this.groupFiles=vI(e),this.resolveSymlink=_I(e,this.isSynchronous),this.walkDirectory=kI(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(n,e,t)=>{let{paths:r,options:{filters:i,resolveSymlinks:a,excludeSymlinks:s,exclude:o,maxFiles:u,signal:l,useRealPaths:c,pathSeparator:h},controller:d}=this.state;if(d.aborted||l&&l.aborted||u&&r.length>u)return;let g=this.getArray(this.state.paths);for(let f=0;f<n.length;++f){let m=n[f];if(m.isFile()||m.isSymbolicLink()&&!a&&!s){let b=this.joinPath(m.name,e);this.pushFile(b,g,this.state.counts,i);}else if(m.isDirectory()){let b=ZF(m.name,e,this.state.options.pathSeparator);if(o&&o(m.name,b))continue;this.pushDirectory(b,r,i),this.walkDirectory(this.state,b,b,t-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let b=BC(m.name,e);this.resolveSymlink(b,this.state,(_,y)=>{if(_.isDirectory()){if(y=Np(y,this.state.options),o&&o(m.name,c?y:b+h))return;this.walkDirectory(this.state,y,c?y:b+h,t-1,this.walk);}else {y=c?y:b;let p=ce.basename(y),v=Np(ce.dirname(y),this.state.options);y=this.joinPath(p,v),this.pushFile(y,g,this.state.counts,i);}});}}this.groupFiles(this.state.groups,e,g);}};function jI(n,e){return new Promise((t,r)=>{HC(n,e,(i,a)=>{if(i)return r(i);t(a);});})}function HC(n,e,t){new GC(n,e,t).start();}function LI(n,e){return new GC(n,e).start()}var jC=class{constructor(n,e){this.root=n,this.options=e;}withPromise(){return jI(this.root,this.options)}withCallback(n){HC(this.root,this.options,n);}sync(){return LI(this.root,this.options)}},JC=null;try{VC.resolve("picomatch"),JC=VC("picomatch");}catch{}var zC=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:ce.sep,filters:[]};globFunction;constructor(n){this.options={...this.options,...n},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(n){return this.options.pathSeparator=n,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(n){return this.options.maxDepth=n,this}withMaxFiles(n){return this.options.maxFiles=n,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:n=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=n,this.withFullPaths()}withAbortSignal(n){return this.options.signal=n,this}normalize(){return this.options.normalizePath=true,this}filter(n){return this.options.filters.push(n),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(n){return this.options.exclude=n,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(n){return new jC(n||".",this.options)}withGlobFunction(n){return this.globFunction=n,this}crawlWithOptions(n,e){return this.options={...this.options,...e},new jC(n||".",this.options)}glob(...n){return this.globFunction?this.globWithOptions(n):this.globWithOptions(n,{dot:true})}globWithOptions(n,...e){let t=this.globFunction||JC;if(!t)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[n.join("\0")];return r||(r=t(n,...e),this.globCache[n.join("\0")]=r),this.options.filters.push(i=>r(i)),this}};var Si=wn(yb()),Tk=Array.isArray,_b=/\\/g,Nk=/^[A-Za-z]:$/,Sb=process.platform==="win32",Fk=/^(\/?\.\.)+$/;function Ik(n,e={}){let t=n.length,r=Array(t),i=Array(t),a,s;for(a=0;a<t;a++){let o=Eb(n[a]);r[a]=o;let u=o.length,l=Array(u);for(s=0;s<u;s++)l[s]=(0, Si.default)(o[s],e);i[a]=l;}return o=>{let u=o.split("/");if(u[0]===".."&&Fk.test(o))return true;for(a=0;a<t;a++){let l=r[a],c=i[a],h=u.length,d=Math.min(h,l.length);for(s=0;s<d;){let g=l[s];if(g.includes("/"))return true;if(!c[s](u[s]))break;if(!e.noglobstar&&g==="**")return true;s++;}if(s===h)return true}return false}}var kk=/^[A-Z]:\/$/i,Rk=Sb?n=>kk.test(n):n=>n==="/";function vb(n,e,t){if(n===e||e.startsWith(`${n}/`)){if(t){let i=n.length+ +!Rk(n);return (a,s)=>a.slice(i,s?-1:void 0)||"."}let r=e.slice(n.length+1);return r?(i,a)=>{if(i===".")return r;let s=`${r}/${i}`;return a?s.slice(0,-1):s}:(i,a)=>a&&i!=="."?i.slice(0,-1):i}return t?r=>ce.posix.relative(n,r)||".":r=>ce.posix.relative(n,`${e}/${r}`)||"."}function $k(n,e){if(e.startsWith(`${n}/`)){let t=e.slice(n.length+1);return r=>`${t}/${r}`}return t=>{let r=ce.posix.relative(n,`${e}/${t}`);return t[t.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function Cb(n){return n.replace(Nk,e=>`${e}/`)}var Vk={parts:true};function Eb(n){var e;let t=Si.default.scan(n,Vk);return !((e=t.parts)===null||e===void 0)&&e.length?t.parts:[n]}var jk=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Lk=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,qk=n=>n.replace(jk,"\\$&"),Bk=n=>n.replace(Lk,"\\$&"),Mk=Sb?Bk:qk;function Wk(n,e){let t=Si.default.scan(n);return t.isGlob||t.negated}function Ys(...n){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...n);}function wb(n){return typeof n=="string"?[n]:n??[]}var Gk=/^(\/?\.\.)+/,Hk=/\\(?=[()[\]{}!*+?@|])/g;function Gp(n,e,t,r){var i;let a=e.cwd,s=n;n[n.length-1]==="/"&&(s=n.slice(0,-1)),s[s.length-1]!=="*"&&e.expandDirectories&&(s+="/**");let o=Mk(a);s=ce.isAbsolute(s.replace(Hk,""))?ce.posix.relative(o,s):ce.posix.normalize(s);let u=(i=Gk.exec(s))===null||i===void 0?void 0:i[0],l=Eb(s);if(u){let h=(u.length+1)/3,d=0,g=o.split("/");for(;d<h&&l[d+h]===g[g.length+d-h];)s=s.slice(0,(h-d-1)*3)+s.slice((h-d)*3+l[d+h].length+1)||".",d++;let f=ce.posix.join(a,u.slice(d*3));f[0]!=="."&&t.root.length>f.length&&(t.root=Cb(f),t.depthOffset=-h+d);}if(!r&&t.depthOffset>=0){var c;(c=t.commonPath)!==null&&c!==void 0||(t.commonPath=l);let h=[],d=Math.min(t.commonPath.length,l.length);for(let g=0;g<d;g++){let f=l[g];if(f==="**"&&!l[g+1]){h.pop();break}if(g===l.length-1||f!==t.commonPath[g]||Wk(f))break;h.push(f);}t.depthOffset=h.length,t.commonPath=h,t.root=Cb(h.length>0?ce.posix.join(a,...h):a);}return s}function Jk(n,e,t){let r=[],i=[];for(let a of n.ignore)a&&(a[0]!=="!"||a[1]==="(")&&i.push(Gp(a,n,t,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?r.push(Gp(a,n,t,false)):(a[1]!=="!"||a[2]==="(")&&i.push(Gp(a.slice(1),n,t,true)));return {match:r,ignore:i}}function zk(n,e){let t=n.cwd,r={root:t,depthOffset:0},i=Jk(n,e,r);n.debug&&Ys("internal processing patterns:",i);let{absolute:a,caseSensitiveMatch:s,debug:o,dot:u,followSymbolicLinks:l,onlyDirectories:c}=n,h=r.root.replace(_b,""),d={dot:u,nobrace:n.braceExpansion===false,nocase:!s,noextglob:n.extglob===false,noglobstar:n.globstar===false,posix:true},g=(0, Si.default)(i.match,d),f=(0, Si.default)(i.ignore,d),m=Ik(i.match,d),b=vb(t,h,a),_=a?b:vb(t,h,true),y=(C,S)=>{let D=_(S,true);return D!=="."&&!m(D)||f(D)},p;n.deep!==void 0&&(p=Math.round(n.deep-r.depthOffset));let v=new zC({filters:[o?(C,S)=>{let D=b(C,S),O=g(D)&&!f(D);return O&&Ys(`matched ${D}`),O}:(C,S)=>{let D=b(C,S);return g(D)&&!f(D)}],exclude:o?(C,S)=>{let D=y(C,S);return Ys(`${D?"skipped":"crawling"} ${S}`),D}:y,fs:n.fs,pathSeparator:"/",relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:c,includeDirs:c||!n.onlyFiles,maxDepth:p,signal:n.signal}).crawl(h);return n.debug&&Ys("internal properties:",{...r,root:h}),[v,t!==h&&!a&&$k(t,h)]}function Uk(n,e){if(e)for(let t=n.length-1;t>=0;t--)n[t]=e(n[t]);return n}var bb={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function Kk(n){let e=Object.assign({},n);for(let t in bb)e[t]===void 0&&Object.assign(e,{[t]:bb[t]});return e.cwd=(e.cwd instanceof URL?url.fileURLToPath(e.cwd):ce.resolve(e.cwd||process.cwd())).replace(_b,"/"),e.ignore=wb(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||JF.readdir,readdirSync:e.fs.readdirSync||JF.readdirSync,realpath:e.fs.realpath||JF.realpath,realpathSync:e.fs.realpathSync||JF.realpathSync,stat:e.fs.stat||JF.stat,statSync:e.fs.statSync||JF.statSync}),e.debug&&Ys("globbing with options:",e),e}function Xk(n,e={}){var t;if(n&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=Tk(n)||typeof n=="string",i=wb((t=r?n:n.patterns)!==null&&t!==void 0?t:"**/*"),a=Kk(r?e:n);return i.length>0?zk(a,i):[]}async function Sl(n,e){let[t,r]=Xk(n,e);return t?Uk(await t.withPromise(),r):[]}var Ab="1.2.0";var En=xr.default.cyan("(pixi-vn-ink)"),Ib="virtual:pixi-vn-ink",Hp=`\0${Ib}`,Zk="manifest.json",kb=/\[(name|ext|extname|file|path|dir)\]/g,Db="ink";function xb(n){if(typeof n=="string")return {type:"literal",value:n};if(n instanceof RegExp)return {type:"regexp",source:n.source,flags:n.flags};try{return {type:"zod",schema:zod.toJSONSchema(n)}}catch{return {type:"literal",value:""}}}function zn(n){return n.replaceAll("\\","/")}function El(n){let e=zn(n.trim());if(!e)throw new Error("vitePluginInk option `inkGlob` must not be empty.");let t=e.replace(/^\.?\//,"");if(!t||t.startsWith("../"))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");return t}function Pb(n,e){let t=zn(e).split("/"),r=[];for(let i of t)if(!(i==="."||i==="")){if(/[*!?[\]{}()]/.test(i))break;r.push(i);}return ce__default.default.resolve(n,...r)}function Ob(n,e){if(!e)return;let t=e.trim();if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must not be empty.");return ce__default.default.isAbsolute(t)?ce__default.default.normalize(t):ce__default.default.resolve(n,t)}function Tb(n,e,t){if(!t)return ce__default.default.join(e,Zk);let r=t.trim();if(!r)throw new Error("vitePluginInk option `inkJsonManifestPath` must not be empty.");return ce__default.default.isAbsolute(r)?ce__default.default.normalize(r):ce__default.default.resolve(n,r)}function Nb(n){let e=n.search(kb);if(e===-1)return ce__default.default.dirname(n);let t=n.slice(0,e).replace(/[\\/]+$/g,"");if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must start with a static directory before placeholders.");return ce__default.default.normalize(t)}function Ei(n,e){let t=ce__default.default.relative(n,e);return !t.startsWith("..")&&!ce__default.default.isAbsolute(t)}function eR(n,e,t,r){let i=zn(ce__default.default.relative(t,r)),a=ce__default.default.posix.parse(i),s=zn(ce__default.default.relative(e,r)),o=ce__default.default.posix.dirname(s),u=ce__default.default.posix.dirname(i),l={name:a.name,ext:a.ext.startsWith(".")?a.ext.slice(1):a.ext,extname:a.ext,file:i,path:u==="."?"":`${u}/`,dir:o==="."?"":`${o}/`},c=zn(n).replace(kb,(h,d)=>l[d]??"");return ce__default.default.normalize(c)}function tR(n,e,t){return Ei(t,n)?`/${zn(ce__default.default.relative(t,n))}`:Ei(e,n)?zn(ce__default.default.relative(e,n)):zn(n)}function Jp(n,e,t){let r=Ht.getUnknownHashtagCommands(n,e);r.forEach(({command:i,line:a})=>{t(`Unknown hashtag command "# ${i}": no registered handler matched this command.`,a);}),r.length>0&&t(`Hashtag command metadata is available via ${wi}.`);}function zp(n,e,t){Ht.getHashtagKeySchemaIssues(n,e).forEach(({command:i,line:a,key:s,element:o,message:u})=>{t(`Hashtag command "# ${i}": "${s}" section ${o} - ${u}`,a);});}function Up(n,e,t){if(e.length===0)return;Ht.getUnknownDivertTargets(n,e).forEach(({target:i,line:a})=>{t(`Divert target "${i}" not found in any known label source.`,a);});}async function nR(n,e,t){let r=e.get(n);return r||(r=(async()=>{try{let i=await fetch(n);if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let a=await i.json();return Ht.getSchemaValidator(a)}catch(i){t(`Could not load/compile JSON schema from "${n}" (${i instanceof Error?i.message:String(i)}). Skipping schema validation.`);return}})(),e.set(n,r)),r}function rR(n,e){let t=`# ${n}`;if(!e)return xr.default.gray(t);let r=new RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g"),i="",a=0;for(let s of t.matchAll(r)){let o=s.index??a;i+=xr.default.gray(t.slice(a,o)),i+=xr.default.yellow(s[0]),a=o+s[0].length;}return i+=xr.default.gray(t.slice(a)),i}async function iR(n,e,t,r){let i=n.$schema;if(!i)return;let a=await nR(i,t,r);if(!a)return;let s=Ht.validateAgainstJsonSchema(n,a);for(let o of s){let u=o.origin?` \u2014 from ink source:
103
- ${rR(o.origin,o.element)}`:"";r(`${e}: ${o.element} - ${o.message}${u}`);}}function Fb(n){return new Promise((e,t)=>{let r="";n.on("data",i=>{r+=i.toString();}),n.on("end",()=>e(r)),n.on("error",t);})}function sR(n){let{inkGlob:e,inkJsonOutputPattern:t,inkJsonManifestPath:r,characters:i}=n??{},a=!!t,s,o=[],u=[],l,c,h,d=[],g,f,m,b=new Map,_=async()=>{let A=mn.info(),E=Ar.info();o=A.map(({name:F,description:R,validation:k,deprecated:x,keySchemas:P})=>({name:F,description:R,validation:xb(k),deprecated:x,keySchemas:P})),u=E.map(({name:F,description:R,validation:k,type:x})=>({name:F,description:R,validation:xb(k),type:x}));},y=A=>A?.find(E=>E.name==="vite-plugin-pixi-vn"),p=A=>{let E=A?.find(F=>F.name==="vite-plugin-nqtr");return [y(A)?.api?.contentLoaded,E?.api?.contentLoaded].filter(F=>!!F)},v=async A=>{let E=A?.api;if(!E)return;let F=d,R=JSON.stringify(F);if(R!==g)try{if(F.length===0&&E.clearExternalLabels)await E.clearExternalLabels(Db);else if(E.setExternalLabels)await E.setExternalLabels(Db,F);else return;g=R;}catch(k){let x=k instanceof Error?k:new Error(String(k));s?.logger.error(`${En} Failed to sync Ink labels with vite-plugin-pixi-vn.`,{error:x,timestamp:true});}},C=A=>{if(!a||!c)return false;let E=ce__default.default.resolve(A);return h&&E===h?true:Ei(c,E)},S=()=>{m!==void 0&&clearTimeout(m),m=setTimeout(()=>{m=void 0,O().then(async()=>{await v(y(f?.config.plugins));let A=f?.moduleGraph.getModuleById(Hp);A&&f?.moduleGraph.invalidateModule(A),f?.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?l??[]:void 0}});}).catch(A=>{let E=A instanceof Error?A:new Error(String(A));s?.logger.error(`${En} Failed to re-export Ink JSON files after characters update.`,{error:E,timestamp:true});});},150);},D=async()=>{if(!s||!e)return [];let A=El(e),E=await Sl(A,{absolute:true,cwd:s.root,onlyFiles:true}),F=[];for(let R of E)try{let k=await hn__default.default.readFile(R,"utf-8"),x=Hs(k,{characters:i??[]});x&&F.push(...Object.keys(x.labels??{}));}catch{}return Array.from(new Set(F)).sort((R,k)=>R.localeCompare(k))},O=async()=>{if(!s||!e){l=void 0,d=[];return}let A=Ob(s.root,t);if(!A){l=void 0,d=[],c=void 0,h=void 0;return}let E=El(e),F=Nb(A);c=ce__default.default.resolve(F);let R=Pb(s.root,E);if(!Ei(s.root,R))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");let k=await Sl(E,{absolute:true,cwd:s.root,onlyFiles:true}),x=[],P=[],Ce=new Set,j=y(s.plugins)?.api?.characters??[],X=[...i??[],...j];await hn__default.default.mkdir(F,{recursive:true});let ut=new Map;for(let pe of k){let At=await hn__default.default.readFile(pe,"utf-8");ut.set(pe,At);let N;try{N=Hs(At,{characters:X});}catch(I){let z=I instanceof Error?I:new Error(String(I));s.logger.error(`${En} Failed to convert "${pe}" to JSON.`,{error:z,timestamp:true});continue}let W=eR(A,s.root,R,pe);if(!Ei(F,W)){s.logger.error(`${En} Output path "${W}" escapes managed directory "${F}".`,{timestamp:true});continue}if(Ce.add(W),!N){await hn__default.default.rm(W,{force:true});continue}P.push(N),await hn__default.default.mkdir(ce__default.default.dirname(W),{recursive:true}),await hn__default.default.writeFile(W,`${JSON.stringify(N,null,2)}
104
- `,"utf-8"),x.push(tR(W,s.root,s.publicDir)),await iR(N,pe,b,I=>s.logger.warn(`${En} ${I}`,{timestamp:true}));}let We=Tb(s.root,F,r);h=ce__default.default.resolve(We);let Jt=await Sl("**/*.json",{absolute:true,cwd:F,onlyFiles:true});for(let pe of Jt)ce__default.default.resolve(pe)!==ce__default.default.resolve(We)&&!Ce.has(pe)&&await hn__default.default.rm(pe,{force:true});x.sort((pe,At)=>pe.localeCompare(At)),l=P;let Qs=P.flatMap(pe=>Object.keys(pe.labels??{}));d=Array.from(new Set(Qs)).sort((pe,At)=>pe.localeCompare(At));let Pr=Qs.length,zt=y(s.plugins)?.api?.labels??[],J=[...d,...zt];for(let[pe,At]of ut)Jp(At,o,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true})),zp(At,o,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true})),Up(At,J,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true}));s.logger.info(`${En} ${xr.default.dim(`${k.length} file(s) exported: ${Pr} label(s), ${o.length} hashtag-command(s), ${u.length} text-replace(s)`)}`,{timestamp:true}),await hn__default.default.mkdir(ce__default.default.dirname(We),{recursive:true}),await hn__default.default.writeFile(We,`${JSON.stringify(x,null,2)}
105
- `,"utf-8");};return {name:"vite-plugin-ink",enforce:"pre",configResolved(A){s=A,c=void 0,h=void 0;let E=e?El(e):void 0;if(E){let F=Pb(A.root,E);if(!Ei(A.root,F))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.")}if(t&&!e)throw new Error("vitePluginInk option `inkJsonOutputPattern` requires `inkGlob` to be set.");if(t){let F=Ob(A.root,t);if(!F)return;let R=Nb(F);if(c=ce__default.default.resolve(R),h=ce__default.default.resolve(Tb(A.root,R,r)),ce__default.default.resolve(R)===ce__default.default.resolve(A.root))throw new Error("vitePluginInk option `inkJsonOutputPattern` must target a directory different from Vite `root`.")}},async buildStart(){let A=y(s?.plugins);d=await D(),await v(A),await Promise.all(p(s?.plugins)),await _(),await O(),await v(A);},configureServer(A){f=A,A.middlewares.use(async(R,k,x)=>{let P=R.url,Ce=R.method;if(P===wi){if(Ce==="GET"){k.setHeader("Content-Type","application/json"),k.end(JSON.stringify(o));return}if(Ce==="POST"){try{let j=await Fb(R);o=JSON.parse(j),k.statusCode=204,k.end();}catch(j){s?.logger.warn(`${En} Invalid JSON body for POST ${wi}: ${String(j)}`,{timestamp:true}),k.statusCode=400,k.end();}return}}if(P===wl&&Ce==="GET"){k.setHeader("Content-Type","application/json");let j={version:Ab,schemaUrl:ia};k.end(JSON.stringify(j));return}if(P===Zs){if(Ce==="GET"){k.setHeader("Content-Type","application/json"),k.end(JSON.stringify(u));return}if(Ce==="POST"){try{let j=await Fb(R);u=JSON.parse(j),k.statusCode=204,k.end();}catch(j){s?.logger.warn(`${En} Invalid JSON body for POST ${Zs}: ${String(j)}`,{timestamp:true}),k.statusCode=400,k.end();}return}}x();});let E=y(A.config.plugins);Promise.all(p(A.config.plugins)).then(async()=>{await _(),await O(),await v(E);}).catch(R=>{let k=R instanceof Error?R:new Error(String(R));s?.logger.error(`${En} Failed to export Ink JSON files during server initialization or restart.`,{error:k,timestamp:true});});let F=E?.api?.onReload;F&&F(()=>{_().then(()=>S());});},resolveId(A){if(A===Ib)return Hp},load(A){if(A===Hp){if(!e)return ["export const inkJsons = undefined;","export default [];"].join(`
106
- `);let E=El(e);return [`const modules = import.meta.glob(${JSON.stringify(`/${E}`)}, { eager: true, import: 'default' });`,`export const inkJsons = ${JSON.stringify(a?l??[]:void 0)};`,"export default Object.values(modules);"].join(`
107
- `)}},hotUpdate:{order:"post",async handler({type:A,file:E,server:F,read:R}){if(E.endsWith(".ink")){if(A!=="delete"){let k=await R(),{issues:x}=Ht.compile(k),P;x.forEach(({line:j,message:X,type:ut})=>{ut===Kp.ErrorType.Warning?F.config.logger.warn(`${E}:${j} ${X}`,{timestamp:true}):(F.config.logger.error(`${E}:${j} ${X}`,{timestamp:true}),P=X);}),Jp(k,o,(j,X)=>F.config.logger.warn(`${X!==void 0?`${E}:${X}`:E}: ${j}`,{timestamp:true})),zp(k,o,(j,X)=>F.config.logger.warn(`${X!==void 0?`${E}:${X}`:E}: ${j}`,{timestamp:true}));let Ce=y(F.config.plugins)?.api?.labels??[];Up(k,[...d,...Ce],(j,X)=>F.config.logger.warn(`${X!==void 0?`${E}:${X}`:E}: ${j}`,{timestamp:true})),await O(),await v(y(F.config.plugins)),P?F.ws.send({type:"error",err:{message:P,stack:E,plugin:"vite-plugin-ink"}}):(F.ws.send({type:"custom",event:"ink-error-cleared",data:{}}),F.ws.send({type:"custom",event:"ink-updated",data:{inkText:k,inkJson:a?l??[]:void 0}}));}else await O(),await v(y(F.config.plugins)),F.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?l??[]:void 0}});return []}if(E.endsWith(".json")&&C(E))return await v(y(F.config.plugins)),F.ws.send({type:"custom",event:"ink-updated",data:{inkJson:l??[]}}),[]}},async transform(A,E){if(!E.endsWith(".ink"))return null;let F=await hn__default.default.readFile(E,"utf-8"),{issues:R}=Ht.compile(F);R.forEach(({line:x,message:P,type:Ce})=>{Ce===Kp.ErrorType.Warning?this.warn(`${E}:${x} ${P}`):this.error(`${E}:${x} ${P}`);}),Jp(F,o,(x,P)=>this.warn({message:x,loc:P!==void 0?{line:P,column:0}:void 0})),zp(F,o,(x,P)=>this.warn({message:x,loc:P!==void 0?{line:P,column:0}:void 0}));let k=y(s?.plugins)?.api?.labels??[];return Up(F,[...d,...k],(x,P)=>this.warn({message:x,loc:P!==void 0?{line:P,column:0}:void 0})),{code:`export default ${JSON.stringify(F)};`,map:null}}}}exports.INK_DEV_API_HASHTAG_COMMANDS=wi;exports.INK_DEV_API_INFO=wl;exports.INK_DEV_API_TEXT_REPLACES=Zs;exports.vitePluginInk=sR;
102
+ ${_}`),_&&(o=true),s=se.getLogichValue(y.glueEnabled,e)||false,_)}),l=se.getLogichValue(u[0],e),c=typeof l=="object"&&"character"in l?l.character:void 0,h=u.flatMap(y=>{let d;y&&typeof y=="object"&&"text"in y?d=y.text:d=y;let _;return Array.isArray(d)?_=d.map(v=>{let w=se.getLogichValue(v,e);return Ks.t(`${w}`)}):_=se.getLogichValue(d,e)||"",Ks.t(_)}),f=a.find(y=>y.end),g=a.find(y=>y.choices),p=false,m=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),p=a[a.length-1].glueEnabled,m=a.reverse().find(y=>!(y.operations&&(!y.dialogue||!y.choices)))?.goNextStep);let C=a.find(y=>y.labelToOpen),b=[];return a.forEach(y=>{y.operations&&(b=[...b,...y.operations]);}),{dialogue:c?{character:c,text:h}:h,end:f?.end,choices:g?.choices,glueEnabled:p,goNextStep:m,labelToOpen:C?.labelToOpen,operations:b}}}var Ip;(n=>{let e=new Set;function t(a){e.add(a);}n.add=t;function r(){e.clear();}n.clear=r;function i(a,s={}){let o=c=>NC(c,s)??void 0,u=FC(a,s);if(e.size===0)return o(u);let l=o;for(let c of e){let h=l;l=f=>c(f,h)??void 0;}return l(u)}n.getLogichValue=i;})(Ip||={});var TF=Object.create,kC=Object.defineProperty,NF=Object.getOwnPropertyDescriptor,FF=Object.getOwnPropertyNames,IF=Object.getPrototypeOf,kF=Object.prototype.hasOwnProperty,IC=(n=>typeof Xn<"u"?Xn:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof Xn<"u"?Xn:e)[t]}):n)(function(n){if(typeof Xn<"u")return Xn.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),RC=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),RF=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of FF(e))!kF.call(n,i)&&i!==t&&kC(n,i,{get:()=>e[i],enumerable:!(r=NF(e,i))||r.enumerable});return n},$F=(n,e,t)=>(t=n!=null?TF(IF(n)):{},RF(kC(t,"default",{value:n,enumerable:true}),n)),VF=RC((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r():typeof define=="function"&&define.amd?define([],r):t.CryptoJS=r();})(n,function(){var t=t||(function(r,i){var a;if(typeof window<"u"&&window.crypto&&(a=window.crypto),typeof self<"u"&&self.crypto&&(a=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(a=globalThis.crypto),!a&&typeof window<"u"&&window.msCrypto&&(a=window.msCrypto),!a&&typeof global<"u"&&global.crypto&&(a=global.crypto),!a&&typeof IC=="function")try{a=IC("crypto");}catch{}var s=function(){if(a){if(typeof a.getRandomValues=="function")try{return a.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof a.randomBytes=="function")try{return a.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||(function(){function y(){}return function(d){var _;return y.prototype=d,_=new y,y.prototype=null,_}})(),u={},l=u.lib={},c=l.Base=(function(){return {extend:function(y){var d=o(this);return y&&d.mixIn(y),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments);}),d.init.prototype=d,d.$super=this,d},create:function(){var y=this.extend();return y.init.apply(y,arguments),y},init:function(){},mixIn:function(y){for(var d in y)y.hasOwnProperty(d)&&(this[d]=y[d]);y.hasOwnProperty("toString")&&(this.toString=y.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=l.WordArray=c.extend({init:function(y,d){y=this.words=y||[],d!=i?this.sigBytes=d:this.sigBytes=y.length*4;},toString:function(y){return (y||g).stringify(this)},concat:function(y){var d=this.words,_=y.words,v=this.sigBytes,w=y.sigBytes;if(this.clamp(),v%4)for(var D=0;D<w;D++){var O=_[D>>>2]>>>24-D%4*8&255;d[v+D>>>2]|=O<<24-(v+D)%4*8;}else for(var P=0;P<w;P+=4)d[v+P>>>2]=_[P>>>2];return this.sigBytes+=w,this},clamp:function(){var y=this.words,d=this.sigBytes;y[d>>>2]&=4294967295<<32-d%4*8,y.length=r.ceil(d/4);},clone:function(){var y=c.clone.call(this);return y.words=this.words.slice(0),y},random:function(y){for(var d=[],_=0;_<y;_+=4)d.push(s());return new h.init(d,y)}}),f=u.enc={},g=f.Hex={stringify:function(y){for(var d=y.words,_=y.sigBytes,v=[],w=0;w<_;w++){var D=d[w>>>2]>>>24-w%4*8&255;v.push((D>>>4).toString(16)),v.push((D&15).toString(16));}return v.join("")},parse:function(y){for(var d=y.length,_=[],v=0;v<d;v+=2)_[v>>>3]|=parseInt(y.substr(v,2),16)<<24-v%8*4;return new h.init(_,d/2)}},p=f.Latin1={stringify:function(y){for(var d=y.words,_=y.sigBytes,v=[],w=0;w<_;w++){var D=d[w>>>2]>>>24-w%4*8&255;v.push(String.fromCharCode(D));}return v.join("")},parse:function(y){for(var d=y.length,_=[],v=0;v<d;v++)_[v>>>2]|=(y.charCodeAt(v)&255)<<24-v%4*8;return new h.init(_,d)}},m=f.Utf8={stringify:function(y){try{return decodeURIComponent(escape(p.stringify(y)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(y){return p.parse(unescape(encodeURIComponent(y)))}},C=l.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(y){typeof y=="string"&&(y=m.parse(y)),this._data.concat(y),this._nDataBytes+=y.sigBytes;},_process:function(y){var d,_=this._data,v=_.words,w=_.sigBytes,D=this.blockSize,O=D*4,P=w/O;y?P=r.ceil(P):P=r.max((P|0)-this._minBufferSize,0);var E=P*D,F=r.min(E*4,w);if(E){for(var R=0;R<E;R+=D)this._doProcessBlock(v,R);d=v.splice(0,E),_.sigBytes-=F;}return new h.init(d,F)},clone:function(){var y=c.clone.call(this);return y._data=this._data.clone(),y},_minBufferSize:0});l.Hasher=C.extend({cfg:c.extend(),init:function(y){this.cfg=this.cfg.extend(y),this.reset();},reset:function(){C.reset.call(this),this._doReset();},update:function(y){return this._append(y),this._process(),this},finalize:function(y){y&&this._append(y);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(y){return function(d,_){return new y.init(_).finalize(d)}},_createHmacHelper:function(y){return function(d,_){return new b.HMAC.init(y,_).finalize(d)}}});var b=u.algo={};return u})(Math);return t});}),jF=RC((n,e)=>{(function(t,r){typeof n=="object"?e.exports=n=r(VF()):typeof define=="function"&&define.amd?define(["./core"],r):r(t.CryptoJS);})(n,function(t){return (function(){var r=t,i=r.lib,a=i.WordArray,s=i.Hasher,o=r.algo,u=[],l=o.SHA1=s.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878,3285377520]);},_doProcessBlock:function(c,h){for(var f=this._hash.words,g=f[0],p=f[1],m=f[2],C=f[3],b=f[4],y=0;y<80;y++){if(y<16)u[y]=c[h+y]|0;else {var d=u[y-3]^u[y-8]^u[y-14]^u[y-16];u[y]=d<<1|d>>>31;}var _=(g<<5|g>>>27)+b+u[y];y<20?_+=(p&m|~p&C)+1518500249:y<40?_+=(p^m^C)+1859775393:y<60?_+=(p&m|p&C|m&C)-1894007588:_+=(p^m^C)-899497514,b=C,C=m,m=p<<30|p>>>2,p=g,g=_;}f[0]=f[0]+g|0,f[1]=f[1]+p|0,f[2]=f[2]+m|0,f[3]=f[3]+C|0,f[4]=f[4]+b|0;},_doFinalize:function(){var c=this._data,h=c.words,f=this._nDataBytes*8,g=c.sigBytes*8;return h[g>>>5]|=128<<24-g%32,h[(g+64>>>9<<4)+14]=Math.floor(f/4294967296),h[(g+64>>>9<<4)+15]=f,c.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var c=s.clone.call(this);return c._hash=this._hash.clone(),c}});r.SHA1=s._createHelper(l),r.HmacSHA1=s._createHmacHelper(l);})(),t.SHA1});});var LF;(n=>(n.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),n.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),n.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),n.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(LF||={});$F(jF());var Qp=An(pr()),Or=An(jC());var LC=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('vite.cjs', document.baseURI).href)));function XF(n){let e=ie.normalize(n);return e.length>1&&e[e.length-1]===ie.sep&&(e=e.substring(0,e.length-1)),e}var YF=/[\\/]/g;function MC(n,e){return n.replace(YF,e)}var QF=/^[a-z]:[\\/]$/i;function ZF(n){return n==="/"||QF.test(n)}function Rp(n,e){let{resolvePaths:t,normalizePath:r,pathSeparator:i}=e,a=process.platform==="win32"&&n.includes("/")||n.startsWith(".");if(t&&(n=ie.resolve(n)),(r||a)&&(n=XF(n)),n===".")return "";let s=n[n.length-1]!==i;return MC(s?n+i:n,i)}function WC(n,e){return e+n}function eI(n,e){return function(t,r){return r.startsWith(n)?r.slice(n.length)+t:MC(ie.relative(n,r),e.pathSeparator)+e.pathSeparator+t}}function tI(n){return n}function nI(n,e,t){return e+n+t}function rI(n,e){let{relativePaths:t,includeBasePath:r}=e;return t&&n?eI(n,e):r?WC:tI}function iI(n){return function(e,t){t.push(e.substring(n.length)||".");}}function sI(n){return function(e,t,r){let i=e.substring(n.length)||".";r.every(a=>a(i,true))&&t.push(i);}}var aI=(n,e)=>{e.push(n||".");},oI=(n,e,t)=>{let r=n||".";t.every(i=>i(r,true))&&e.push(r);},uI=()=>{};function lI(n,e){let{includeDirs:t,filters:r,relativePaths:i}=e;return t?i?r&&r.length?sI(n):iI(n):r&&r.length?oI:aI:uI}var cI=(n,e,t,r)=>{r.every(i=>i(n,false))&&t.files++;},hI=(n,e,t,r)=>{r.every(i=>i(n,false))&&e.push(n);},dI=(n,e,t,r)=>{t.files++;},fI=(n,e)=>{e.push(n);},pI=()=>{};function mI(n){let{excludeFiles:e,filters:t,onlyCounts:r}=n;return e?pI:t&&t.length?r?cI:hI:r?dI:fI}var gI=n=>n,yI=()=>[""].slice(0,0);function vI(n){return n.group?yI:gI}var CI=(n,e,t)=>{n.push({directory:e,files:t,dir:e});},bI=()=>{};function _I(n){return n.group?CI:bI}var SI=function(n,e,t){let{queue:r,fs:i,options:{suppressErrors:a}}=e;r.enqueue(),i.realpath(n,(s,o)=>{if(s)return r.dequeue(a?null:s,e);i.stat(o,(u,l)=>{if(u)return r.dequeue(a?null:u,e);if(l.isDirectory()&&GC(n,o,e))return r.dequeue(null,e);t(l,o),r.dequeue(null,e);});});},EI=function(n,e,t){let{queue:r,fs:i,options:{suppressErrors:a}}=e;r.enqueue();try{let s=i.realpathSync(n),o=i.statSync(s);if(o.isDirectory()&&GC(n,s,e))return;t(o,s);}catch(s){if(!a)throw s}};function wI(n,e){return !n.resolveSymlinks||n.excludeSymlinks?null:e?EI:SI}function GC(n,e,t){if(t.options.useRealPaths)return AI(e,t);let r=ie.dirname(n),i=1;for(;r!==t.root&&i<2;){let a=t.symlinks.get(r);!!a&&(a===e||a.startsWith(e)||e.startsWith(a))?i++:r=ie.dirname(r);}return t.symlinks.set(n,e),i>1}function AI(n,e){return e.visited.includes(n+e.options.pathSeparator)}var DI=n=>n.counts,xI=n=>n.groups,PI=n=>n.paths,OI=n=>n.paths.slice(0,n.options.maxFiles),TI=(n,e,t)=>(_l(e,t,n.counts,n.options.suppressErrors),null),NI=(n,e,t)=>(_l(e,t,n.paths,n.options.suppressErrors),null),FI=(n,e,t)=>(_l(e,t,n.paths.slice(0,n.options.maxFiles),n.options.suppressErrors),null),II=(n,e,t)=>(_l(e,t,n.groups,n.options.suppressErrors),null);function _l(n,e,t,r){e(n&&!r?n:null,t);}function kI(n,e){let{onlyCounts:t,group:r,maxFiles:i}=n;return t?e?DI:TI:r?e?xI:II:i?e?OI:FI:e?PI:NI}var HC={withFileTypes:true},RI=(n,e,t,r,i)=>{if(n.queue.enqueue(),r<0)return n.queue.dequeue(null,n);let{fs:a}=n;n.visited.push(e),n.counts.directories++,a.readdir(e||".",HC,(s,o=[])=>{i(o,t,r),n.queue.dequeue(n.options.suppressErrors?null:s,n);});},$I=(n,e,t,r,i)=>{let{fs:a}=n;if(r<0)return;n.visited.push(e),n.counts.directories++;let s=[];try{s=a.readdirSync(e||".",HC);}catch(o){if(!n.options.suppressErrors)throw o}i(s,t,r);};function VI(n){return n?$I:RI}var jI=class{count=0;constructor(n){this.onQueueEmpty=n;}enqueue(){return this.count++,this.count}dequeue(n,e){this.onQueueEmpty&&(--this.count<=0||n)&&(this.onQueueEmpty(n,e),n&&(e.controller.abort(),this.onQueueEmpty=void 0));}},LI=class{_files=0;_directories=0;set files(n){this._files=n;}get files(){return this._files}set directories(n){this._directories=n;}get directories(){return this._directories}get dirs(){return this._directories}},qI=class{aborted=false;abort(){this.aborted=true;}},JC=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(n,e,t){this.isSynchronous=!t,this.callbackInvoker=kI(e,this.isSynchronous),this.root=Rp(n,e),this.state={root:ZF(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new LI,options:e,queue:new jI((r,i)=>this.callbackInvoker(i,r,t)),symlinks:new Map,visited:[""].slice(0,0),controller:new qI,fs:e.fs||KF__namespace},this.joinPath=rI(this.root,e),this.pushDirectory=lI(this.root,e),this.pushFile=mI(e),this.getArray=vI(e),this.groupFiles=_I(e),this.resolveSymlink=wI(e,this.isSynchronous),this.walkDirectory=VI(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(n,e,t)=>{let{paths:r,options:{filters:i,resolveSymlinks:a,excludeSymlinks:s,exclude:o,maxFiles:u,signal:l,useRealPaths:c,pathSeparator:h},controller:f}=this.state;if(f.aborted||l&&l.aborted||u&&r.length>u)return;let g=this.getArray(this.state.paths);for(let p=0;p<n.length;++p){let m=n[p];if(m.isFile()||m.isSymbolicLink()&&!a&&!s){let C=this.joinPath(m.name,e);this.pushFile(C,g,this.state.counts,i);}else if(m.isDirectory()){let C=nI(m.name,e,this.state.options.pathSeparator);if(o&&o(m.name,C))continue;this.pushDirectory(C,r,i),this.walkDirectory(this.state,C,C,t-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let C=WC(m.name,e);this.resolveSymlink(C,this.state,(b,y)=>{if(b.isDirectory()){if(y=Rp(y,this.state.options),o&&o(m.name,c?y:C+h))return;this.walkDirectory(this.state,y,c?y:C+h,t-1,this.walk);}else {y=c?y:C;let d=ie.basename(y),_=Rp(ie.dirname(y),this.state.options);y=this.joinPath(d,_),this.pushFile(y,g,this.state.counts,i);}});}}this.groupFiles(this.state.groups,e,g);}};function BI(n,e){return new Promise((t,r)=>{zC(n,e,(i,a)=>{if(i)return r(i);t(a);});})}function zC(n,e,t){new JC(n,e,t).start();}function MI(n,e){return new JC(n,e).start()}var qC=class{constructor(n,e){this.root=n,this.options=e;}withPromise(){return BI(this.root,this.options)}withCallback(n){zC(this.root,this.options,n);}sync(){return MI(this.root,this.options)}},UC=null;try{LC.resolve("picomatch"),UC=LC("picomatch");}catch{}var KC=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:ie.sep,filters:[]};globFunction;constructor(n){this.options={...this.options,...n},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(n){return this.options.pathSeparator=n,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(n){return this.options.maxDepth=n,this}withMaxFiles(n){return this.options.maxFiles=n,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:n=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=n,this.withFullPaths()}withAbortSignal(n){return this.options.signal=n,this}normalize(){return this.options.normalizePath=true,this}filter(n){return this.options.filters.push(n),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(n){return this.options.exclude=n,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(n){return new qC(n||".",this.options)}withGlobFunction(n){return this.globFunction=n,this}crawlWithOptions(n,e){return this.options={...this.options,...e},new qC(n||".",this.options)}glob(...n){return this.globFunction?this.globWithOptions(n):this.globWithOptions(n,{dot:true})}globWithOptions(n,...e){let t=this.globFunction||UC;if(!t)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[n.join("\0")];return r||(r=t(n,...e),this.globCache[n.join("\0")]=r),this.options.filters.push(i=>r(i)),this}};var Ai=An(Cb()),Ik=Array.isArray,Eb=/\\/g,kk=/^[A-Za-z]:$/,wb=process.platform==="win32",Rk=/^(\/?\.\.)+$/;function $k(n,e={}){let t=n.length,r=Array(t),i=Array(t),a,s;for(a=0;a<t;a++){let o=Ab(n[a]);r[a]=o;let u=o.length,l=Array(u);for(s=0;s<u;s++)l[s]=(0, Ai.default)(o[s],e);i[a]=l;}return o=>{let u=o.split("/");if(u[0]===".."&&Rk.test(o))return true;for(a=0;a<t;a++){let l=r[a],c=i[a],h=u.length,f=Math.min(h,l.length);for(s=0;s<f;){let g=l[s];if(g.includes("/"))return true;if(!c[s](u[s]))break;if(!e.noglobstar&&g==="**")return true;s++;}if(s===h)return true}return false}}var Vk=/^[A-Z]:\/$/i,jk=wb?n=>Vk.test(n):n=>n==="/";function bb(n,e,t){if(n===e||e.startsWith(`${n}/`)){if(t){let i=n.length+ +!jk(n);return (a,s)=>a.slice(i,s?-1:void 0)||"."}let r=e.slice(n.length+1);return r?(i,a)=>{if(i===".")return r;let s=`${r}/${i}`;return a?s.slice(0,-1):s}:(i,a)=>a&&i!=="."?i.slice(0,-1):i}return t?r=>ie.posix.relative(n,r)||".":r=>ie.posix.relative(n,`${e}/${r}`)||"."}function Lk(n,e){if(e.startsWith(`${n}/`)){let t=e.slice(n.length+1);return r=>`${t}/${r}`}return t=>{let r=ie.posix.relative(n,`${e}/${t}`);return t[t.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function _b(n){return n.replace(kk,e=>`${e}/`)}var qk={parts:true};function Ab(n){var e;let t=Ai.default.scan(n,qk);return !((e=t.parts)===null||e===void 0)&&e.length?t.parts:[n]}var Bk=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Mk=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Wk=n=>n.replace(Bk,"\\$&"),Gk=n=>n.replace(Mk,"\\$&"),Hk=wb?Gk:Wk;function Jk(n,e){let t=Ai.default.scan(n);return t.isGlob||t.negated}function Zs(...n){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...n);}function Db(n){return typeof n=="string"?[n]:n??[]}var zk=/^(\/?\.\.)+/,Uk=/\\(?=[()[\]{}!*+?@|])/g;function zp(n,e,t,r){var i;let a=e.cwd,s=n;n[n.length-1]==="/"&&(s=n.slice(0,-1)),s[s.length-1]!=="*"&&e.expandDirectories&&(s+="/**");let o=Hk(a);s=ie.isAbsolute(s.replace(Uk,""))?ie.posix.relative(o,s):ie.posix.normalize(s);let u=(i=zk.exec(s))===null||i===void 0?void 0:i[0],l=Ab(s);if(u){let h=(u.length+1)/3,f=0,g=o.split("/");for(;f<h&&l[f+h]===g[g.length+f-h];)s=s.slice(0,(h-f-1)*3)+s.slice((h-f)*3+l[f+h].length+1)||".",f++;let p=ie.posix.join(a,u.slice(f*3));p[0]!=="."&&t.root.length>p.length&&(t.root=_b(p),t.depthOffset=-h+f);}if(!r&&t.depthOffset>=0){var c;(c=t.commonPath)!==null&&c!==void 0||(t.commonPath=l);let h=[],f=Math.min(t.commonPath.length,l.length);for(let g=0;g<f;g++){let p=l[g];if(p==="**"&&!l[g+1]){h.pop();break}if(g===l.length-1||p!==t.commonPath[g]||Jk(p))break;h.push(p);}t.depthOffset=h.length,t.commonPath=h,t.root=_b(h.length>0?ie.posix.join(a,...h):a);}return s}function Kk(n,e,t){let r=[],i=[];for(let a of n.ignore)a&&(a[0]!=="!"||a[1]==="(")&&i.push(zp(a,n,t,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?r.push(zp(a,n,t,false)):(a[1]!=="!"||a[2]==="(")&&i.push(zp(a.slice(1),n,t,true)));return {match:r,ignore:i}}function Xk(n,e){let t=n.cwd,r={root:t,depthOffset:0},i=Kk(n,e,r);n.debug&&Zs("internal processing patterns:",i);let{absolute:a,caseSensitiveMatch:s,debug:o,dot:u,followSymbolicLinks:l,onlyDirectories:c}=n,h=r.root.replace(Eb,""),f={dot:u,nobrace:n.braceExpansion===false,nocase:!s,noextglob:n.extglob===false,noglobstar:n.globstar===false,posix:true},g=(0, Ai.default)(i.match,f),p=(0, Ai.default)(i.ignore,f),m=$k(i.match,f),C=bb(t,h,a),b=a?C:bb(t,h,true),y=(v,w)=>{let D=b(w,true);return D!=="."&&!m(D)||p(D)},d;n.deep!==void 0&&(d=Math.round(n.deep-r.depthOffset));let _=new KC({filters:[o?(v,w)=>{let D=C(v,w),O=g(D)&&!p(D);return O&&Zs(`matched ${D}`),O}:(v,w)=>{let D=C(v,w);return g(D)&&!p(D)}],exclude:o?(v,w)=>{let D=y(v,w);return Zs(`${D?"skipped":"crawling"} ${w}`),D}:y,fs:n.fs,pathSeparator:"/",relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:c,includeDirs:c||!n.onlyFiles,maxDepth:d,signal:n.signal}).crawl(h);return n.debug&&Zs("internal properties:",{...r,root:h}),[_,t!==h&&!a&&Lk(t,h)]}function Yk(n,e){if(e)for(let t=n.length-1;t>=0;t--)n[t]=e(n[t]);return n}var Sb={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function Qk(n){let e=Object.assign({},n);for(let t in Sb)e[t]===void 0&&Object.assign(e,{[t]:Sb[t]});return e.cwd=(e.cwd instanceof URL?url.fileURLToPath(e.cwd):ie.resolve(e.cwd||process.cwd())).replace(Eb,"/"),e.ignore=Db(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||KF.readdir,readdirSync:e.fs.readdirSync||KF.readdirSync,realpath:e.fs.realpath||KF.realpath,realpathSync:e.fs.realpathSync||KF.realpathSync,stat:e.fs.stat||KF.stat,statSync:e.fs.statSync||KF.statSync}),e.debug&&Zs("globbing with options:",e),e}function Zk(n,e={}){var t;if(n&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=Ik(n)||typeof n=="string",i=Db((t=r?n:n.patterns)!==null&&t!==void 0?t:"**/*"),a=Qk(r?e:n);return i.length>0?Xk(a,i):[]}async function wl(n,e){let[t,r]=Zk(n,e);return t?Yk(await t.withPromise(),r):[]}var xb="1.2.2";var Sn=Or.default.cyan("(pixi-vn-ink)"),Rb="virtual:pixi-vn-ink",Up=`\0${Rb}`,nR="manifest.json",$b=/\[(name|ext|extname|file|path|dir)\]/g,Pb="ink";function Ob(n){if(typeof n=="string")return {type:"literal",value:n};if(n instanceof RegExp)return {type:"regexp",source:n.source,flags:n.flags};try{return {type:"zod",schema:zod.toJSONSchema(n)}}catch{return {type:"literal",value:""}}}function Un(n){return n.replaceAll("\\","/")}function Al(n){let e=Un(n.trim());if(!e)throw new Error("vitePluginInk option `inkGlob` must not be empty.");let t=e.replace(/^\.?\//,"");if(!t||t.startsWith("../"))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");return t}function Tb(n,e){let t=Un(e).split("/"),r=[];for(let i of t)if(!(i==="."||i==="")){if(/[*!?[\]{}()]/.test(i))break;r.push(i);}return ie__default.default.resolve(n,...r)}function Nb(n,e){if(!e)return;let t=e.trim();if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must not be empty.");return ie__default.default.isAbsolute(t)?ie__default.default.normalize(t):ie__default.default.resolve(n,t)}function Fb(n,e,t){if(!t)return ie__default.default.join(e,nR);let r=t.trim();if(!r)throw new Error("vitePluginInk option `inkJsonManifestPath` must not be empty.");return ie__default.default.isAbsolute(r)?ie__default.default.normalize(r):ie__default.default.resolve(n,r)}function Ib(n){let e=n.search($b);if(e===-1)return ie__default.default.dirname(n);let t=n.slice(0,e).replace(/[\\/]+$/g,"");if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must start with a static directory before placeholders.");return ie__default.default.normalize(t)}function Di(n,e){let t=ie__default.default.relative(n,e);return !t.startsWith("..")&&!ie__default.default.isAbsolute(t)}function rR(n,e,t,r){let i=Un(ie__default.default.relative(t,r)),a=ie__default.default.posix.parse(i),s=Un(ie__default.default.relative(e,r)),o=ie__default.default.posix.dirname(s),u=ie__default.default.posix.dirname(i),l={name:a.name,ext:a.ext.startsWith(".")?a.ext.slice(1):a.ext,extname:a.ext,file:i,path:u==="."?"":`${u}/`,dir:o==="."?"":`${o}/`},c=Un(n).replace($b,(h,f)=>l[f]??"");return ie__default.default.normalize(c)}function iR(n,e,t){return Di(t,n)?`/${Un(ie__default.default.relative(t,n))}`:Di(e,n)?Un(ie__default.default.relative(e,n)):Un(n)}function Kp(n,e,t){let r=Ht.getUnknownHashtagCommands(n,e);r.forEach(({command:i,line:a})=>{t(`Unknown hashtag command "# ${i}": no registered handler matched this command.`,a);}),r.length>0&&t(`Hashtag command metadata is available via ${xi}.`);}function Xp(n,e,t){Ht.getHashtagKeySchemaIssues(n,e).forEach(({command:i,line:a,key:s,element:o,message:u})=>{t(`Hashtag command "# ${i}": "${s}" section ${o} - ${u}`,a);});}function Yp(n,e,t){if(e.length===0)return;Ht.getUnknownDivertTargets(n,e).forEach(({target:i,line:a})=>{t(`Divert target "${i}" not found in any known label source.`,a);});}async function sR(n,e,t){let r=e.get(n);return r||(r=(async()=>{try{let i=await fetch(n);if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let a=await i.json();return Ht.getSchemaValidator(a)}catch(i){t(`Could not load/compile JSON schema from "${n}" (${i instanceof Error?i.message:String(i)}). Skipping schema validation.`);return}})(),e.set(n,r)),r}function aR(n,e){let t=`# ${n}`;if(!e)return Or.default.gray(t);let r=new RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g"),i="",a=0;for(let s of t.matchAll(r)){let o=s.index??a;i+=Or.default.gray(t.slice(a,o)),i+=Or.default.yellow(s[0]),a=o+s[0].length;}return i+=Or.default.gray(t.slice(a)),i}async function oR(n,e,t,r){let i=n.$schema;if(!i)return;let a=await sR(i,t,r);if(!a)return;let s=Ht.validateAgainstJsonSchema(n,a);for(let o of s){let u=o.origin?` \u2014 from ink source:
103
+ ${aR(o.origin,o.element)}`:"";r(`${e}: ${o.element} - ${o.message}${u}`);}}function kb(n){return new Promise((e,t)=>{let r="";n.on("data",i=>{r+=i.toString();}),n.on("end",()=>e(r)),n.on("error",t);})}function uR(n){let{inkGlob:e,inkJsonOutputPattern:t,inkJsonManifestPath:r,characters:i}=n??{},a=!!t,s,o=[],u=[],l,c,h,f=[],g,p,m,C=new Map,b=async()=>{let P=pn.info(),E=xr.info();o=P.map(({name:F,description:R,validation:k,deprecated:A,keySchemas:x})=>({name:F,description:R,validation:Ob(k),deprecated:A,keySchemas:x})),u=E.map(({name:F,description:R,validation:k,type:A})=>({name:F,description:R,validation:Ob(k),type:A}));},y=P=>P?.find(E=>E.name==="vite-plugin-pixi-vn"),d=P=>{let E=P?.find(F=>F.name==="vite-plugin-nqtr");return [y(P)?.api?.contentLoaded,E?.api?.contentLoaded].filter(F=>!!F)},_=async P=>{let E=P?.api;if(!E)return;let F=f,R=JSON.stringify(F);if(R!==g)try{if(F.length===0&&E.clearExternalLabels)await E.clearExternalLabels(Pb);else if(E.setExternalLabels)await E.setExternalLabels(Pb,F);else return;g=R;}catch(k){let A=k instanceof Error?k:new Error(String(k));s?.logger.error(`${Sn} Failed to sync Ink labels with vite-plugin-pixi-vn.`,{error:A,timestamp:true});}},v=P=>{if(!a||!c)return false;let E=ie__default.default.resolve(P);return h&&E===h?true:Di(c,E)},w=()=>{m!==void 0&&clearTimeout(m),m=setTimeout(()=>{m=void 0,O().then(async()=>{await _(y(p?.config.plugins));let P=p?.moduleGraph.getModuleById(Up);P&&p?.moduleGraph.invalidateModule(P),p?.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?l??[]:void 0}});}).catch(P=>{let E=P instanceof Error?P:new Error(String(P));s?.logger.error(`${Sn} Failed to re-export Ink JSON files after characters update.`,{error:E,timestamp:true});});},150);},D=async()=>{if(!s||!e)return [];let P=Al(e),E=await wl(P,{absolute:true,cwd:s.root,onlyFiles:true}),F=[];for(let R of E)try{let k=await ln__default.default.readFile(R,"utf-8"),A=Us(k,{characters:i??[]});A&&F.push(...Object.keys(A.labels??{}));}catch{}return Array.from(new Set(F)).sort((R,k)=>R.localeCompare(k))},O=async()=>{if(!s||!e){l=void 0,f=[];return}let P=Nb(s.root,t);if(!P){l=void 0,f=[],c=void 0,h=void 0;return}let E=Al(e),F=Ib(P);c=ie__default.default.resolve(F);let R=Tb(s.root,E);if(!Di(s.root,R))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");let k=await wl(E,{absolute:true,cwd:s.root,onlyFiles:true}),A=[],x=[],Ce=new Set,j=y(s.plugins)?.api?.characters??[],ce=[...i??[],...j];await ln__default.default.mkdir(F,{recursive:true});let Le=new Map;for(let pe of k){let At=await ln__default.default.readFile(pe,"utf-8");Le.set(pe,At);let N;try{N=Us(At,{characters:ce});}catch(I){let z=I instanceof Error?I:new Error(String(I));s.logger.error(`${Sn} Failed to convert "${pe}" to JSON.`,{error:z,timestamp:true});continue}let W=rR(P,s.root,R,pe);if(!Di(F,W)){s.logger.error(`${Sn} Output path "${W}" escapes managed directory "${F}".`,{timestamp:true});continue}if(Ce.add(ie__default.default.resolve(W)),!N){await ln__default.default.rm(W,{force:true});continue}x.push(N),await ln__default.default.mkdir(ie__default.default.dirname(W),{recursive:true}),await ln__default.default.writeFile(W,`${JSON.stringify(N,null,2)}
104
+ `,"utf-8"),A.push(iR(W,s.root,s.publicDir)),await oR(N,pe,C,I=>s.logger.warn(`${Sn} ${I}`,{timestamp:true}));}let xe=Fb(s.root,F,r);h=ie__default.default.resolve(xe);let En=await wl("**/*.json",{absolute:true,cwd:F,onlyFiles:true});for(let pe of En)ie__default.default.resolve(pe)!==ie__default.default.resolve(xe)&&!Ce.has(ie__default.default.resolve(pe))&&await ln__default.default.rm(pe,{force:true});A.sort((pe,At)=>pe.localeCompare(At)),l=x;let wn=x.flatMap(pe=>Object.keys(pe.labels??{}));f=Array.from(new Set(wn)).sort((pe,At)=>pe.localeCompare(At));let cn=wn.length,Jt=y(s.plugins)?.api?.labels??[],J=[...f,...Jt];for(let[pe,At]of Le)Kp(At,o,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true})),Xp(At,o,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true})),Yp(At,J,(N,W)=>s.logger.warn(`${W!==void 0?`${pe}:${W}`:pe}: ${N}`,{timestamp:true}));s.logger.info(`${Sn} ${Or.default.dim(`${k.length} file(s) exported: ${cn} label(s), ${o.length} hashtag-command(s), ${u.length} text-replace(s)`)}`,{timestamp:true}),await ln__default.default.mkdir(ie__default.default.dirname(xe),{recursive:true}),await ln__default.default.writeFile(xe,`${JSON.stringify(A,null,2)}
105
+ `,"utf-8");};return {name:"vite-plugin-ink",enforce:"pre",configResolved(P){s=P,c=void 0,h=void 0;let E=e?Al(e):void 0;if(E){let F=Tb(P.root,E);if(!Di(P.root,F))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.")}if(t&&!e)throw new Error("vitePluginInk option `inkJsonOutputPattern` requires `inkGlob` to be set.");if(t){let F=Nb(P.root,t);if(!F)return;let R=Ib(F);if(c=ie__default.default.resolve(R),h=ie__default.default.resolve(Fb(P.root,R,r)),ie__default.default.resolve(R)===ie__default.default.resolve(P.root))throw new Error("vitePluginInk option `inkJsonOutputPattern` must target a directory different from Vite `root`.")}},async buildStart(){let P=y(s?.plugins);f=await D(),await _(P),await Promise.all(d(s?.plugins)),await b(),await O(),await _(P);},configureServer(P){p=P,P.middlewares.use(async(R,k,A)=>{let x=R.url,Ce=R.method;if(x===xi){if(Ce==="GET"){k.setHeader("Content-Type","application/json"),k.end(JSON.stringify(o));return}if(Ce==="POST"){try{let j=await kb(R);o=JSON.parse(j),k.statusCode=204,k.end();}catch(j){s?.logger.warn(`${Sn} Invalid JSON body for POST ${xi}: ${String(j)}`,{timestamp:true}),k.statusCode=400,k.end();}return}}if(x===Dl&&Ce==="GET"){k.setHeader("Content-Type","application/json");let j={version:xb,schemaUrl:sa};k.end(JSON.stringify(j));return}if(x===ea){if(Ce==="GET"){k.setHeader("Content-Type","application/json"),k.end(JSON.stringify(u));return}if(Ce==="POST"){try{let j=await kb(R);u=JSON.parse(j),k.statusCode=204,k.end();}catch(j){s?.logger.warn(`${Sn} Invalid JSON body for POST ${ea}: ${String(j)}`,{timestamp:true}),k.statusCode=400,k.end();}return}}A();});let E=y(P.config.plugins);Promise.all(d(P.config.plugins)).then(async()=>{await b(),await O(),await _(E);}).catch(R=>{let k=R instanceof Error?R:new Error(String(R));s?.logger.error(`${Sn} Failed to export Ink JSON files during server initialization or restart.`,{error:k,timestamp:true});});let F=E?.api?.onReload;F&&F(()=>{b().then(()=>w());});},resolveId(P){if(P===Rb)return Up},load(P){if(P===Up){if(!e)return ["export const inkJsons = undefined;","export default [];"].join(`
106
+ `);let E=Al(e);return [`const modules = import.meta.glob(${JSON.stringify(`/${E}`)}, { eager: true, import: 'default' });`,`export const inkJsons = ${JSON.stringify(a?l??[]:void 0)};`,"export default Object.values(modules);"].join(`
107
+ `)}},hotUpdate:{order:"post",async handler({type:P,file:E,server:F,read:R}){if(E.endsWith(".ink")){if(P!=="delete"){let k=await R(),{issues:A}=Ht.compile(k),x;A.forEach(({line:j,message:ce,type:Le})=>{Le===Qp.ErrorType.Warning?F.config.logger.warn(`${E}:${j} ${ce}`,{timestamp:true}):(F.config.logger.error(`${E}:${j} ${ce}`,{timestamp:true}),x=ce);}),Kp(k,o,(j,ce)=>F.config.logger.warn(`${ce!==void 0?`${E}:${ce}`:E}: ${j}`,{timestamp:true})),Xp(k,o,(j,ce)=>F.config.logger.warn(`${ce!==void 0?`${E}:${ce}`:E}: ${j}`,{timestamp:true}));let Ce=y(F.config.plugins)?.api?.labels??[];Yp(k,[...f,...Ce],(j,ce)=>F.config.logger.warn(`${ce!==void 0?`${E}:${ce}`:E}: ${j}`,{timestamp:true})),await O(),await _(y(F.config.plugins)),x?F.ws.send({type:"error",err:{message:x,stack:E,plugin:"vite-plugin-ink"}}):(F.ws.send({type:"custom",event:"ink-error-cleared",data:{}}),F.ws.send({type:"custom",event:"ink-updated",data:{inkText:k,inkJson:a?l??[]:void 0}}));}else await O(),await _(y(F.config.plugins)),F.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?l??[]:void 0}});return []}if(E.endsWith(".json")&&v(E))return await _(y(F.config.plugins)),F.ws.send({type:"custom",event:"ink-updated",data:{inkJson:l??[]}}),[]}},async transform(P,E){if(!E.endsWith(".ink"))return null;let F=await ln__default.default.readFile(E,"utf-8"),{issues:R}=Ht.compile(F);R.forEach(({line:A,message:x,type:Ce})=>{Ce===Qp.ErrorType.Warning?this.warn(`${E}:${A} ${x}`):this.error(`${E}:${A} ${x}`);}),Kp(F,o,(A,x)=>this.warn({message:A,loc:x!==void 0?{line:x,column:0}:void 0})),Xp(F,o,(A,x)=>this.warn({message:A,loc:x!==void 0?{line:x,column:0}:void 0}));let k=y(s?.plugins)?.api?.labels??[];return Yp(F,[...f,...k],(A,x)=>this.warn({message:A,loc:x!==void 0?{line:x,column:0}:void 0})),{code:`export default ${JSON.stringify(F)};`,map:null}}}}exports.INK_DEV_API_HASHTAG_COMMANDS=xi;exports.INK_DEV_API_INFO=Dl;exports.INK_DEV_API_TEXT_REPLACES=ea;exports.vitePluginInk=uR;