@drincs/pixi-vn-ink 1.1.1 → 1.1.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,64 +1,64 @@
1
- 'use strict';var zod=require('zod'),pixiVn=require('@drincs/pixi-vn');require('@drincs/pixi-vn/canvas');var characters=require('@drincs/pixi-vn/characters'),narration=require('@drincs/pixi-vn/narration');require('@drincs/pixi-vn/sound');var storage=require('@drincs/pixi-vn/storage'),uS=require('ajv'),Pt=require('fs/promises'),X=require('path'),rv=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 uS__default=/*#__PURE__*/_interopDefault(uS);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var X__default=/*#__PURE__*/_interopDefault(X);var rv__namespace=/*#__PURE__*/_interopNamespace(rv);var uf=Object.create;var Ru=Object.defineProperty;var cf=Object.getOwnPropertyDescriptor;var hf=Object.getOwnPropertyNames;var pf=Object.getPrototypeOf,ff=Object.prototype.hasOwnProperty;var Kt=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var P=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var df=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hf(e))!ff.call(i,r)&&r!==t&&Ru(i,r,{get:()=>e[r],enumerable:!(n=cf(e,r))||n.enumerable});return i};var mn=(i,e,t)=>(t=i!=null?uf(pf(i)):{},df(Ru(t,"default",{value:i,enumerable:true}),i));var Ha=P(Yi=>{Object.defineProperty(Yi,"__esModule",{value:true});Yi.CompilerOptions=void 0;var Ga=class{constructor(e=null,t=[],n=false,r=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=r,this.fileHandler=a;}};Yi.CompilerOptions=Ga;});var uc=P(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.DebugSourceRange=void 0;var Ja=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Qi.DebugSourceRange=Ja;});var en=P(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.ErrorType=void 0;var cc;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(cc||(Zi.ErrorType=cc={}));});var hc=P(er=>{Object.defineProperty(er,"__esModule",{value:true});er.Argument=void 0;var Ua=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};er.Argument=Ua;});var ie=P(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 ed(i,e){return i instanceof e?pc(i):null}be.asOrNull=ed;function td(i,e){if(i instanceof e)return pc(i);throw new Error(`${i} is not of type ${e}`)}be.asOrThrows=td;function nd(i){if(typeof i=="number")return i;throw new Error(`${i} is not a number`)}be.asNumberOrThrows=nd;function id(i){if(typeof i=="boolean")return i;throw new Error(`${i} is not a boolean`)}be.asBooleanOrThrows=id;function rd(i){return i.hasValidName&&i.name?i:null}be.asINamedContentOrNull=rd;function sd(i){return typeof i>"u"?null:i}be.nullIfUndefined=sd;function ad(i){return typeof i=="object"&&typeof i.Equals=="function"}be.isEquatable=ad;function pc(i,e){return i}function od(i){return i!=null}be.filterUndef=od;});var he=P(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.ParsedObject=void 0;var fc=ie(),za=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 n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);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 n=(0, fc.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let r of this.content){let a=r.Find&&r.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let r=Array.isArray(n)?n:[],a=(0, fc.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&r.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,r);return r},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,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};tr.ParsedObject=za;});var ir=P(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.AuthorWarning=void 0;var ld=he(),Ka=class extends ld.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};nr.AuthorWarning=Ka;});var We=P(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Path=void 0;var Sn=class i{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 i.Component&&arguments[1]instanceof i){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 i(e)}else return i.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 i;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new i,n=0;for(let r=0;r<e._components.length&&e._components[r].isParent;++r)n++;for(let r=0;r<this._components.length-n;++r)t._components.push(this._components[r]);for(let r=n;r<e._components.length;++r)t._components.push(e._components[r]);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 n of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new i.Component(parseInt(n))):this._components.push(new i.Component(n));}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,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new i;return t._components.push(...this._components),t._components.push(e),t}};Zn.Path=Sn;Sn.parentId="^";(function(i){class e{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==i.parentId}static ToParent(){return new e(i.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}i.Component=e;})(Sn||(Zn.Path=Sn={}));});var ei=P(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.Debug=void 0;var dc;(function(i){function e(n,r,a){t(n instanceof r,a);}i.AssertType=e;function t(n,r){if(!n)throw typeof r<"u"&&console.warn(r),console.trace&&console.trace(),new Error("")}i.Assert=t;})(dc||(rr.Debug=dc={}));});var we=P(En=>{Object.defineProperty(En,"__esModule",{value:true});En.throwNullException=En.NullException=void 0;var sr=class extends Error{};En.NullException=sr;function ud(i){throw new sr(`${i} is null or undefined`)}En.throwNullException=ud;});var je=P(or=>{Object.defineProperty(or,"__esModule",{value:true});or.InkObject=void 0;var bn=We(),ti=Ce(),Xa=ei(),An=ie(),ar=we(),Ya=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 n=t.ContentAtPath(e).obj;if(n){let r=n.debugMetadata;if(r!==null)return r.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new bn.Path;else {let e=[],t=this,n=(0, An.asOrNull)(t.parent,ti.Container);for(;n!==null;){let r=(0, An.asINamedContentOrNull)(t);if(r!=null&&r.hasValidName){if(r.name===null)return (0, ar.throwNullException)("namedChild.name");e.unshift(new bn.Path.Component(r.name));}else e.unshift(new bn.Path.Component(n.content.indexOf(t)));t=n,n=(0, An.asOrNull)(n.parent,ti.Container);}this._path=new bn.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, ar.throwNullException)("path");if(e.isRelative){let t=(0, An.asOrNull)(this,ti.Container);return t===null&&(Xa.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, An.asOrNull)(this.parent,ti.Container),Xa.Debug.Assert(t!==null,"Expected parent to be a container"),Xa.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, ar.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, ar.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),r=-1;for(let l=0;l<n;++l){let u=t.GetComponent(l),c=e.GetComponent(l);if(u.Equals(c))r=l;else break}if(r==-1)return e;let a=t.componentCount-1-r,s=[];for(let l=0;l<a;++l)s.push(bn.Path.Component.ToParent());for(let l=r+1;l<e.componentCount;++l)s.push(e.GetComponent(l));return new bn.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, An.asOrNull)(e,ti.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};or.InkObject=Ya;});var tn=P(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.StringBuilder=void 0;var Qa=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+=`
2
- `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,r)=>typeof t[r]<"u"?t[r]:n);}toString(){return this.string}Clear(){this.string="";}};lr.StringBuilder=Qa;});var Me=P(Dn=>{Object.defineProperty(Dn,"__esModule",{value:true});Dn.InkList=Dn.InkListItem=void 0;var pt=we(),cd=tn(),qe=class i{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 i(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 i){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new i(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!i.isLikeInkListItem(t))return i.Null;let n=t;return new i(n.originName,n.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)}};Dn.InkListItem=qe;var Za=class i extends Map{constructor(){if(super(arguments[0]instanceof i?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof i){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, pt.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, pt.throwNullException)("def.result");this.origins=[n.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 n;if(e==null||e=="")return new i;let r=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(r)return r.value===null?(0, pt.throwNullException)("listValue.value"):new i(r.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 qe){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, pt.throwNullException)("this.origins");for(let r of this.origins)if(r.name==n.originName){let a=r.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" 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 n=e,r=null;if(this.origins===null)return (0, pt.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, pt.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(r!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+r.name);r=a;}}if(r==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=i.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new qe(r.name,n),s=r.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(qe.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,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(n=>n.name==e?(t=n,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=qe.fromSerializedKey(e);if(t.originName===null)return (0, pt.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:qe.Null,Value:0};for(let[t,n]of this){let r=qe.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:r,Value:n});}return e}get minItem(){let e={Key:qe.Null,Value:0};for(let[t,n]of this){let r=qe.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:r,Value:n});}return e}get inverse(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=qe.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,r);}return e}get all(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=qe.fromSerializedKey(n);e.set(a.serialized(),r);}return e}Union(e){let t=new i(this);for(let[n,r]of e)t.set(n,r);return t}Intersect(e){let t=new i;for(let[n,r]of this)e.has(n)&&t.set(n,r);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new i(this);for(let[n]of e)t.delete(n);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[n]of t)if(!this.has(n))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 i(this.maxItem):new i}MinAsList(){return this.Count>0?new i(this.minItem):new i}ListWithSubRange(e,t){if(this.Count==0)return new i;let n=this.orderedItems,r=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?r=e:e instanceof i&&e.Count>0&&(r=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof i&&t.Count>0&&(a=t.maxItem.Value);let s=new i;s.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=r&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof i)||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,n]of this){let r=qe.fromSerializedKey(t);e.push({Key:r,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, pt.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, pt.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new cd.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let r=e[n].Key;if(r.itemName===null)return (0, pt.throwNullException)("item.itemName");t.Append(r.itemName);}return t.toString()}valueOf(){return NaN}};Dn.InkList=Za;});var ni=P(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.StoryException=void 0;var eo=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};ur.StoryException=eo;});var xn=P(Lt=>{Object.defineProperty(Lt,"__esModule",{value:true});Lt.tryParseFloat=Lt.tryParseInt=Lt.tryGetValueFromMap=void 0;function hd(i,e,t){if(i===null)return {result:t,exists:false};let n=i.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Lt.tryGetValueFromMap=hd;function pd(i,e=0){let t=parseInt(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Lt.tryParseInt=pd;function fd(i,e=0){let t=parseFloat(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Lt.tryParseFloat=fd;});var fe=P(de=>{Object.defineProperty(de,"__esModule",{value:true});de.ValueType=de.ListValue=de.VariablePointerValue=de.DivertTargetValue=de.StringValue=de.FloatValue=de.IntValue=de.BoolValue=de.Value=de.AbstractValue=void 0;var gc=je(),mc=We(),nn=Me(),dd=ni(),ii=ie(),Cc=xn(),Xe=we(),cr=class i extends gc.InkObject{static Create(e,t){if(t){if(t===ce.Int&&Number.isInteger(Number(e)))return new dt(Number(e));if(t===ce.Float&&!isNaN(e))return new gt(Number(e))}if(typeof e=="boolean")return new _n(!!e);if(typeof e=="string")return new _t(String(e));if(Number.isInteger(Number(e)))return new dt(Number(e));if(isNaN(e)){if(e instanceof mc.Path)return new hr((0, ii.asOrThrows)(e,mc.Path));if(e instanceof nn.InkList)return new pr((0, ii.asOrThrows)(e,nn.InkList))}else return new gt(Number(e));return null}Copy(){return (0, ii.asOrThrows)(i.Create(this.valueObject),gc.InkObject)}BadCastException(e){return new dd.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};de.AbstractValue=cr;var ft=class extends cr{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Xe.throwNullException)("Value.value"):this.value.toString()}};de.Value=ft;var _n=class extends ft{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return ce.Bool}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Int)return new dt(this.value?1:0);if(e==ce.Float)return new gt(this.value?1:0);if(e==ce.String)return new _t(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};de.BoolValue=_n;var dt=class extends ft{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ce.Int}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Bool)return new _n(this.value!==0);if(e==ce.Float)return new gt(this.value);if(e==ce.String)return new _t(""+this.value);throw this.BadCastException(e)}};de.IntValue=dt;var gt=class extends ft{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ce.Float}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Bool)return new _n(this.value!==0);if(e==ce.Int)return new dt(this.value);if(e==ce.String)return new _t(""+this.value);throw this.BadCastException(e)}};de.FloatValue=gt;var _t=class extends ft{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
- `,this._isInlineWhitespace=true,this.value===null)return (0, Xe.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return ce.String}get isTruthy(){return this.value===null?(0, Xe.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==ce.Int){let t=(0, Cc.tryParseInt)(this.value);if(t.exists)return new dt(t.result);throw this.BadCastException(e)}if(e==ce.Float){let t=(0, Cc.tryParseFloat)(this.value);if(t.exists)return new gt(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};de.StringValue=_t;var hr=class extends ft{constructor(e=null){super(e);}get valueType(){return ce.DivertTarget}get targetPath(){return this.value===null?(0, Xe.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+")"}};de.DivertTargetValue=hr;var to=class i extends ft{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, Xe.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return ce.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 i(this.variableName,this.contextIndex)}};de.VariablePointerValue=to;var pr=class i extends ft{get isTruthy(){return this.value===null?(0, Xe.throwNullException)("this.value"):this.value.Count>0}get valueType(){return ce.List}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==ce.Int){let t=this.value.maxItem;return t.Key.isNull?new dt(0):new dt(t.Value)}else if(e==ce.Float){let t=this.value.maxItem;return t.Key.isNull?new gt(0):new gt(t.Value)}else if(e==ce.String){let t=this.value.maxItem;return t.Key.isNull?new _t(""):new _t(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new nn.InkList:e instanceof nn.InkList?this.value=new nn.InkList(e):e instanceof nn.InkListItem&&typeof t=="number"&&(this.value=new nn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, ii.asOrNull)(e,i),r=(0, ii.asOrNull)(t,i);if(r&&r.value===null)return (0, Xe.throwNullException)("newList.value");if(n&&n.value===null)return (0, Xe.throwNullException)("oldList.value");n&&r&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}};de.ListValue=pr;var ce;(function(i){i[i.Bool=-1]="Bool",i[i.Int=0]="Int",i[i.Float=1]="Float",i[i.List=2]="List",i[i.String=3]="String",i[i.DivertTarget=4]="DivertTarget",i[i.VariablePointer=5]="VariablePointer";})(ce||(de.ValueType=ce={}));});var yc=P(fr=>{Object.defineProperty(fr,"__esModule",{value:true});fr.SearchResult=void 0;var gd=Ce(),no=class i{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof gd.Container?this.obj:null}copy(){let e=new i;return e.obj=this.obj,e.approximate=this.approximate,e}};fr.SearchResult=no;});var Ce=P(si=>{Object.defineProperty(si,"__esModule",{value:true});si.Container=void 0;var md=fe(),vc=we(),Cd=tn(),wn=je(),yd=yc(),Sc=We(),Ec=ei(),vd=xn(),Bt=ie(),ri=class i extends wn.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,n]of this.namedContent){let r=(0, Bt.asOrThrows)(n,wn.InkObject);e.set(t,r);}for(let t of this.content){let n=(0, Bt.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let r=(0, Bt.asINamedContentOrNull)(n);r!=null&&this.AddToNamedContentOnly(r);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=i.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=i.CountFlags.Turns),this.countingAtStartOnly&&(e|=i.CountFlags.CountStartOnly),e==i.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&i.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&i.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&i.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 i;)t.content.length>0&&(e.push(new Sc.Path.Component(0)),t=t.content[0]);return new Sc.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}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, Bt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){Ec.Debug.AssertType(e,wn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Bt.asOrThrows)(e,wn.InkObject);if(t.parent=this,e.name===null)return (0, vc.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let r=new yd.SearchResult;r.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let l=e.GetComponent(o);if(a==null){r.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){r.approximate=true;break}let c=(0, Bt.asOrNull)(u,i);if(o<n-1&&c==null){r.approximate=true;break}s=u,a=c;}return r.obj=s,r}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, vc.throwNullException)("component.name");let t=(0, vd.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Bt.asOrThrows)(t.result,wn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new Cd.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function r(){for(let o=0;o<4*t;++o)e.Append(" ");}r(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof i?o.BuildStringOfHierarchy(e,t,n):(r(),o instanceof md.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
- `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof i)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Bt.asOrThrows)(o,wn.InkObject))>=0||a.set(s,o);if(a.size>0){r(),e.AppendLine("-- named: --");for(let[,s]of a)Ec.Debug.AssertType(s,i,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,r(),e.Append("]");}};si.Container=ri;(function(i){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(i.CountFlags||(i.CountFlags={}));})(ri||(si.Container=ri={}));});var Oe=P(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.ControlCommand=void 0;var Sd=je(),ai=class i extends Sd.InkObject{get commandType(){return this._commandType}constructor(e=i.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new i(this.commandType)}static EvalStart(){return new i(i.CommandType.EvalStart)}static EvalOutput(){return new i(i.CommandType.EvalOutput)}static EvalEnd(){return new i(i.CommandType.EvalEnd)}static Duplicate(){return new i(i.CommandType.Duplicate)}static PopEvaluatedValue(){return new i(i.CommandType.PopEvaluatedValue)}static PopFunction(){return new i(i.CommandType.PopFunction)}static PopTunnel(){return new i(i.CommandType.PopTunnel)}static BeginString(){return new i(i.CommandType.BeginString)}static EndString(){return new i(i.CommandType.EndString)}static NoOp(){return new i(i.CommandType.NoOp)}static ChoiceCount(){return new i(i.CommandType.ChoiceCount)}static Turns(){return new i(i.CommandType.Turns)}static TurnsSince(){return new i(i.CommandType.TurnsSince)}static ReadCount(){return new i(i.CommandType.ReadCount)}static Random(){return new i(i.CommandType.Random)}static SeedRandom(){return new i(i.CommandType.SeedRandom)}static VisitIndex(){return new i(i.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new i(i.CommandType.SequenceShuffleIndex)}static StartThread(){return new i(i.CommandType.StartThread)}static Done(){return new i(i.CommandType.Done)}static End(){return new i(i.CommandType.End)}static ListFromInt(){return new i(i.CommandType.ListFromInt)}static ListRange(){return new i(i.CommandType.ListRange)}static ListRandom(){return new i(i.CommandType.ListRandom)}static BeginTag(){return new i(i.CommandType.BeginTag)}static EndTag(){return new i(i.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};oi.ControlCommand=ai;(function(i){(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";})(i.CommandType||(i.CommandType={}));})(ai||(oi.ControlCommand=ai={}));});var Ye=P(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.Expression=void 0;var bc=Ce(),io=Oe(),Ed=he(),ro=class extends Ed.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new bc.Container;return e.AddContent(io.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(io.ControlCommand.EvalOutput()),e.AddContent(io.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new bc.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};dr.Expression=ro;});var rn=P(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.Void=void 0;var bd=je(),so=class extends bd.InkObject{toString(){return "Void"}};gr.Void=so;});var mt=P(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.NativeFunctionCall=void 0;var k=fe(),li=ni(),Ad=rn(),mr=Me(),Dd=je(),Qe=ie(),$e=we(),J=class i extends Dd.InkObject{static CallWithName(e){return new i(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, $e.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(i._nativeFunctions===null?(0, $e.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=i._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 Ad.Void)throw new li.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 k.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),r=n[0].valueType;return r==k.ValueType.Int?this.CallType(n):r==k.ValueType.Float?this.CallType(n):r==k.ValueType.String?this.CallType(n):r==k.ValueType.DivertTarget?this.CallType(n):r==k.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Qe.asOrThrows)(e[0],k.Value),n=t.valueType,r=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=k.ValueType[n];throw new li.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Qe.asOrThrows)(e[1],k.Value),u=s;if(r.value===null||l.value===null)return (0, $e.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=u(r.value,l.value);return k.Value.Create(c)}else {let o=s;if(r.value===null)return (0, $e.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(r.value);return this.name===i.Int?k.Value.Create(l,k.ValueType.Int):this.name===i.Float?k.Value.Create(l,k.ValueType.Float):k.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof k.ListValue&&e[1]instanceof k.IntValue)return this.CallListIncrementOperation(e);let t=(0, Qe.asOrThrows)(e[0],k.Value),n=(0, Qe.asOrThrows)(e[1],k.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=k.ValueType.List||n.valueType!=k.ValueType.List)){if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(k.ValueType.Int);if(r===null)return (0, $e.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Qe.asBooleanOrThrows)(r(t.isTruthy?1:0,n.isTruthy?1:0));return new k.BoolValue(a)}if(t.valueType==k.ValueType.List&&n.valueType==k.ValueType.List)return this.CallType([t,n]);throw new li.StoryException("Can not call use "+this.name+" operation on "+k.ValueType[t.valueType]+" and "+k.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Qe.asOrThrows)(e[0],k.ListValue),n=(0, Qe.asOrThrows)(e[1],k.IntValue),r=new mr.InkList;if(t.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=mr.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(k.ValueType.Int);if(n.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),c=null;if(t.value.origins===null)return (0, $e.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(u,mr.InkListItem.Null);h.exists&&r.Add(h.result,u);}}return new k.ListValue(r)}CoerceValuesToSingleType(e){let t=k.ValueType.Int,n=null;for(let a of e){let s=(0, Qe.asOrThrows)(a,k.Value);s.valueType>t&&(t=s.valueType),s.valueType==k.ValueType.List&&(n=(0, Qe.asOrNull)(s,k.ListValue));}let r=[];if(k.ValueType[t]==k.ValueType[k.ValueType.List])for(let a of e){let s=(0, Qe.asOrThrows)(a,k.Value);if(s.valueType==k.ValueType.List)r.push(s);else if(s.valueType==k.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Qe.asOrThrows)(n,k.ListValue),n.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, $e.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,mr.InkListItem.Null);if(u.exists){let c=new k.ListValue(u.result,o);r.push(c);}else throw new li.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=k.ValueType[s.valueType];throw new li.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Qe.asOrThrows)(a,k.Value).Cast(t);r.push(o);}return r}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)i.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];i.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,(n,r)=>n+r),this.AddIntBinaryOp(this.Subtract,(n,r)=>n-r),this.AddIntBinaryOp(this.Multiply,(n,r)=>n*r),this.AddIntBinaryOp(this.Divide,(n,r)=>Math.floor(n/r)),this.AddIntBinaryOp(this.Mod,(n,r)=>n%r),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,r)=>n==r),this.AddIntBinaryOp(this.Greater,(n,r)=>n>r),this.AddIntBinaryOp(this.Less,(n,r)=>n<r),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddIntBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddIntBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddIntBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddIntBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddIntBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddIntBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddIntUnaryOp(this.Floor,i.Identity),this.AddIntUnaryOp(this.Ceiling,i.Identity),this.AddIntUnaryOp(this.Int,i.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,r)=>n+r),this.AddFloatBinaryOp(this.Subtract,(n,r)=>n-r),this.AddFloatBinaryOp(this.Multiply,(n,r)=>n*r),this.AddFloatBinaryOp(this.Divide,(n,r)=>n/r),this.AddFloatBinaryOp(this.Mod,(n,r)=>n%r),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,r)=>n==r),this.AddFloatBinaryOp(this.Greater,(n,r)=>n>r),this.AddFloatBinaryOp(this.Less,(n,r)=>n<r),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddFloatBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddFloatBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddFloatBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddFloatBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddFloatBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,i.Identity),this.AddStringBinaryOp(this.Add,(n,r)=>n+r),this.AddStringBinaryOp(this.Equal,(n,r)=>n===r),this.AddStringBinaryOp(this.NotEquals,(n,r)=>n!==r),this.AddStringBinaryOp(this.Has,(n,r)=>n.includes(r)),this.AddStringBinaryOp(this.Hasnt,(n,r)=>!n.includes(r)),this.AddListBinaryOp(this.Add,(n,r)=>n.Union(r)),this.AddListBinaryOp(this.Subtract,(n,r)=>n.Without(r)),this.AddListBinaryOp(this.Has,(n,r)=>n.Contains(r)),this.AddListBinaryOp(this.Hasnt,(n,r)=>!n.Contains(r)),this.AddListBinaryOp(this.Intersect,(n,r)=>n.Intersect(r)),this.AddListBinaryOp(this.Equal,(n,r)=>n.Equals(r)),this.AddListBinaryOp(this.Greater,(n,r)=>n.GreaterThan(r)),this.AddListBinaryOp(this.Less,(n,r)=>n.LessThan(r)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,r)=>n.GreaterThanOrEquals(r)),this.AddListBinaryOp(this.LessThanOrEquals,(n,r)=>n.LessThanOrEquals(r)),this.AddListBinaryOp(this.NotEquals,(n,r)=>!n.Equals(r)),this.AddListBinaryOp(this.And,(n,r)=>n.Count>0&&r.Count>0),this.AddListBinaryOp(this.Or,(n,r)=>n.Count>0||r.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,r)=>n.Equals(r),t=(n,r)=>!n.Equals(r);this.AddOpToNativeFunc(this.Equal,2,k.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,k.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,r){if(this._nativeFunctions===null)return (0, $e.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new i(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,r);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};Cr.NativeFunctionCall=J;J.Add="+";J.Subtract="-";J.Divide="/";J.Multiply="*";J.Mod="%";J.Negate="_";J.Equal="==";J.Greater=">";J.Less="<";J.GreaterThanOrEquals=">=";J.LessThanOrEquals="<=";J.NotEquals="!=";J.Not="!";J.And="&&";J.Or="||";J.Min="MIN";J.Max="MAX";J.Pow="POW";J.Floor="FLOOR";J.Ceiling="CEILING";J.Int="INT";J.Float="FLOAT";J.Has="?";J.Hasnt="!?";J.Intersect="^";J.ListMin="LIST_MIN";J.ListMax="LIST_MAX";J.All="LIST_ALL";J.Count="LIST_COUNT";J.ValueOfList="LIST_VALUE";J.Invert="LIST_INVERT";J._nativeFunctions=null;});var vr=P(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.NumberExpression=void 0;var xd=Ye(),ao=fe(),_d=ie(),oo=class i extends xd.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new ao.IntValue(this.value)):this.isFloat()?n.AddContent(new ao.FloatValue(this.value)):this.isBool()&&n.AddContent(new ao.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, _d.asOrNull)(e,i);return t?t.subtype==this.subtype&&t.value==this.value:false}};yr.NumberExpression=oo;});var lo=P(Sr=>{Object.defineProperty(Sr,"__esModule",{value:true});Sr.UnaryExpression=void 0;var wd=Ye(),Od=mt(),On=vr(),Td=ie(),ui=class extends wd.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Od.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Sr.UnaryExpression=ui;ui.WithInner=(i,e)=>{let t=(0, Td.asOrNull)(i,On.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new On.NumberExpression(-t.value,"int");if(t.isFloat())return new On.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new On.NumberExpression(t.value==0,"bool");if(t.isFloat())return new On.NumberExpression(t.value==0,"bool");if(t.isBool())return new On.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new ui(i,e)};});var co=P(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.BinaryExpression=void 0;var Pd=Ye(),Fd=mt(),Nd=lo(),Id=ie(),uo=class extends Pd.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=r=>{this.leftExpression.GenerateIntoContainer(r),this.rightExpression.GenerateIntoContainer(r),this.opName=this.NativeNameForOp(this.opName),r.AddContent(Fd.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=r=>r==="and"?"&&":r==="or"?"||":r==="mod"?"%":r==="has"?"?":r==="hasnt"?"!?":r,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Id.asOrNull)(this.leftExpression,Nd.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.`);}}};Er.BinaryExpression=uo;});var hi=P(br=>{Object.defineProperty(br,"__esModule",{value:true});br.CharacterSet=void 0;var ci=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let r=t.charCodeAt(0);r<=n.charCodeAt(0);++r)this.Add(String.fromCharCode(r));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};br.CharacterSet=ci;ci.FromRange=(i,e)=>new ci().AddRange(i,e);});var Dc=P(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.CharacterRange=void 0;var Ac=hi(),pi=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Ac.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let r=this.start.charCodeAt(0),a;r<=this.end.charCodeAt(0);r+=1)a=String.fromCharCode(r),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof Ac.CharacterSet)this._excludes=n.set;else for(let r of n)this._excludes.add(r);}get start(){return this._start}get end(){return this._end}};Ar.CharacterRange=pi;pi.Define=(i,e,t=[])=>new pi(i,e,t);});var xr=P(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.ChoicePoint=void 0;var Rd=je(),Vd=We(),ho=we(),po=class extends Rd.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, ho.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, ho.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Vd.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, ho.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};Dr.ChoicePoint=po;});var sn=P(_r=>{Object.defineProperty(_r,"__esModule",{value:true});_r.PushPopType=void 0;var xc;(function(i){i[i.Tunnel=0]="Tunnel",i[i.Function=1]="Function",i[i.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(xc||(_r.PushPopType=xc={}));});var fi=P(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.Pointer=void 0;var kd=We(),fo=class i{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 kd.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 i(this.container,this.index)}static StartOf(e){return new i(e,0)}static get Null(){return new i(null,-1)}};wr.Pointer=fo;});var Ct=P(Tr=>{Object.defineProperty(Tr,"__esModule",{value:true});Tr.Divert=void 0;var Ld=We(),Bd=sn(),Wd=tn(),jd=je(),go=fi(),_c=Ce(),Or=we(),mo=class i extends jd.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=go.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Or.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Or.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, Or.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof _c.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=go.Pointer.StartOf(e instanceof _c.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 Ld.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=go.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 i&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, Or.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 Wd.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Bd.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};Tr.Divert=mo;});var wt=P(Pr=>{Object.defineProperty(Pr,"__esModule",{value:true});Pr.SymbolType=void 0;var wc;(function(i){i[i.Knot=0]="Knot",i[i.List=1]="List",i[i.ListItem=2]="ListItem",i[i.Var=3]="Var",i[i.SubFlowAndWeave=4]="SubFlowAndWeave",i[i.Arg=5]="Arg",i[i.Temp=6]="Temp";})(wc||(Pr.SymbolType=wc={}));});var Wt=P(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.VariableAssignment=void 0;var qd=je(),Co=class extends qd.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Fr.VariableAssignment=Co;});var Tn=P(Ir=>{Object.defineProperty(Ir,"__esModule",{value:true});Ir.Choice=void 0;var Md=xr(),Nr=Ce(),jt=Oe(),yo=Ct(),Oc=fe(),$d=he(),Gd=wt(),Tc=Wt(),vo=class extends $d.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,n){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 Nr.Container,this._runtimeChoice=new Md.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(jt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Oc.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let r=new Tc.VariableAssignment("$r",true);this._outerContainer.AddContent(r),this._outerContainer.AddContent(jt.ControlCommand.BeginString()),this._divertToStartContentOuter=new yo.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new yo.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Nr.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(jt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(jt.ControlCommand.BeginString());let r=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(r),this._outerContainer.AddContent(jt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(jt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Nr.Container,this.startContent){this._returnToR2=new Oc.DivertTargetValue,this._innerContentContainer.AddContent(jt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(jt.ControlCommand.EvalEnd());let r=new Tc.VariableAssignment("$r",true);this._innerContentContainer.AddContent(r),this._divertToStartContentInner=new yo.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Nr.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let r=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(r);}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=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&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,Gd.SymbolType.SubFlowAndWeave);}};Ir.Choice=vo;});var Pc=P(Vr=>{Object.defineProperty(Vr,"__esModule",{value:true});Vr.StringParserElement=void 0;var Rr=class i{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{i._uniqueIdCounter++,this.uniqueId=i._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;};}};Vr.StringParserElement=Rr;Rr._uniqueIdCounter=1e3;});var Nc=P(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.StringParserState=void 0;var Fc=Pc(),So=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 n=0;n<200;++n)this._stack[n]=new Fc.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],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.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],n=this._stack[this._numElements-1];t.SquashFrom(n),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 Fc.StringParserElement;this._numElements=1;}};kr.StringParserState=So;});var bo=P(an=>{Object.defineProperty(an,"__esModule",{value:true});an.StringParser=an.ParseSuccess=void 0;var Eo=hi(),Hd=Nc();an.ParseSuccess=Symbol("ParseSuccessStruct");var di=class i{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,r=null)=>{let a=this.state.Peek(n),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(r,s,a),this.state.Squash();let o=r;return o===null&&(o=i.ParseSuccess),o},this.Expect=(n,r=null,a=null)=>{let s=this.ParseObject(n);if(s===null){r===null&&(r=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${r} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(n,r=false)=>{this.ErrorOnLine(n,this.lineIndex+1,r);},this.ErrorWithParsedObject=(n,r,a=false)=>{this.ErrorOnLine(n,r.debugMetadata?r.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,r,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,r-1,a);else throw new Error(`${s} on line ${r}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
1
+ 'use strict';var zod=require('zod'),pixiVn=require('@drincs/pixi-vn');require('@drincs/pixi-vn/canvas');var characters=require('@drincs/pixi-vn/characters'),narration=require('@drincs/pixi-vn/narration');require('@drincs/pixi-vn/sound');var storage=require('@drincs/pixi-vn/storage'),uS=require('ajv'),bt=require('fs/promises'),Q=require('path'),rv=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 uS__default=/*#__PURE__*/_interopDefault(uS);var bt__default=/*#__PURE__*/_interopDefault(bt);var Q__default=/*#__PURE__*/_interopDefault(Q);var rv__namespace=/*#__PURE__*/_interopNamespace(rv);var uf=Object.create;var Vu=Object.defineProperty;var cf=Object.getOwnPropertyDescriptor;var hf=Object.getOwnPropertyNames;var pf=Object.getPrototypeOf,ff=Object.prototype.hasOwnProperty;var Kt=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var T=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var df=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hf(e))!ff.call(i,r)&&r!==t&&Vu(i,r,{get:()=>e[r],enumerable:!(n=cf(e,r))||n.enumerable});return i};var mn=(i,e,t)=>(t=i!=null?uf(pf(i)):{},df(Vu(t,"default",{value:i,enumerable:true}),i));var Ua=T(Qi=>{Object.defineProperty(Qi,"__esModule",{value:true});Qi.CompilerOptions=void 0;var Ja=class{constructor(e=null,t=[],n=false,r=null,a=null){this.sourceFilename=e,this.pluginNames=t,this.countAllVisits=n,this.errorHandler=r,this.fileHandler=a;}};Qi.CompilerOptions=Ja;});var cc=T(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.DebugSourceRange=void 0;var za=class{constructor(e,t,n){this.length=e,this.debugMetadata=t,this.text=n;}};Zi.DebugSourceRange=za;});var en=T(er=>{Object.defineProperty(er,"__esModule",{value:true});er.ErrorType=void 0;var hc;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(hc||(er.ErrorType=hc={}));});var pc=T(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.Argument=void 0;var Ka=class{constructor(e=null,t=null,n=null){this.identifier=e,this.isByReference=t,this.isDivertTarget=n;}get typeName(){return "Argument"}};tr.Argument=Ka;});var ne=T(Ae=>{Object.defineProperty(Ae,"__esModule",{value:true});Ae.filterUndef=Ae.isEquatable=Ae.nullIfUndefined=Ae.asINamedContentOrNull=Ae.asBooleanOrThrows=Ae.asNumberOrThrows=Ae.asOrThrows=Ae.asOrNull=void 0;function ed(i,e){return i instanceof e?fc(i):null}Ae.asOrNull=ed;function td(i,e){if(i instanceof e)return fc(i);throw new Error(`${i} is not of type ${e}`)}Ae.asOrThrows=td;function nd(i){if(typeof i=="number")return i;throw new Error(`${i} is not a number`)}Ae.asNumberOrThrows=nd;function id(i){if(typeof i=="boolean")return i;throw new Error(`${i} is not a boolean`)}Ae.asBooleanOrThrows=id;function rd(i){return i.hasValidName&&i.name?i:null}Ae.asINamedContentOrNull=rd;function sd(i){return typeof i>"u"?null:i}Ae.nullIfUndefined=sd;function ad(i){return typeof i=="object"&&typeof i.Equals=="function"}Ae.isEquatable=ad;function fc(i,e){return i}function od(i){return i!=null}Ae.filterUndef=od;});var pe=T(nr=>{Object.defineProperty(nr,"__esModule",{value:true});nr.ParsedObject=void 0;var dc=ne(),Xa=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 n of t)n.hasOwnProperty("parent")&&(n.parent=this),this.content.push(n);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 n=(0, dc.asOrNull)(this,e);if(n!==null&&(t===null||t(n)===true))return n;if(this.content===null)return null;for(let r of this.content){let a=r.Find&&r.Find(e)(t);if(a)return a}return null},this.FindAll=e=>(t,n)=>{let r=Array.isArray(n)?n:[],a=(0, dc.asOrNull)(this,e);if(a!==null&&(!t||t(a)===true)&&r.push(a),this.content===null)return [];for(let s of this.content)s.FindAll&&s.FindAll(e)(t,r);return r},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,n=false){if(t===null&&(t=this),!(t._alreadyHadError&&!n||t._alreadyHadWarning&&n)){if(this.parent)this.parent.Error(e,t,n);else throw new Error(`No parent object to send error to: ${e}`);n?t._alreadyHadWarning=true:t._alreadyHadError=true;}}};nr.ParsedObject=Xa;});var rr=T(ir=>{Object.defineProperty(ir,"__esModule",{value:true});ir.AuthorWarning=void 0;var ld=pe(),Ya=class extends ld.ParsedObject{constructor(e){super(),this.warningMessage=e,this.GenerateRuntimeObject=()=>(this.Warning(this.warningMessage),null);}get typeName(){return "AuthorWarning"}};ir.AuthorWarning=Ya;});var We=T(Zn=>{Object.defineProperty(Zn,"__esModule",{value:true});Zn.Path=void 0;var Sn=class i{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 i.Component&&arguments[1]instanceof i){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 i(e)}else return i.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 i;return e._isRelative=true,e}GetComponent(e){return this._components[e]}PathByAppendingPath(e){let t=new i,n=0;for(let r=0;r<e._components.length&&e._components[r].isParent;++r)n++;for(let r=0;r<this._components.length-n;++r)t._components.push(this._components[r]);for(let r=n;r<e._components.length;++r)t._components.push(e._components[r]);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 n of t)/^(\-|\+)?([0-9]+|Infinity)$/.test(n)?this._components.push(new i.Component(parseInt(n))):this._components.push(new i.Component(n));}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,n=e._components.length;t<n;t++)if(!e._components[t].Equals(this._components[t]))return false;return true}PathByAppendingComponent(e){let t=new i;return t._components.push(...this._components),t._components.push(e),t}};Zn.Path=Sn;Sn.parentId="^";(function(i){class e{constructor(n){this.index=-1,this.name=null,typeof n=="string"?this.name=n:this.index=n;}get isIndex(){return this.index>=0}get isParent(){return this.name==i.parentId}static ToParent(){return new e(i.parentId)}toString(){return this.isIndex?this.index.toString():this.name}Equals(n){return n!=null&&n.isIndex==this.isIndex?this.isIndex?this.index==n.index:this.name==n.name:false}}i.Component=e;})(Sn||(Zn.Path=Sn={}));});var ei=T(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.Debug=void 0;var gc;(function(i){function e(n,r,a){t(n instanceof r,a);}i.AssertType=e;function t(n,r){if(!n)throw typeof r<"u"&&console.warn(r),console.trace&&console.trace(),new Error("")}i.Assert=t;})(gc||(sr.Debug=gc={}));});var Te=T(En=>{Object.defineProperty(En,"__esModule",{value:true});En.throwNullException=En.NullException=void 0;var ar=class extends Error{};En.NullException=ar;function ud(i){throw new ar(`${i} is null or undefined`)}En.throwNullException=ud;});var je=T(lr=>{Object.defineProperty(lr,"__esModule",{value:true});lr.InkObject=void 0;var bn=We(),ti=ye(),Qa=ei(),An=ne(),or=Te(),Za=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 n=t.ContentAtPath(e).obj;if(n){let r=n.debugMetadata;if(r!==null)return r.startLineNumber}}return null}get path(){if(this._path==null)if(this.parent==null)this._path=new bn.Path;else {let e=[],t=this,n=(0, An.asOrNull)(t.parent,ti.Container);for(;n!==null;){let r=(0, An.asINamedContentOrNull)(t);if(r!=null&&r.hasValidName){if(r.name===null)return (0, or.throwNullException)("namedChild.name");e.unshift(new bn.Path.Component(r.name));}else e.unshift(new bn.Path.Component(n.content.indexOf(t)));t=n,n=(0, An.asOrNull)(n.parent,ti.Container);}this._path=new bn.Path(e);}return this._path}ResolvePath(e){if(e===null)return (0, or.throwNullException)("path");if(e.isRelative){let t=(0, An.asOrNull)(this,ti.Container);return t===null&&(Qa.Debug.Assert(this.parent!==null,"Can't resolve relative path because we don't have a parent"),t=(0, An.asOrNull)(this.parent,ti.Container),Qa.Debug.Assert(t!==null,"Expected parent to be a container"),Qa.Debug.Assert(e.GetComponent(0).isParent),e=e.tail),t===null?(0, or.throwNullException)("nearestContainer"):t.ContentAtPath(e)}else {let t=this.rootContentContainer;return t===null?(0, or.throwNullException)("contentContainer"):t.ContentAtPath(e)}}ConvertPathToRelative(e){let t=this.path,n=Math.min(e.length,t.length),r=-1;for(let l=0;l<n;++l){let u=t.GetComponent(l),c=e.GetComponent(l);if(u.Equals(c))r=l;else break}if(r==-1)return e;let a=t.componentCount-1-r,s=[];for(let l=0;l<a;++l)s.push(bn.Path.Component.ToParent());for(let l=r+1;l<e.componentCount;++l)s.push(e.GetComponent(l));return new bn.Path(s,true)}CompactPathString(e){let t=null,n=null;return e.isRelative?(n=e.componentsString,t=this.path.PathByAppendingPath(e).componentsString):(n=this.ConvertPathToRelative(e).componentsString,t=e.componentsString),n.length<t.length?n:t}get rootContentContainer(){let e=this;for(;e.parent;)e=e.parent;return (0, An.asOrNull)(e,ti.Container)}Copy(){throw Error("Not Implemented: Doesn't support copying")}SetChild(e,t,n){e[t]&&(e[t]=null),e[t]=n,e[t]&&(e[t].parent=this);}Equals(e){return e===this}};lr.InkObject=Za;});var tn=T(ur=>{Object.defineProperty(ur,"__esModule",{value:true});ur.StringBuilder=void 0;var eo=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+=`
2
+ `;}AppendFormat(e,...t){this.string+=e.replace(/{(\d+)}/g,(n,r)=>typeof t[r]<"u"?t[r]:n);}toString(){return this.string}Clear(){this.string="";}};ur.StringBuilder=eo;});var Me=T(Dn=>{Object.defineProperty(Dn,"__esModule",{value:true});Dn.InkList=Dn.InkListItem=void 0;var pt=Te(),cd=tn(),qe=class i{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 i(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 i){let t=e;return t.itemName==this.itemName&&t.originName==this.originName}return false}copy(){return new i(this.originName,this.itemName)}serialized(){return JSON.stringify({originName:this.originName,itemName:this.itemName})}static fromSerializedKey(e){let t=JSON.parse(e);if(!i.isLikeInkListItem(t))return i.Null;let n=t;return new i(n.originName,n.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)}};Dn.InkListItem=qe;var to=class i extends Map{constructor(){if(super(arguments[0]instanceof i?arguments[0]:[]),this.origins=null,this._originNames=[],arguments[0]instanceof i){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, pt.throwNullException)("originStory.listDefinitions");let n=t.listDefinitions.TryListGetDefinition(e,null);if(n.exists){if(n.result===null)return (0, pt.throwNullException)("def.result");this.origins=[n.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 n;if(e==null||e=="")return new i;let r=(n=t.listDefinitions)===null||n===void 0?void 0:n.FindSingleItemListWithName(e);if(r)return r.value===null?(0, pt.throwNullException)("listValue.value"):new i(r.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 qe){let n=e;if(n.originName==null){this.AddItem(n.itemName);return}if(this.origins===null)return (0, pt.throwNullException)("this.origins");for(let r of this.origins)if(r.name==n.originName){let a=r.TryGetValueForItem(n,0);if(a.exists){this.Add(n,a.result);return}else throw new Error("Could not add the item "+n+" 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 n=e,r=null;if(this.origins===null)return (0, pt.throwNullException)("this.origins");for(let a of this.origins){if(n===null)return (0, pt.throwNullException)("itemName");if(a.ContainsItemWithName(n)){if(r!=null)throw new Error("Could not add the item "+n+" to this list because it could come from either "+a.name+" or "+r.name);r=a;}}if(r==null){if(t==null)throw new Error("Could not add the item "+n+" to this list because it isn't known to any list definitions previously associated with this list.");{let a=i.FromString(n,t).orderedItems[0];this.Add(a.Key,a.Value);}}else {let a=new qe(r.name,n),s=r.ValueForItem(a);this.Add(a,s);}}}ContainsItemNamed(e){for(let[t]of this)if(qe.fromSerializedKey(t).itemName==e)return true;return false}ContainsKey(e){return this.has(e.serialized())}Add(e,t){let n=e.serialized();if(this.has(n))throw new Error(`The Map already contains an entry for ${e}`);this.set(n,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(n=>n.name==e?(t=n,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=qe.fromSerializedKey(e);if(t.originName===null)return (0, pt.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:qe.Null,Value:0};for(let[t,n]of this){let r=qe.fromSerializedKey(t);(e.Key.isNull||n>e.Value)&&(e={Key:r,Value:n});}return e}get minItem(){let e={Key:qe.Null,Value:0};for(let[t,n]of this){let r=qe.fromSerializedKey(t);(e.Key.isNull||n<e.Value)&&(e={Key:r,Value:n});}return e}get inverse(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=qe.fromSerializedKey(n);this.ContainsKey(a)||e.Add(a,r);}return e}get all(){let e=new i;if(this.origins!=null)for(let t of this.origins)for(let[n,r]of t.items){let a=qe.fromSerializedKey(n);e.set(a.serialized(),r);}return e}Union(e){let t=new i(this);for(let[n,r]of e)t.set(n,r);return t}Intersect(e){let t=new i;for(let[n,r]of this)e.has(n)&&t.set(n,r);return t}HasIntersection(e){for(let[t]of this)if(e.has(t))return true;return false}Without(e){let t=new i(this);for(let[n]of e)t.delete(n);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[n]of t)if(!this.has(n))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 i(this.maxItem):new i}MinAsList(){return this.Count>0?new i(this.minItem):new i}ListWithSubRange(e,t){if(this.Count==0)return new i;let n=this.orderedItems,r=0,a=Number.MAX_SAFE_INTEGER;Number.isInteger(e)?r=e:e instanceof i&&e.Count>0&&(r=e.minItem.Value),Number.isInteger(t)?a=t:t instanceof i&&t.Count>0&&(a=t.maxItem.Value);let s=new i;s.SetInitialOriginNames(this.originNames);for(let o of n)o.Value>=r&&o.Value<=a&&s.Add(o.Key,o.Value);return s}Equals(e){if(!(e instanceof i)||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,n]of this){let r=qe.fromSerializedKey(t);e.push({Key:r,Value:n});}return e.sort((t,n)=>t.Key.originName===null?(0, pt.throwNullException)("x.Key.originName"):n.Key.originName===null?(0, pt.throwNullException)("y.Key.originName"):t.Value==n.Value?t.Key.originName.localeCompare(n.Key.originName):t.Value<n.Value?-1:t.Value>n.Value?1:0),e}get singleItem(){for(let e of this.orderedItems)return e.Key;return null}toString(){let e=this.orderedItems,t=new cd.StringBuilder;for(let n=0;n<e.length;n++){n>0&&t.Append(", ");let r=e[n].Key;if(r.itemName===null)return (0, pt.throwNullException)("item.itemName");t.Append(r.itemName);}return t.toString()}valueOf(){return NaN}};Dn.InkList=to;});var ni=T(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.StoryException=void 0;var no=class extends Error{constructor(e){super(e),this.useEndLineNumber=false,this.message=e,this.name="StoryException";}};cr.StoryException=no;});var xn=T(Lt=>{Object.defineProperty(Lt,"__esModule",{value:true});Lt.tryParseFloat=Lt.tryParseInt=Lt.tryGetValueFromMap=void 0;function hd(i,e,t){if(i===null)return {result:t,exists:false};let n=i.get(e);return typeof n>"u"?{result:t,exists:false}:{result:n,exists:true}}Lt.tryGetValueFromMap=hd;function pd(i,e=0){let t=parseInt(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Lt.tryParseInt=pd;function fd(i,e=0){let t=parseFloat(i);return Number.isNaN(t)?{result:e,exists:false}:{result:t,exists:true}}Lt.tryParseFloat=fd;});var de=T(ge=>{Object.defineProperty(ge,"__esModule",{value:true});ge.ValueType=ge.ListValue=ge.VariablePointerValue=ge.DivertTargetValue=ge.StringValue=ge.FloatValue=ge.IntValue=ge.BoolValue=ge.Value=ge.AbstractValue=void 0;var mc=je(),Cc=We(),nn=Me(),dd=ni(),ii=ne(),yc=xn(),Xe=Te(),hr=class i extends mc.InkObject{static Create(e,t){if(t){if(t===ce.Int&&Number.isInteger(Number(e)))return new dt(Number(e));if(t===ce.Float&&!isNaN(e))return new gt(Number(e))}if(typeof e=="boolean")return new _n(!!e);if(typeof e=="string")return new wt(String(e));if(Number.isInteger(Number(e)))return new dt(Number(e));if(isNaN(e)){if(e instanceof Cc.Path)return new pr((0, ii.asOrThrows)(e,Cc.Path));if(e instanceof nn.InkList)return new fr((0, ii.asOrThrows)(e,nn.InkList))}else return new gt(Number(e));return null}Copy(){return (0, ii.asOrThrows)(i.Create(this.valueObject),mc.InkObject)}BadCastException(e){return new dd.StoryException("Can't cast "+this.valueObject+" from "+this.valueType+" to "+e)}};ge.AbstractValue=hr;var ft=class extends hr{constructor(e){super(),this.value=e;}get valueObject(){return this.value}toString(){return this.value===null?(0, Xe.throwNullException)("Value.value"):this.value.toString()}};ge.Value=ft;var _n=class extends ft{constructor(e){super(e||false);}get isTruthy(){return !!this.value}get valueType(){return ce.Bool}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Int)return new dt(this.value?1:0);if(e==ce.Float)return new gt(this.value?1:0);if(e==ce.String)return new wt(this.value?"true":"false");throw this.BadCastException(e)}toString(){return this.value?"true":"false"}};ge.BoolValue=_n;var dt=class extends ft{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ce.Int}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Bool)return new _n(this.value!==0);if(e==ce.Float)return new gt(this.value);if(e==ce.String)return new wt(""+this.value);throw this.BadCastException(e)}};ge.IntValue=dt;var gt=class extends ft{constructor(e){super(e||0);}get isTruthy(){return this.value!=0}get valueType(){return ce.Float}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==this.valueType)return this;if(e==ce.Bool)return new _n(this.value!==0);if(e==ce.Int)return new dt(this.value);if(e==ce.String)return new wt(""+this.value);throw this.BadCastException(e)}};ge.FloatValue=gt;var wt=class extends ft{constructor(e){if(super(e||""),this._isNewline=this.value==`
3
+ `,this._isInlineWhitespace=true,this.value===null)return (0, Xe.throwNullException)("Value.value");this.value.length>0&&this.value.split("").every(t=>t!=" "&&t!=" "?(this._isInlineWhitespace=false,false):true);}get valueType(){return ce.String}get isTruthy(){return this.value===null?(0, Xe.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==ce.Int){let t=(0, yc.tryParseInt)(this.value);if(t.exists)return new dt(t.result);throw this.BadCastException(e)}if(e==ce.Float){let t=(0, yc.tryParseFloat)(this.value);if(t.exists)return new gt(t.result);throw this.BadCastException(e)}throw this.BadCastException(e)}};ge.StringValue=wt;var pr=class extends ft{constructor(e=null){super(e);}get valueType(){return ce.DivertTarget}get targetPath(){return this.value===null?(0, Xe.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+")"}};ge.DivertTargetValue=pr;var io=class i extends ft{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, Xe.throwNullException)("Value.value"):this.value}set variableName(e){this.value=e;}get valueType(){return ce.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 i(this.variableName,this.contextIndex)}};ge.VariablePointerValue=io;var fr=class i extends ft{get isTruthy(){return this.value===null?(0, Xe.throwNullException)("this.value"):this.value.Count>0}get valueType(){return ce.List}Cast(e){if(this.value===null)return (0, Xe.throwNullException)("Value.value");if(e==ce.Int){let t=this.value.maxItem;return t.Key.isNull?new dt(0):new dt(t.Value)}else if(e==ce.Float){let t=this.value.maxItem;return t.Key.isNull?new gt(0):new gt(t.Value)}else if(e==ce.String){let t=this.value.maxItem;return t.Key.isNull?new wt(""):new wt(t.Key.toString())}if(e==this.valueType)return this;throw this.BadCastException(e)}constructor(e,t){super(null),!e&&!t?this.value=new nn.InkList:e instanceof nn.InkList?this.value=new nn.InkList(e):e instanceof nn.InkListItem&&typeof t=="number"&&(this.value=new nn.InkList({Key:e,Value:t}));}static RetainListOriginsForAssignment(e,t){let n=(0, ii.asOrNull)(e,i),r=(0, ii.asOrNull)(t,i);if(r&&r.value===null)return (0, Xe.throwNullException)("newList.value");if(n&&n.value===null)return (0, Xe.throwNullException)("oldList.value");n&&r&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}};ge.ListValue=fr;var ce;(function(i){i[i.Bool=-1]="Bool",i[i.Int=0]="Int",i[i.Float=1]="Float",i[i.List=2]="List",i[i.String=3]="String",i[i.DivertTarget=4]="DivertTarget",i[i.VariablePointer=5]="VariablePointer";})(ce||(ge.ValueType=ce={}));});var vc=T(dr=>{Object.defineProperty(dr,"__esModule",{value:true});dr.SearchResult=void 0;var gd=ye(),ro=class i{constructor(){this.obj=null,this.approximate=false;}get correctObj(){return this.approximate?null:this.obj}get container(){return this.obj instanceof gd.Container?this.obj:null}copy(){let e=new i;return e.obj=this.obj,e.approximate=this.approximate,e}};dr.SearchResult=ro;});var ye=T(si=>{Object.defineProperty(si,"__esModule",{value:true});si.Container=void 0;var md=de(),Sc=Te(),Cd=tn(),wn=je(),yd=vc(),Ec=We(),bc=ei(),vd=xn(),Bt=ne(),ri=class i extends wn.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,n]of this.namedContent){let r=(0, Bt.asOrThrows)(n,wn.InkObject);e.set(t,r);}for(let t of this.content){let n=(0, Bt.asINamedContentOrNull)(t);n!=null&&n.hasValidName&&e.delete(n.name);}return e.size==0&&(e=null),e}set namedOnlyContent(e){let t=this.namedOnlyContent;if(t!=null)for(let[n]of t)this.namedContent.delete(n);if(e!=null)for(let[,n]of e){let r=(0, Bt.asINamedContentOrNull)(n);r!=null&&this.AddToNamedContentOnly(r);}}get countFlags(){let e=0;return this.visitsShouldBeCounted&&(e|=i.CountFlags.Visits),this.turnIndexShouldBeCounted&&(e|=i.CountFlags.Turns),this.countingAtStartOnly&&(e|=i.CountFlags.CountStartOnly),e==i.CountFlags.CountStartOnly&&(e=0),e}set countFlags(e){let t=e;(t&i.CountFlags.Visits)>0&&(this.visitsShouldBeCounted=true),(t&i.CountFlags.Turns)>0&&(this.turnIndexShouldBeCounted=true),(t&i.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 i;)t.content.length>0&&(e.push(new Ec.Path.Component(0)),t=t.content[0]);return new Ec.Path(e)}AddContent(e){if(e instanceof Array){let t=e;for(let n of t)this.AddContent(n);}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, Bt.asINamedContentOrNull)(e);t!=null&&t.hasValidName&&this.AddToNamedContentOnly(t);}AddToNamedContentOnly(e){bc.Debug.AssertType(e,wn.InkObject,"Can only add Runtime.Objects to a Runtime.Container");let t=(0, Bt.asOrThrows)(e,wn.InkObject);if(t.parent=this,e.name===null)return (0, Sc.throwNullException)("namedContentObj.name");this.namedContent.set(e.name,e);}ContentAtPath(e,t=0,n=-1){n==-1&&(n=e.length);let r=new yd.SearchResult;r.approximate=false;let a=this,s=this;for(let o=t;o<n;++o){let l=e.GetComponent(o);if(a==null){r.approximate=true;break}let u=a.ContentWithPathComponent(l);if(u==null){r.approximate=true;break}let c=(0, Bt.asOrNull)(u,i);if(o<n-1&&c==null){r.approximate=true;break}s=u,a=c;}return r.obj=s,r}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, Sc.throwNullException)("component.name");let t=(0, vd.tryGetValueFromMap)(this.namedContent,e.name,null);return t.exists?(0, Bt.asOrThrows)(t.result,wn.InkObject):null}}BuildStringOfHierarchy(){let e;if(arguments.length==0)return e=new Cd.StringBuilder,this.BuildStringOfHierarchy(e,0,null),e.toString();e=arguments[0];let t=arguments[1],n=arguments[2];function r(){for(let o=0;o<4*t;++o)e.Append(" ");}r(),e.Append("["),this.hasValidName&&e.AppendFormat(" ({0})",this.name),this==n&&e.Append(" <---"),e.AppendLine(),t++;for(let s=0;s<this.content.length;++s){let o=this.content[s];o instanceof i?o.BuildStringOfHierarchy(e,t,n):(r(),o instanceof md.StringValue?(e.Append('"'),e.Append(o.toString().replace(`
4
+ `,"\\n")),e.Append('"')):e.Append(o.toString())),s!=this.content.length-1&&e.Append(","),!(o instanceof i)&&o==n&&e.Append(" <---"),e.AppendLine();}let a=new Map;for(let[s,o]of this.namedContent)this.content.indexOf((0, Bt.asOrThrows)(o,wn.InkObject))>=0||a.set(s,o);if(a.size>0){r(),e.AppendLine("-- named: --");for(let[,s]of a)bc.Debug.AssertType(s,i,"Can only print out named Containers"),s.BuildStringOfHierarchy(e,t,n),e.AppendLine();}t--,r(),e.Append("]");}};si.Container=ri;(function(i){(function(t){t[t.Start=0]="Start",t[t.Visits=1]="Visits",t[t.Turns=2]="Turns",t[t.CountStartOnly=4]="CountStartOnly";})(i.CountFlags||(i.CountFlags={}));})(ri||(si.Container=ri={}));});var Pe=T(oi=>{Object.defineProperty(oi,"__esModule",{value:true});oi.ControlCommand=void 0;var Sd=je(),ai=class i extends Sd.InkObject{get commandType(){return this._commandType}constructor(e=i.CommandType.NotSet){super(),this._commandType=e;}Copy(){return new i(this.commandType)}static EvalStart(){return new i(i.CommandType.EvalStart)}static EvalOutput(){return new i(i.CommandType.EvalOutput)}static EvalEnd(){return new i(i.CommandType.EvalEnd)}static Duplicate(){return new i(i.CommandType.Duplicate)}static PopEvaluatedValue(){return new i(i.CommandType.PopEvaluatedValue)}static PopFunction(){return new i(i.CommandType.PopFunction)}static PopTunnel(){return new i(i.CommandType.PopTunnel)}static BeginString(){return new i(i.CommandType.BeginString)}static EndString(){return new i(i.CommandType.EndString)}static NoOp(){return new i(i.CommandType.NoOp)}static ChoiceCount(){return new i(i.CommandType.ChoiceCount)}static Turns(){return new i(i.CommandType.Turns)}static TurnsSince(){return new i(i.CommandType.TurnsSince)}static ReadCount(){return new i(i.CommandType.ReadCount)}static Random(){return new i(i.CommandType.Random)}static SeedRandom(){return new i(i.CommandType.SeedRandom)}static VisitIndex(){return new i(i.CommandType.VisitIndex)}static SequenceShuffleIndex(){return new i(i.CommandType.SequenceShuffleIndex)}static StartThread(){return new i(i.CommandType.StartThread)}static Done(){return new i(i.CommandType.Done)}static End(){return new i(i.CommandType.End)}static ListFromInt(){return new i(i.CommandType.ListFromInt)}static ListRange(){return new i(i.CommandType.ListRange)}static ListRandom(){return new i(i.CommandType.ListRandom)}static BeginTag(){return new i(i.CommandType.BeginTag)}static EndTag(){return new i(i.CommandType.EndTag)}toString(){return "ControlCommand "+this.commandType.toString()}};oi.ControlCommand=ai;(function(i){(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";})(i.CommandType||(i.CommandType={}));})(ai||(oi.ControlCommand=ai={}));});var Ye=T(gr=>{Object.defineProperty(gr,"__esModule",{value:true});gr.Expression=void 0;var Ac=ye(),so=Pe(),Ed=pe(),ao=class extends Ed.ParsedObject{constructor(){super(...arguments),this._prototypeRuntimeConstantExpression=null,this.outputWhenComplete=false,this.GenerateRuntimeObject=()=>{let e=new Ac.Container;return e.AddContent(so.ControlCommand.EvalStart()),this.GenerateIntoContainer(e),this.outputWhenComplete&&e.AddContent(so.ControlCommand.EvalOutput()),e.AddContent(so.ControlCommand.EvalEnd()),e},this.GenerateConstantIntoContainer=e=>{this._prototypeRuntimeConstantExpression===null&&(this._prototypeRuntimeConstantExpression=new Ac.Container,this.GenerateIntoContainer(this._prototypeRuntimeConstantExpression));for(let t of this._prototypeRuntimeConstantExpression.content){let n=t.Copy();n&&e.AddContent(n);}},this.toString=()=>"No string value in JavaScript.";}get typeName(){return "Expression"}Equals(e){return false}};gr.Expression=ao;});var rn=T(mr=>{Object.defineProperty(mr,"__esModule",{value:true});mr.Void=void 0;var bd=je(),oo=class extends bd.InkObject{toString(){return "Void"}};mr.Void=oo;});var mt=T(yr=>{Object.defineProperty(yr,"__esModule",{value:true});yr.NativeFunctionCall=void 0;var k=de(),li=ni(),Ad=rn(),Cr=Me(),Dd=je(),Qe=ne(),$e=Te(),z=class i extends Dd.InkObject{static CallWithName(e){return new i(e)}static CallExistsWithName(e){return this.GenerateNativeFunctionsIfNecessary(),this._nativeFunctions.get(e)}get name(){return this._name===null?(0, $e.throwNullException)("NativeFunctionCall._name"):this._name}set name(e){this._name=e,this._isPrototype||(i._nativeFunctions===null?(0, $e.throwNullException)("NativeFunctionCall._nativeFunctions"):this._prototype=i._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 Ad.Void)throw new li.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 k.ListValue&&(t=true);}if(e.length==2&&t)return this.CallBinaryListOperation(e);let n=this.CoerceValuesToSingleType(e),r=n[0].valueType;return r==k.ValueType.Int?this.CallType(n):r==k.ValueType.Float?this.CallType(n):r==k.ValueType.String?this.CallType(n):r==k.ValueType.DivertTarget?this.CallType(n):r==k.ValueType.List?this.CallType(n):null}CallType(e){let t=(0, Qe.asOrThrows)(e[0],k.Value),n=t.valueType,r=t,a=e.length;if(a==2||a==1){if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let s=this._operationFuncs.get(n);if(!s){let o=k.ValueType[n];throw new li.StoryException("Cannot perform operation "+this.name+" on "+o)}if(a==2){let l=(0, Qe.asOrThrows)(e[1],k.Value),u=s;if(r.value===null||l.value===null)return (0, $e.throwNullException)("NativeFunctionCall.Call BinaryOp values");let c=u(r.value,l.value);return k.Value.Create(c)}else {let o=s;if(r.value===null)return (0, $e.throwNullException)("NativeFunctionCall.Call UnaryOp value");let l=o(r.value);return this.name===i.Int?k.Value.Create(l,k.ValueType.Int):this.name===i.Float?k.Value.Create(l,k.ValueType.Float):k.Value.Create(l,t.valueType)}}else throw new Error("Unexpected number of parameters to NativeFunctionCall: "+e.length)}CallBinaryListOperation(e){if((this.name=="+"||this.name=="-")&&e[0]instanceof k.ListValue&&e[1]instanceof k.IntValue)return this.CallListIncrementOperation(e);let t=(0, Qe.asOrThrows)(e[0],k.Value),n=(0, Qe.asOrThrows)(e[1],k.Value);if((this.name=="&&"||this.name=="||")&&(t.valueType!=k.ValueType.List||n.valueType!=k.ValueType.List)){if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let r=this._operationFuncs.get(k.ValueType.Int);if(r===null)return (0, $e.throwNullException)("NativeFunctionCall.CallBinaryListOperation op");let a=(0, Qe.asBooleanOrThrows)(r(t.isTruthy?1:0,n.isTruthy?1:0));return new k.BoolValue(a)}if(t.valueType==k.ValueType.List&&n.valueType==k.ValueType.List)return this.CallType([t,n]);throw new li.StoryException("Can not call use "+this.name+" operation on "+k.ValueType[t.valueType]+" and "+k.ValueType[n.valueType])}CallListIncrementOperation(e){let t=(0, Qe.asOrThrows)(e[0],k.ListValue),n=(0, Qe.asOrThrows)(e[1],k.IntValue),r=new Cr.InkList;if(t.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CallListIncrementOperation listVal.value");for(let[a,s]of t.value){let o=Cr.InkListItem.fromSerializedKey(a);if(this._operationFuncs===null)return (0, $e.throwNullException)("NativeFunctionCall._operationFuncs");let l=this._operationFuncs.get(k.ValueType.Int);if(n.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CallListIncrementOperation intVal.value");let u=l(s,n.value),c=null;if(t.value.origins===null)return (0, $e.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(u,Cr.InkListItem.Null);h.exists&&r.Add(h.result,u);}}return new k.ListValue(r)}CoerceValuesToSingleType(e){let t=k.ValueType.Int,n=null;for(let a of e){let s=(0, Qe.asOrThrows)(a,k.Value);s.valueType>t&&(t=s.valueType),s.valueType==k.ValueType.List&&(n=(0, Qe.asOrNull)(s,k.ListValue));}let r=[];if(k.ValueType[t]==k.ValueType[k.ValueType.List])for(let a of e){let s=(0, Qe.asOrThrows)(a,k.Value);if(s.valueType==k.ValueType.List)r.push(s);else if(s.valueType==k.ValueType.Int){let o=parseInt(s.valueObject);if(n=(0, Qe.asOrThrows)(n,k.ListValue),n.value===null)return (0, $e.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType specialCaseList.value");let l=n.value.originOfMaxItem;if(l===null)return (0, $e.throwNullException)("NativeFunctionCall.CoerceValuesToSingleType list");let u=l.TryGetItemWithValue(o,Cr.InkListItem.Null);if(u.exists){let c=new k.ListValue(u.result,o);r.push(c);}else throw new li.StoryException("Could not find List item with the value "+o+" in "+l.name)}else {let o=k.ValueType[s.valueType];throw new li.StoryException("Cannot mix Lists and "+o+" values in this operation")}}else for(let a of e){let o=(0, Qe.asOrThrows)(a,k.Value).Cast(t);r.push(o);}return r}constructor(){if(super(),this._name=null,this._numberOfParameters=0,this._prototype=null,this._isPrototype=false,this._operationFuncs=null,arguments.length===0)i.GenerateNativeFunctionsIfNecessary();else if(arguments.length===1){let e=arguments[0];i.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,(n,r)=>n+r),this.AddIntBinaryOp(this.Subtract,(n,r)=>n-r),this.AddIntBinaryOp(this.Multiply,(n,r)=>n*r),this.AddIntBinaryOp(this.Divide,(n,r)=>Math.floor(n/r)),this.AddIntBinaryOp(this.Mod,(n,r)=>n%r),this.AddIntUnaryOp(this.Negate,n=>-n),this.AddIntBinaryOp(this.Equal,(n,r)=>n==r),this.AddIntBinaryOp(this.Greater,(n,r)=>n>r),this.AddIntBinaryOp(this.Less,(n,r)=>n<r),this.AddIntBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddIntBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddIntBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddIntUnaryOp(this.Not,n=>n==0),this.AddIntBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddIntBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddIntBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddIntBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddIntBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddIntUnaryOp(this.Floor,i.Identity),this.AddIntUnaryOp(this.Ceiling,i.Identity),this.AddIntUnaryOp(this.Int,i.Identity),this.AddIntUnaryOp(this.Float,n=>n),this.AddFloatBinaryOp(this.Add,(n,r)=>n+r),this.AddFloatBinaryOp(this.Subtract,(n,r)=>n-r),this.AddFloatBinaryOp(this.Multiply,(n,r)=>n*r),this.AddFloatBinaryOp(this.Divide,(n,r)=>n/r),this.AddFloatBinaryOp(this.Mod,(n,r)=>n%r),this.AddFloatUnaryOp(this.Negate,n=>-n),this.AddFloatBinaryOp(this.Equal,(n,r)=>n==r),this.AddFloatBinaryOp(this.Greater,(n,r)=>n>r),this.AddFloatBinaryOp(this.Less,(n,r)=>n<r),this.AddFloatBinaryOp(this.GreaterThanOrEquals,(n,r)=>n>=r),this.AddFloatBinaryOp(this.LessThanOrEquals,(n,r)=>n<=r),this.AddFloatBinaryOp(this.NotEquals,(n,r)=>n!=r),this.AddFloatUnaryOp(this.Not,n=>n==0),this.AddFloatBinaryOp(this.And,(n,r)=>n!=0&&r!=0),this.AddFloatBinaryOp(this.Or,(n,r)=>n!=0||r!=0),this.AddFloatBinaryOp(this.Max,(n,r)=>Math.max(n,r)),this.AddFloatBinaryOp(this.Min,(n,r)=>Math.min(n,r)),this.AddFloatBinaryOp(this.Pow,(n,r)=>Math.pow(n,r)),this.AddFloatUnaryOp(this.Floor,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Ceiling,n=>Math.ceil(n)),this.AddFloatUnaryOp(this.Int,n=>Math.floor(n)),this.AddFloatUnaryOp(this.Float,i.Identity),this.AddStringBinaryOp(this.Add,(n,r)=>n+r),this.AddStringBinaryOp(this.Equal,(n,r)=>n===r),this.AddStringBinaryOp(this.NotEquals,(n,r)=>n!==r),this.AddStringBinaryOp(this.Has,(n,r)=>n.includes(r)),this.AddStringBinaryOp(this.Hasnt,(n,r)=>!n.includes(r)),this.AddListBinaryOp(this.Add,(n,r)=>n.Union(r)),this.AddListBinaryOp(this.Subtract,(n,r)=>n.Without(r)),this.AddListBinaryOp(this.Has,(n,r)=>n.Contains(r)),this.AddListBinaryOp(this.Hasnt,(n,r)=>!n.Contains(r)),this.AddListBinaryOp(this.Intersect,(n,r)=>n.Intersect(r)),this.AddListBinaryOp(this.Equal,(n,r)=>n.Equals(r)),this.AddListBinaryOp(this.Greater,(n,r)=>n.GreaterThan(r)),this.AddListBinaryOp(this.Less,(n,r)=>n.LessThan(r)),this.AddListBinaryOp(this.GreaterThanOrEquals,(n,r)=>n.GreaterThanOrEquals(r)),this.AddListBinaryOp(this.LessThanOrEquals,(n,r)=>n.LessThanOrEquals(r)),this.AddListBinaryOp(this.NotEquals,(n,r)=>!n.Equals(r)),this.AddListBinaryOp(this.And,(n,r)=>n.Count>0&&r.Count>0),this.AddListBinaryOp(this.Or,(n,r)=>n.Count>0||r.Count>0),this.AddListUnaryOp(this.Not,n=>n.Count==0?1:0),this.AddListUnaryOp(this.Invert,n=>n.inverse),this.AddListUnaryOp(this.All,n=>n.all),this.AddListUnaryOp(this.ListMin,n=>n.MinAsList()),this.AddListUnaryOp(this.ListMax,n=>n.MaxAsList()),this.AddListUnaryOp(this.Count,n=>n.Count),this.AddListUnaryOp(this.ValueOfList,n=>n.maxItem.Value);let e=(n,r)=>n.Equals(r),t=(n,r)=>!n.Equals(r);this.AddOpToNativeFunc(this.Equal,2,k.ValueType.DivertTarget,e),this.AddOpToNativeFunc(this.NotEquals,2,k.ValueType.DivertTarget,t);}}AddOpFuncForType(e,t){this._operationFuncs==null&&(this._operationFuncs=new Map),this._operationFuncs.set(e,t);}static AddOpToNativeFunc(e,t,n,r){if(this._nativeFunctions===null)return (0, $e.throwNullException)("NativeFunctionCall._nativeFunctions");let a=this._nativeFunctions.get(e);a||(a=new i(e,t),this._nativeFunctions.set(e,a)),a.AddOpFuncForType(n,r);}static AddIntBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.Int,t);}static AddIntUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.Int,t);}static AddFloatBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.Float,t);}static AddFloatUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.Float,t);}static AddStringBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.String,t);}static AddListBinaryOp(e,t){this.AddOpToNativeFunc(e,2,k.ValueType.List,t);}static AddListUnaryOp(e,t){this.AddOpToNativeFunc(e,1,k.ValueType.List,t);}toString(){return 'Native "'+this.name+'"'}};yr.NativeFunctionCall=z;z.Add="+";z.Subtract="-";z.Divide="/";z.Multiply="*";z.Mod="%";z.Negate="_";z.Equal="==";z.Greater=">";z.Less="<";z.GreaterThanOrEquals=">=";z.LessThanOrEquals="<=";z.NotEquals="!=";z.Not="!";z.And="&&";z.Or="||";z.Min="MIN";z.Max="MAX";z.Pow="POW";z.Floor="FLOOR";z.Ceiling="CEILING";z.Int="INT";z.Float="FLOAT";z.Has="?";z.Hasnt="!?";z.Intersect="^";z.ListMin="LIST_MIN";z.ListMax="LIST_MAX";z.All="LIST_ALL";z.Count="LIST_COUNT";z.ValueOfList="LIST_VALUE";z.Invert="LIST_INVERT";z._nativeFunctions=null;});var Sr=T(vr=>{Object.defineProperty(vr,"__esModule",{value:true});vr.NumberExpression=void 0;var xd=Ye(),lo=de(),_d=ne(),uo=class i extends xd.Expression{constructor(e,t){if(super(),this.isInt=()=>this.subtype=="int",this.isFloat=()=>this.subtype=="float",this.isBool=()=>this.subtype=="bool",this.GenerateIntoContainer=n=>{this.isInt()?n.AddContent(new lo.IntValue(this.value)):this.isFloat()?n.AddContent(new lo.FloatValue(this.value)):this.isBool()&&n.AddContent(new lo.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, _d.asOrNull)(e,i);return t?t.subtype==this.subtype&&t.value==this.value:false}};vr.NumberExpression=uo;});var co=T(Er=>{Object.defineProperty(Er,"__esModule",{value:true});Er.UnaryExpression=void 0;var wd=Ye(),Od=mt(),On=Sr(),Td=ne(),ui=class extends wd.Expression{get nativeNameForOp(){return this.op==="-"?"_":this.op==="not"?"!":this.op}constructor(e,t){super(),this.op=t,this.GenerateIntoContainer=n=>{this.innerExpression.GenerateIntoContainer(n),n.AddContent(Od.NativeFunctionCall.CallWithName(this.nativeNameForOp));},this.toString=()=>this.nativeNameForOp+this.innerExpression,this.innerExpression=this.AddContent(e);}get typeName(){return "UnaryExpression"}};Er.UnaryExpression=ui;ui.WithInner=(i,e)=>{let t=(0, Td.asOrNull)(i,On.NumberExpression);if(t){if(e==="-"){if(t.isInt())return new On.NumberExpression(-t.value,"int");if(t.isFloat())return new On.NumberExpression(-t.value,"float")}else if(e=="!"||e=="not"){if(t.isInt())return new On.NumberExpression(t.value==0,"bool");if(t.isFloat())return new On.NumberExpression(t.value==0,"bool");if(t.isBool())return new On.NumberExpression(!t.value,"bool")}throw new Error("Unexpected operation or number type")}return new ui(i,e)};});var po=T(br=>{Object.defineProperty(br,"__esModule",{value:true});br.BinaryExpression=void 0;var Pd=Ye(),Fd=mt(),Nd=co(),Id=ne(),ho=class extends Pd.Expression{constructor(e,t,n){super(),this.opName=n,this.GenerateIntoContainer=r=>{this.leftExpression.GenerateIntoContainer(r),this.rightExpression.GenerateIntoContainer(r),this.opName=this.NativeNameForOp(this.opName),r.AddContent(Fd.NativeFunctionCall.CallWithName(this.opName));},this.NativeNameForOp=r=>r==="and"?"&&":r==="or"?"||":r==="mod"?"%":r==="has"?"?":r==="hasnt"?"!?":r,this.toString=()=>`(${this.leftExpression} ${this.opName} ${this.rightExpression})`,this.leftExpression=this.AddContent(e),this.rightExpression=this.AddContent(t),this.opName=n;}get typeName(){return "BinaryExpression"}ResolveReferences(e){if(super.ResolveReferences(e),this.NativeNameForOp(this.opName)==="?"){let t=(0, Id.asOrNull)(this.leftExpression,Nd.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.`);}}};br.BinaryExpression=ho;});var hi=T(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.CharacterSet=void 0;var ci=class{constructor(e){this.set=new Set,this.Add=t=>this.set.add(t),this.AddRange=(t,n)=>{for(let r=t.charCodeAt(0);r<=n.charCodeAt(0);++r)this.Add(String.fromCharCode(r));return this},this.AddCharacters=t=>{if(typeof t=="string"||Array.isArray(t))for(let n of t)this.Add(n);else for(let n of t.set)this.Add(n);return this},e&&this.AddCharacters(e);}};Ar.CharacterSet=ci;ci.FromRange=(i,e)=>new ci().AddRange(i,e);});var xc=T(Dr=>{Object.defineProperty(Dr,"__esModule",{value:true});Dr.CharacterRange=void 0;var Dc=hi(),pi=class{constructor(e,t,n=[]){if(this._start=e,this._end=t,this._correspondingCharSet=new Dc.CharacterSet,this._excludes=new Set,this.ToCharacterSet=()=>{if(this._correspondingCharSet.set.size===0)for(let r=this.start.charCodeAt(0),a;r<=this.end.charCodeAt(0);r+=1)a=String.fromCharCode(r),this._excludes.has(a)||this._correspondingCharSet.AddCharacters(a);return this._correspondingCharSet},n instanceof Dc.CharacterSet)this._excludes=n.set;else for(let r of n)this._excludes.add(r);}get start(){return this._start}get end(){return this._end}};Dr.CharacterRange=pi;pi.Define=(i,e,t=[])=>new pi(i,e,t);});var _r=T(xr=>{Object.defineProperty(xr,"__esModule",{value:true});xr.ChoicePoint=void 0;var Rd=je(),Vd=We(),fo=Te(),go=class extends Rd.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, fo.throwNullException)("ChoicePoint._pathOnChoice"):this.ResolvePath(this._pathOnChoice).container}get pathStringOnChoice(){return this.pathOnChoice===null?(0, fo.throwNullException)("ChoicePoint.pathOnChoice"):this.CompactPathString(this.pathOnChoice)}set pathStringOnChoice(e){this.pathOnChoice=new Vd.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, fo.throwNullException)("ChoicePoint.pathOnChoice");let t=this.pathOnChoice.toString();return "Choice: -> "+t}};xr.ChoicePoint=go;});var sn=T(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.PushPopType=void 0;var _c;(function(i){i[i.Tunnel=0]="Tunnel",i[i.Function=1]="Function",i[i.FunctionEvaluationFromGame=2]="FunctionEvaluationFromGame";})(_c||(wr.PushPopType=_c={}));});var fi=T(Or=>{Object.defineProperty(Or,"__esModule",{value:true});Or.Pointer=void 0;var kd=We(),mo=class i{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 kd.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 i(this.container,this.index)}static StartOf(e){return new i(e,0)}static get Null(){return new i(null,-1)}};Or.Pointer=mo;});var Ct=T(Pr=>{Object.defineProperty(Pr,"__esModule",{value:true});Pr.Divert=void 0;var Ld=We(),Bd=sn(),Wd=tn(),jd=je(),Co=fi(),wc=ye(),Tr=Te(),yo=class i extends jd.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=Co.Pointer.Null;}get targetPointer(){if(this._targetPointer.isNull){let e=this.ResolvePath(this._targetPath).obj;if(this._targetPath===null)return (0, Tr.throwNullException)("this._targetPath");if(this._targetPath.lastComponent===null)return (0, Tr.throwNullException)("this._targetPath.lastComponent");if(this._targetPath.lastComponent.isIndex){if(e===null)return (0, Tr.throwNullException)("targetObj");this._targetPointer.container=e.parent instanceof wc.Container?e.parent:null,this._targetPointer.index=this._targetPath.lastComponent.index;}else this._targetPointer=Co.Pointer.StartOf(e instanceof wc.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 Ld.Path(e);}get hasVariableTarget(){return this.variableDivertName!=null}constructor(e){super(),this._targetPath=null,this._targetPointer=Co.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 i&&this.hasVariableTarget==t.hasVariableTarget?this.hasVariableTarget?this.variableDivertName==t.variableDivertName:this.targetPath===null?(0, Tr.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 Wd.StringBuilder,t=this.targetPath.toString();return e.Append("Divert"),this.isConditional&&e.Append("?"),this.pushesToStack&&(this.stackPushType==Bd.PushPopType.Function?e.Append(" function"):e.Append(" tunnel")),e.Append(" -> "),e.Append(this.targetPathString),e.Append(" ("),e.Append(t),e.Append(")"),e.toString()}}};Pr.Divert=yo;});var Ot=T(Fr=>{Object.defineProperty(Fr,"__esModule",{value:true});Fr.SymbolType=void 0;var Oc;(function(i){i[i.Knot=0]="Knot",i[i.List=1]="List",i[i.ListItem=2]="ListItem",i[i.Var=3]="Var",i[i.SubFlowAndWeave=4]="SubFlowAndWeave",i[i.Arg=5]="Arg",i[i.Temp=6]="Temp";})(Oc||(Fr.SymbolType=Oc={}));});var Wt=T(Nr=>{Object.defineProperty(Nr,"__esModule",{value:true});Nr.VariableAssignment=void 0;var qd=je(),vo=class extends qd.InkObject{constructor(e,t){super(),this.variableName=e||null,this.isNewDeclaration=!!t,this.isGlobal=false;}toString(){return "VarAssign to "+this.variableName}};Nr.VariableAssignment=vo;});var Tn=T(Rr=>{Object.defineProperty(Rr,"__esModule",{value:true});Rr.Choice=void 0;var Md=_r(),Ir=ye(),jt=Pe(),So=Ct(),Tc=de(),$d=pe(),Gd=Ot(),Pc=Wt(),Eo=class extends $d.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,n){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 Ir.Container,this._runtimeChoice=new Md.ChoicePoint(this.onceOnly),this._runtimeChoice.isInvisibleDefault=this.isInvisibleDefault,(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(jt.ControlCommand.EvalStart()),this.startContent){this._returnToR1=new Tc.DivertTargetValue,this._outerContainer.AddContent(this._returnToR1);let r=new Pc.VariableAssignment("$r",true);this._outerContainer.AddContent(r),this._outerContainer.AddContent(jt.ControlCommand.BeginString()),this._divertToStartContentOuter=new So.Divert,this._outerContainer.AddContent(this._divertToStartContentOuter),this._startContentRuntimeContainer=this.startContent.GenerateRuntimeObject(),this._startContentRuntimeContainer.name="s";let a=new So.Divert;a.variableDivertName="$r",this._startContentRuntimeContainer.AddContent(a),this._outerContainer.AddToNamedContentOnly(this._startContentRuntimeContainer),this._r1Label=new Ir.Container,this._r1Label.name="$r1",this._outerContainer.AddContent(this._r1Label),this._outerContainer.AddContent(jt.ControlCommand.EndString()),this._runtimeChoice.hasStartContent=true;}if(this.choiceOnlyContent){this._outerContainer.AddContent(jt.ControlCommand.BeginString());let r=this.choiceOnlyContent.GenerateRuntimeObject();this._outerContainer.AddContentsOfContainer(r),this._outerContainer.AddContent(jt.ControlCommand.EndString()),this._runtimeChoice.hasChoiceOnlyContent=true;}if(this.condition&&(this.condition.GenerateIntoContainer(this._outerContainer),this._runtimeChoice.hasCondition=true),(this.startContent||this.choiceOnlyContent||this.condition)&&this._outerContainer.AddContent(jt.ControlCommand.EvalEnd()),this._outerContainer.AddContent(this._runtimeChoice),this._innerContentContainer=new Ir.Container,this.startContent){this._returnToR2=new Tc.DivertTargetValue,this._innerContentContainer.AddContent(jt.ControlCommand.EvalStart()),this._innerContentContainer.AddContent(this._returnToR2),this._innerContentContainer.AddContent(jt.ControlCommand.EvalEnd());let r=new Pc.VariableAssignment("$r",true);this._innerContentContainer.AddContent(r),this._divertToStartContentInner=new So.Divert,this._innerContentContainer.AddContent(this._divertToStartContentInner),this._r2Label=new Ir.Container,this._r2Label.name="$r2",this._innerContentContainer.AddContent(this._r2Label);}if(this.innerContent){let r=this.innerContent.GenerateRuntimeObject();this._innerContentContainer.AddContentsOfContainer(r);}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=n,this.indentationDepth=1,e&&this.AddContent(this.startContent),t&&this.AddContent(this.choiceOnlyContent),n&&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,Gd.SymbolType.SubFlowAndWeave);}};Rr.Choice=Eo;});var Fc=T(kr=>{Object.defineProperty(kr,"__esModule",{value:true});kr.StringParserElement=void 0;var Vr=class i{constructor(){this.characterIndex=0,this.characterInLineIndex=0,this.lineIndex=0,this.reportedErrorInScope=false,this.uniqueId=0,this.customFlags=0,this.CopyFrom=e=>{i._uniqueIdCounter++,this.uniqueId=i._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;};}};kr.StringParserElement=Vr;Vr._uniqueIdCounter=1e3;});var Ic=T(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.StringParserState=void 0;var Nc=Fc(),bo=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 n=0;n<200;++n)this._stack[n]=new Nc.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],n=this._stack[this._numElements];return this._numElements++,n.CopyFrom(t),n.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],n=this._stack[this._numElements-1];t.SquashFrom(n),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 Nc.StringParserElement;this._numElements=1;}};Lr.StringParserState=bo;});var Do=T(an=>{Object.defineProperty(an,"__esModule",{value:true});an.StringParser=an.ParseSuccess=void 0;var Ao=hi(),Hd=Ic();an.ParseSuccess=Symbol("ParseSuccessStruct");var di=class i{constructor(e){this.ParseRule=null,this.errorHandler=null,this.hadError=false,this.BeginRule=()=>this.state.Push(),this.FailRule=n=>(this.state.Pop(n),null),this.CancelRule=n=>{this.state.Pop(n);},this.SucceedRule=(n,r=null)=>{let a=this.state.Peek(n),s=this.state.PeekPenultimate();this.RuleDidSucceed&&this.RuleDidSucceed(r,s,a),this.state.Squash();let o=r;return o===null&&(o=i.ParseSuccess),o},this.Expect=(n,r=null,a=null)=>{let s=this.ParseObject(n);if(s===null){r===null&&(r=n.name);let o,l=this.LineRemainder();l===null||l.length===0?o="end of line":o=`'${l}'`,this.Error(`Expected ${r} but saw ${o}`),a!==null&&(s=a());}return s},this.Error=(n,r=false)=>{this.ErrorOnLine(n,this.lineIndex+1,r);},this.ErrorWithParsedObject=(n,r,a=false)=>{this.ErrorOnLine(n,r.debugMetadata?r.debugMetadata.startLineNumber:-1,a);},this.ErrorOnLine=(n,r,a)=>{if(!this.state.errorReportedAlreadyInScope){let s=a?"Warning":"Error";if(this.errorHandler)this.errorHandler(n,this.index,r-1,a);else throw new Error(`${s} on line ${r}: ${n}`);this.state.NoteErrorReported();}a||(this.hadError=true);},this.Warning=n=>this.Error(n,true),this.LineRemainder=()=>this.Peek(()=>this.ParseUntilCharactersFromString(`
5
5
  \r`)),this.SetFlag=(n,r)=>{r?this.state.customFlags|=n:this.state.customFlags&=~n;},this.GetFlag=n=>!!(this.state.customFlags&n),this.ParseObject=n=>{let r=this.BeginRule(),a=this.state.stackHeight,s=n();if(a!==this.state.stackHeight)throw new Error("Mismatched Begin/Fail/Succeed rules");return s===null?this.FailRule(r):(this.SucceedRule(r,s),s)},this.Parse=n=>{let r=this.BeginRule(),a=n();return a===null?(this.FailRule(r),null):(this.SucceedRule(r,a),a)},this.OneOf=n=>{for(let r of n){let a=this.ParseObject(r);if(a!==null)return a}return null},this.OneOrMore=n=>{let r=[],a=null;do a=this.ParseObject(n),a!==null&&r.push(a);while(a!==null);return r.length>0?r:null},this.Optional=n=>()=>{let r=this.ParseObject(n);return r===null?i.ParseSuccess:r},this.Exclude=n=>()=>this.ParseObject(n)&&i.ParseSuccess,this.OptionalExclude=n=>()=>(this.ParseObject(n),i.ParseSuccess),this.String=n=>()=>this.ParseString(n),this.TryAddResultToList=(n,r,a=true)=>{if(n!==i.ParseSuccess){if(a&&Array.isArray(n)){let s=n;if(s!==null){for(let o of s)r.push(o);return}}r.push(n);}},this.Interleave=(n,r,a=null,s=true)=>{let o=this.BeginRule(),l=[],u=this.ParseObject(n);if(u===null)return this.FailRule(o);this.TryAddResultToList(u,l,s);let c=null,h=null;do{if(a!==null&&this.Peek(a)!==null||(c=this.ParseObject(r),c===null))break;if(this.TryAddResultToList(c,l,s),h=null,c!==null){if(h=this.ParseObject(n),h===null)break;this.TryAddResultToList(h,l,s);}}while((c!==null||h!==null)&&!(c===i.ParseSuccess&&h==i.ParseSuccess)&&this.remainingLength>0);return l.length===0?this.FailRule(o):this.SucceedRule(o,l)},this.ParseString=n=>{if(n.length>this.remainingLength)return null;let r=this.BeginRule(),a=this.index,s=this.characterInLineIndex,o=this.lineIndex,l=true;for(let u=0;u<n.length;u+=1){let c=n[u];if(this._chars[a]!==c){l=false;break}c===`
6
6
  `&&(o++,s=-1),a++,s++;}return this.index=a,this.characterInLineIndex=s,this.lineIndex=o,l?this.SucceedRule(r,n):this.FailRule(r)},this.ParseSingleCharacter=()=>{if(this.remainingLength>0){let n=this._chars[this.index];return n===`
7
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,r=-1)=>this.ParseCharactersFromString(n,false,r),this.ParseUntilCharactersFromCharSet=(n,r=-1)=>this.ParseCharactersFromCharSet(n,false,r),this.ParseCharactersFromString=(n,r=-1,a=-1)=>{let s=new Eo.CharacterSet(n);return typeof r=="number"?this.ParseCharactersFromCharSet(s,true,r):this.ParseCharactersFromCharSet(s,r,a)},this.ParseCharactersFromCharSet=(n,r=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,c=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===r&&c<a;)this._chars[o]===`
7
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1,n}return "0"},this.ParseUntilCharactersFromString=(n,r=-1)=>this.ParseCharactersFromString(n,false,r),this.ParseUntilCharactersFromCharSet=(n,r=-1)=>this.ParseCharactersFromCharSet(n,false,r),this.ParseCharactersFromString=(n,r=-1,a=-1)=>{let s=new Ao.CharacterSet(n);return typeof r=="number"?this.ParseCharactersFromCharSet(s,true,r):this.ParseCharactersFromCharSet(s,r,a)},this.ParseCharactersFromCharSet=(n,r=true,a=-1)=>{a===-1&&(a=Number.MAX_SAFE_INTEGER);let s=this.index,o=this.index,l=this.characterInLineIndex,u=this.lineIndex,c=0;for(;o<this._chars.length&&n.set.has(this._chars[o])===r&&c<a;)this._chars[o]===`
8
8
  `&&(u+=1,l=-1),o+=1,l+=1,c+=1;return this.index=o,this.characterInLineIndex=l,this.lineIndex=u,this.index>s?this._chars.slice(s,this.index).join(""):null},this.Peek=n=>{let r=this.BeginRule(),a=n();return this.CancelRule(r),a},this.ParseInt=()=>{let n=this.index,r=this.characterInLineIndex,a=this.ParseString("-")!==null;this.ParseCharactersFromString(" ");let s=this.ParseCharactersFromCharSet(i.numbersCharacterSet);if(s===null)return this.index=n,this.characterInLineIndex=r,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 n=this.index,r=this.characterInLineIndex,a=this.ParseInt();if(a!==null&&this.ParseString(".")!==null){let s=this.ParseCharactersFromCharSet(i.numbersCharacterSet);return +`${a}.${s}`}return this.index=n,this.characterInLineIndex=r,null},this.ParseNewline=()=>{let n=this.BeginRule();return this.ParseString("\r"),this.ParseString(`
9
9
  `)===null?this.FailRule(n):this.SucceedRule(n,`
10
- `)};let t=this.PreProcessInputString(e);this.state=new Hd.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,n=null){let r=this.BeginRule(),a=new Eo.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){s+=u,u===`
11
- `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(r,String(s)):this.FailRule(r)}};an.StringParser=di;di.ParseSuccess=an.ParseSuccess;di.numbersCharacterSet=new Eo.CharacterSet("0123456789");});var Ic=P(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.CommentEliminator=void 0;var Ao=hi(),Jd=bo(),Do=class extends Jd.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new Ao.CharacterSet(`/\r
12
- `),this._commentBlockEndCharacter=new Ao.CharacterSet("*"),this._newlineCharacters=new Ao.CharacterSet(`
10
+ `)};let t=this.PreProcessInputString(e);this.state=new Hd.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,n=null){let r=this.BeginRule(),a=new Ao.CharacterSet;t!==null&&(a.set=new Set([...a.set.values(),...t.set.values()])),n!==null&&(a.set=new Set([...a.set.values(),...n.set.values()]));let s="",o=null;do{let l=this.ParseUntilCharactersFromCharSet(a);if(l&&(s+=l),o=this.Peek(e),o!==null)break;{if(this.endOfInput)break;let u=this.currentCharacter;if(t!==null&&t.set.has(u)){s+=u,u===`
11
+ `&&(this.lineIndex+=1,this.characterInLineIndex=-1),this.index+=1,this.characterInLineIndex+=1;continue}else break}}while(true);return s.length>0?this.SucceedRule(r,String(s)):this.FailRule(r)}};an.StringParser=di;di.ParseSuccess=an.ParseSuccess;di.numbersCharacterSet=new Ao.CharacterSet("0123456789");});var Rc=T(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.CommentEliminator=void 0;var xo=hi(),Jd=Do(),_o=class extends Jd.StringParser{constructor(){super(...arguments),this._commentOrNewlineStartCharacter=new xo.CharacterSet(`/\r
12
+ `),this._commentBlockEndCharacter=new xo.CharacterSet("*"),this._newlineCharacters=new xo.CharacterSet(`
13
13
  \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?`
14
- `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};Lr.CommentEliminator=Do;});var Wr=P(Br=>{Object.defineProperty(Br,"__esModule",{value:true});Br.Conditional=void 0;var Ud=Ce(),Rc=Oe(),zd=he(),xo=class extends zd.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Ud.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let r of this.branches){let a=r.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Rc.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Rc.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},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 n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};Br.Conditional=xo;});var qt=P(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.Text=void 0;var Kd=he(),Xd=fe(),_o=class extends Kd.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Xd.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};jr.Text=_o;});var Mr=P(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.ConstantDeclaration=void 0;var Yd=he(),Qd=wt(),wo=class extends Yd.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,Qd.SymbolType.Var);}};qr.ConstantDeclaration=wo;});var Pn=P($r=>{Object.defineProperty($r,"__esModule",{value:true});$r.FlowLevel=void 0;var Vc;(function(i){i[i.Story=0]="Story",i[i.Knot=1]="Knot",i[i.Stitch=2]="Stitch",i[i.WeavePoint=3]="WeavePoint";})(Vc||($r.FlowLevel=Vc={}));});var gi=P(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.Gather=void 0;var Zd=Ce(),eg=he(),tg=wt(),Oo=class extends eg.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 n=new Zd.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let r of this.content)n.AddContent(r.runtimeObject);return n},this.toString=()=>{var n,r;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((r=this.identifier)===null||r===void 0?void 0:r.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,tg.SymbolType.SubFlowAndWeave);}};Gr.Gather=Oo;});var on=P(Jr=>{Object.defineProperty(Jr,"__esModule",{value:true});Jr.Path=void 0;var Hr=ie(),kc=yt(),Fn=Pn(),ng=ln(),To=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Fn.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(Hr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Fn.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let r=this.ResolveBaseTarget(n);return r===null?null:this.components.length>1?this.ResolveTailComponents(r):r},this.ResolveBaseTarget=n=>{let r=this.firstComponent,a=n;for(;a;){let s=a===n,o=this.GetChildFromContext(a,r,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let r=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,l=(0, Hr.asOrNull)(r,kc.FlowBase);if(l!==null?o=l.flowLevel+1:o=Fn.FlowLevel.WeavePoint,r=this.GetChildFromContext(r,s,o),r===null)break}return r},this.GetChildFromContext=(n,r,a,s=false)=>{let o=a===null,l=(0, Hr.asOrNull)(n,ng.Weave);if(r&&l!==null&&(o||a===Fn.FlowLevel.WeavePoint))return l.WeavePointNamed(r);let u=(0, Hr.asOrNull)(n,kc.FlowBase);if(r&&u!==null){let c=s||u.flowLevel===Fn.FlowLevel.Knot;return u.ContentWithNameAtLevel(r,a,c)}return null},Object.values(Fn.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"}};Jr.Path=To;});var No=P(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.ReturnType=void 0;var ig=he(),rg=Ce(),Po=Oe(),sg=rn(),Fo=class extends ig.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new rg.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(Po.ControlCommand.EvalStart()),t.AddContent(new sg.Void),t.AddContent(Po.ControlCommand.EvalEnd())),t.AddContent(Po.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};Ur.ReturnType=Fo;});var mi=P(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.ClosestFlowBase=void 0;function ag(i){let e=i.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}zr.ClosestFlowBase=ag;});var Xr=P(Kr=>{Object.defineProperty(Kr,"__esModule",{value:true});Kr.Identifier=void 0;var Io=class i{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new i("DONE")}};Kr.Identifier=Io;});var yt=P(Yr=>{Object.defineProperty(Yr,"__esModule",{value:true});Yr.FlowBase=void 0;var og=Tn(),Ro=In(),lg=Nn(),vt=Pn(),ug=gi(),cg=he(),hg=on(),pg=No(),fg=Ce(),dg=Ct(),gg=Wt(),Vo=wt(),mg=ln(),Cg=mi(),yg=Xr(),Lc=ie(),ko=class i extends cg.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,n=null,r=false,a=false){super(),this.isFunction=r,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 l,u;let c=[],h=[];this._subFlowsByName=new Map;for(let d of s){let g=(0, Lc.asOrNull)(d,i);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),h.push(d),!((l=g.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=g.identifier)===null||u===void 0?void 0:u.name,g)):c.push(d);}o&&c.push(new ug.Gather(null,1),new Ro.Divert(new hg.Path(yg.Identifier.Done())));let f=[];return c.length>0&&(this._rootWeave=new mg.Weave(c,0),f.push(this._rootWeave)),h.length>0&&f.push(...h),f},this.ResolveVariableWithName=(s,o)=>{var l;let u={},c=o===null?this:(0, Cg.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((l=h.identifier)===null||l===void 0?void 0:l.name)===s)return u.found=true,u.isArgument=true,u.ownerFlow=c,u}if(c!==this.story&&c.variableDeclarations.has(s))return u.found=true,u.ownerFlow=c,u.isTemporary=true,u}return this.story.variableDeclarations.has(s)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,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===vt.FlowLevel.Knot||this.flowLevel===vt.FlowLevel.Stitch)&&(o=this.Find(pg.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let l=new fg.Container;l.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let c=this.content[u];if(c instanceof i){let h=c,f=h.runtimeObject;u===0&&!h.hasParameters&&this.flowLevel===vt.FlowLevel.Knot&&(this._startingSubFlowDivert=new dg.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let d=f,g=l.namedContent.get(d.name)||null;if(g){let y=`${this.GetType()} already contains flow named '${d.name}' (at ${g.debugMetadata})`;this.Error(y,h);}l.AddToNamedContentOnly(d);}else c&&l.AddContent(c.runtimeObject);u+=1;}return this.flowLevel!==vt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,c=new gg.VariableAssignment(u,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&s===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===vt.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===vt.FlowLevel.WeavePoint)return l?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:l?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,vt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(s,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==vt.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[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(Ro.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof lg.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(og.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},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 l=(0, Lc.asOrNull)(s,Ro.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let r of this.args)e.CheckForNamingCollisions(this,r.identifier,Vo.SymbolType.Arg,"argument");for(let r=0;r<this.args.length;r+=1)for(let a=r+1;a<this.args.length;a+=1)((t=this.args[r].identifier)===null||t===void 0?void 0:t.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[r].identifier}'`);}if(this.flowLevel!==vt.FlowLevel.Story){let r=this.flowLevel===vt.FlowLevel.Knot?Vo.SymbolType.Knot:Vo.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,r);}}};Yr.FlowBase=ko;});var Zr=P(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.ContentList=void 0;var vg=Ce(),Sg=he(),Eg=qt(),bg=ie(),Lo=class extends Sg.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let r=(0, bg.asOrNull)(this.content[n],Eg.Text);if(r===null)break;if(r.text=r.text.replace(new RegExp(/[ \t]/g),""),r.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new vg.Container;if(this.content!==null)for(let r of this.content){let a=r.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Qr.ContentList=Lo;});var Rn=P(es=>{Object.defineProperty(es,"__esModule",{value:true});es.VariableReference=void 0;var Ag=je(),Dg=We(),Bo=class extends Ag.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 Dg.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};es.VariableReference=Bo;});var Vn=P(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.VariableReference=void 0;var xg=Zr(),_g=Ye(),Bc=yt(),wg=on(),Og=Rn(),Tg=ln(),Pg=Xr(),Wc=ie(),Wo=class extends _g.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(Wc.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Pg.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 n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new Og.VariableReference(this.name),this.path.length===1||this.path.length===2){let r="",a="";this.path.length===1?r=this.path[0]:(a=this.path[0],r=this.path[1]),this.story.ResolveListItem(a,r,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 wg.Path(this.pathIdentifiers),n=t.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let r=(0, Wc.asOrNull)(n,Bc.FlowBase);r&&r.isFunction&&(this.parent instanceof Tg.Weave||this.parent instanceof xg.ContentList||this.parent instanceof Bc.FlowBase)&&this.Warning(`'${r.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${r.identifier}()`);return}if(this.path.length>1){let r=`Could not find target for read count: ${t}`;this.path.length<=2&&(r+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(r);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};ts.VariableReference=Wo;});var Ci=P(ss=>{Object.defineProperty(ss,"__esModule",{value:true});ss.FunctionCall=void 0;var St=Oe(),Fg=In(),Ng=Nn(),Ig=Ye(),Rg=Me(),Vg=fe(),is=mt(),jc=vr(),kg=on(),Lg=fe(),Bg=Vn(),ns=ie(),rs=class i extends Ig.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=n=>{let r=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"),n.AddContent(St.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(St.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, ns.asOrNull)(this.args[0],Ng.DivertTarget),o=(0, ns.asOrNull)(this.args[0],Bg.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(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(St.ControlCommand.TurnsSince()):n.AddContent(St.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, ns.asOrNull)(this.args[s],jc.NumberExpression);if(o&&!o.isInt()){let l=s===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(St.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, ns.asOrNull)(this.args[0],jc.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(St.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(n);n.AddContent(St.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(St.ControlCommand.ListRandom());else if(is.NativeFunctionCall.CallExistsWithName(this.name)){let s=is.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${i.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(n);n.AddContent(is.NativeFunctionCall.CallWithName(this.name));}else if(r!==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)n.AddContent(new Lg.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(St.ControlCommand.ListFromInt());else {let s=new Rg.InkList;s.SetInitialOriginName(this.name),n.AddContent(new Vg.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(St.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Fg.Divert(new kg.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,n=t.runtimeDivert.variableDivertName!=null;if(n){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 r=t.targetContent;if(r===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!r.containerForCounting)throw new Error;r.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${i.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};ss.FunctionCall=rs;rs.IsBuiltIn=i=>is.NativeFunctionCall.CallExistsWithName(i)?true:i==="CHOICE_COUNT"||i==="TURNS_SINCE"||i==="TURNS"||i==="RANDOM"||i==="SEED_RANDOM"||i==="LIST_VALUE"||i==="LIST_RANDOM"||i==="READ_COUNT";});var qo=P(as=>{Object.defineProperty(as,"__esModule",{value:true});as.MultipleConditionExpression=void 0;var Wg=Ye(),jg=mt(),jo=class extends Wg.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let r of this.subExpressions)r.GenerateIntoContainer(t),n||t.AddContent(jg.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};as.MultipleConditionExpression=jo;});var Nn=P(os=>{Object.defineProperty(os,"__esModule",{value:true});os.DivertTarget=void 0;var qg=co(),Mg=Tn(),$g=Wr(),Gg=Ho(),Hg=fe(),Mo=Ye(),Jg=yt(),qc=Ci(),Ug=qo(),Mc=Vn(),$o=ie(),Go=class i extends Mo.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 Hg.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, $o.asOrNull)(t,i);if(!n||!this.divert.target||!n.divert.target)return false;let r=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return r===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 Mo.Expression;){let r=false,a=false,s=t.parent;if(s instanceof qg.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?r=true:(o.leftExpression instanceof i||o.leftExpression instanceof Mc.VariableReference)&&(o.rightExpression instanceof i||o.rightExpression instanceof Mc.VariableReference)||(r=true),a=true;}else if(s instanceof qc.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(r=true),a=true;}else (s instanceof Mo.Expression||s instanceof Ug.MultipleConditionExpression||s instanceof Mg.Choice&&s.condition===t||s instanceof $g.Conditional||s instanceof Gg.ConditionalSingleBranch)&&(r=true,a=true);if(r&&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 n=this.divert.targetContent;if(n!==null){let r=n.containerForCounting;if(r!==null){let s=(0, $o.asOrNull)(this.parent,qc.FunctionCall);s&&s.isTurnsSince||(r.visitsShouldBeCounted=true),r.turnIndexShouldBeCounted=true;}let a=(0, $o.asOrNull)(n,Jg.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}').`);}}};os.DivertTarget=Go;});var In=P(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.Divert=void 0;var zg=Ce(),yi=Oe(),Kg=Ct(),Jo=Nn(),Uo=yt(),Xg=Ci(),Yg=he(),$c=on(),Qg=We(),Gc=sn(),Zg=fe(),Hc=Vn(),em=mi(),vi=ie(),zo=class extends Yg.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 yi.ControlCommand.End();if(this.isDone)return yi.ControlCommand.Done();this.runtimeDivert=new Kg.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let r=new zg.Container;if(n){this.isFunctionCall||r.AddContent(yi.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],l=null;if(a&&s<a.length&&(l=a[s]),l&&l.isByReference){let u=(0, vi.asOrNull)(o,Hc.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let c=new $c.Path(u.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 Zg.VariablePointerValue(u.name);r.AddContent(f);}else o.GenerateIntoContainer(r);}this.isFunctionCall||r.AddContent(yi.ControlCommand.EvalEnd());}return this.isThread?r.AddContent(yi.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Gc.PushPopType.Function:Gc.PushPopType.Tunnel),r.AddContent(this.runtimeDivert),r}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let r=(0, vi.asOrNull)((0, em.ClosestFlowBase)(this),Uo.FlowBase);if(r){let a=r.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});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=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let r=(0, vi.asOrNull)(this.targetContent,Uo.FlowBase);if(n===0&&(r===null||!r.hasParameters))return;if(r===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(r!==null&&(r.args===null||!r.args&&n>0)){this.Error(`target (${r.name}) doesn't take parameters`);return}else if(this.parent instanceof Jo.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=r.args.length;if(a!==n){let s;n===0?s="but there weren't any passed to it":n<a?s=`but only got ${n}`:s=`but got ${n}`,this.Error(`to '${r.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=r.args[s],l=this.args[s];if(o.isDivertTarget){let u=(0, vi.asOrNull)(l,Hc.VariableReference);if(!(l instanceof Jo.DivertTarget)&&u===null)this.Error(`Target '${r.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let c=new $c.Path(u.pathIdentifiers);c.ResolveFromContext(u)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(r===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let r=this.target?this.target.firstComponent:null,a=n.externals.get(r);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 '${r}'. Expected ${s} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},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, vi.asOrNull)(this.targetContent,Uo.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 Jo.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 n=this.targetContent!==null,r=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(r=Xg.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),r||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 Qg.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!r&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};ls.Divert=zo;});var Jc=P(us=>{Object.defineProperty(us,"__esModule",{value:true});us.GatherPointToResolve=void 0;var Ko=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};us.GatherPointToResolve=Ko;});var Uc=P(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.SequenceDivertToResolve=void 0;var Xo=class{constructor(e,t){this.divert=e,this.targetContent=t;}};cs.SequenceDivertToResolve=Xo;});var Yo=P(hs=>{Object.defineProperty(hs,"__esModule",{value:true});hs.SequenceType=void 0;var zc;(function(i){i[i.Stopping=1]="Stopping",i[i.Cycle=2]="Cycle",i[i.Shuffle=4]="Shuffle",i[i.Once=8]="Once";})(zc||(hs.SequenceType=zc={}));});var el=P(ds=>{Object.defineProperty(ds,"__esModule",{value:true});ds.Sequence=void 0;var Kc=Ce(),at=Oe(),Qo=Ct(),Si=fe(),ps=mt(),tm=he(),nm=Uc(),fs=Yo(),im=ln(),Zo=class extends tm.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Kc.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(at.ControlCommand.EvalStart()),n.AddContent(at.ControlCommand.VisitIndex());let r=(this.sequenceType&fs.SequenceType.Once)>0,a=(this.sequenceType&fs.SequenceType.Cycle)>0,s=(this.sequenceType&fs.SequenceType.Stopping)>0,o=(this.sequenceType&fs.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(r&&(l+=1),s||r?(n.AddContent(new Si.IntValue(l-1)),n.AddContent(ps.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new Si.IntValue(this.sequenceElements.length)),n.AddContent(ps.NativeFunctionCall.CallWithName("%"))),o){let c=at.ControlCommand.NoOp();if(r||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(at.ControlCommand.Duplicate()),n.AddContent(new Si.IntValue(f)),n.AddContent(ps.NativeFunctionCall.CallWithName("=="));let d=new Qo.Divert;d.isConditional=true,n.AddContent(d),this.AddDivertToResolve(d,c);}let h=this.sequenceElements.length;s&&(h-=1),n.AddContent(new Si.IntValue(h)),n.AddContent(at.ControlCommand.SequenceShuffleIndex()),(r||s)&&n.AddContent(c);}n.AddContent(at.ControlCommand.EvalEnd());let u=at.ControlCommand.NoOp();for(let c=0;c<l;c+=1){n.AddContent(at.ControlCommand.EvalStart()),n.AddContent(at.ControlCommand.Duplicate()),n.AddContent(new Si.IntValue(c)),n.AddContent(ps.NativeFunctionCall.CallWithName("==")),n.AddContent(at.ControlCommand.EvalEnd());let h=new Qo.Divert;h.isConditional=true,n.AddContent(h);let f;c<this.sequenceElements.length?f=this.sequenceElements[c].runtimeObject:f=new Kc.Container,f.name=`s${c}`,f.InsertContent(at.ControlCommand.PopEvaluatedValue(),0);let d=new Qo.Divert;f.AddContent(d),n.AddToNamedContentOnly(f),this.AddDivertToResolve(h,f),this.AddDivertToResolve(d,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,r)=>{this._sequenceDivertsToResolve.push(new nm.SequenceDivertToResolve(n,r));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let r=n.content,a=null;r===null||r.length===0?a=n:a=new im.Weave(r),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;}};ds.Sequence=Zo;});var nl=P(gs=>{Object.defineProperty(gs,"__esModule",{value:true});gs.TunnelOnwards=void 0;var rm=Ce(),Ei=Oe(),sm=Ct(),am=fe(),om=he(),lm=rn(),um=ie(),cm=Rn(),tl=class extends om.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new rm.Container;if(e.AddContent(Ei.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===Ei.ControlCommand.CommandType.EvalStart?s=l:u.commandType===Ei.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let r=(0, um.asOrNull)(t,sm.Divert);if(r!=null&&r.hasVariableTarget){let a=new cm.VariableReference(r.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new am.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new lm.Void);return e.AddContent(Ei.ControlCommand.EvalEnd()),e.AddContent(Ei.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);}};gs.TunnelOnwards=tl;});var sl=P(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.ListDefinition=void 0;var il=Me(),rl=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 n=new il.InkListItem(this.name,e);this._items.set(n.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[n,r]of this._itemNameToValues)if(r==e)return t=new il.InkListItem(this.name,n),{result:t,exists:true};return t=il.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};ms.ListDefinition=rl;});var ys=P(Cs=>{Object.defineProperty(Cs,"__esModule",{value:true});Cs.ListDefinition=void 0;var hm=Me(),pm=Me(),fm=sl(),dm=fe(),gm=he(),mm=wt(),al=class extends gm.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new fm.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=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,r;let a=new hm.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new pm.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((r=this.identifier)===null||r===void 0?void 0:r.name)||""),new dm.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,mm.SymbolType.List);}};Cs.ListDefinition=al;});var ll=P(vs=>{Object.defineProperty(vs,"__esModule",{value:true});vs.VariableAssignment=void 0;var Cm=Ce(),ym=mi(),vm=ys(),Sm=he(),Xc=wt(),Em=Wt(),bm=Vn(),Am=ie(),ol=class extends Sm.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:n,listDef:r,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, ym.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new Cm.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Em.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=!!n,r instanceof vm.ListDefinition?(this.listDefinition=this.AddContent(r),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?Xc.SymbolType.Var:Xc.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Am.asOrNull)(this.expression,bm.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);}}};vs.VariableAssignment=ol;});var ln=P(bs=>{Object.defineProperty(bs,"__esModule",{value:true});bs.Weave=void 0;var Yc=ir(),Ze=Tn(),Ss=Wr(),Dm=Mr(),xm=Ce(),Es=In(),_m=Ct(),wm=Nn(),Om=yt(),Et=gi(),Tm=Jc(),Pm=he(),ul=el(),Fm=qt(),Nm=nl(),Im=ll(),et=ie(),cl=class i extends Pm.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 n=this.content.length-1;n>=0;--n){e=this.content[n];let r=(0, et.asOrNull)(e,Fm.Text);if(!(r&&r.text===`
15
- `)&&!this.IsGlobalDeclaration(e))break}let t=(0, et.asOrNull)(e,i);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 n,r,a;let s=[...this.FindAll(Et.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(Ze.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof Et.Gather?"gather":"choice",c=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((r=o.identifier)===null||r===void 0)&&r.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let r=this.content[n];if(r instanceof Ze.Choice||r instanceof Et.Gather){let s=r.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let h=(0, et.asOrNull)(this.content[n],Ze.Choice)||(0, et.asOrNull)(this.content[n],Et.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let c=new i(u,s);this.InsertContent(o,c),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let r of n)if(r instanceof Ze.Choice||r instanceof Et.Gather)return r.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new xm.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof Ze.Choice||n instanceof Et.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof i){let r=n;this.AddRuntimeForNestedWeave(r),this.gatherPointsToResolve.splice(0,0,...r.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let r=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),r){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 Et.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof Es.Divert)l=o.runtimeObject;else {l=new _m.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new Tm.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Et.Gather)this.AddRuntimeForGather(n);else if(n instanceof Ze.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Et.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let r=n;if(this.currentContainer.AddContent(r.runtimeObject),!r.innerContentContainer)throw new Error;r.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(r.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, et.asOrNull)(n,Ze.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,r=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, et.asOrNull)(s,i);o&&(!a&&n===null&&(n=o),a&&r===null&&(r=o)),(s instanceof ul.Sequence||s instanceof Ss.Conditional)&&(a=true);}if(!(n===null&&r===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],l=false;if(a){if(o instanceof Ze.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof Ze.Choice)){let u=n||r;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let r=this.namedWeavePoints.get(n);return r||null},this.IsGlobalDeclaration=n=>{let r=(0, et.asOrNull)(n,Im.VariableAssignment);return !!(r&&r.isGlobalDeclaration&&r.isDeclaration||(0, et.asOrNull)(n,Dm.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let r=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||r.push(l);let s=(0, et.asOrNull)(a.parent,i);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let l=o+1;l<s.content.length;l+=1){let u=s.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof Ze.Choice||u instanceof Et.Gather||u instanceof i)break;r.push(u);}}return r},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Yc.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,n);}else {for(let a of this.content)if(a instanceof Ze.Choice||a instanceof Es.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let r=null;for(let s=n.parent;s!==null;s=s.parent)if(s instanceof ul.Sequence||s instanceof Ss.Conditional){r=(0, et.asOrNull)(s,Ss.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";r!==null&&r.FindAll(Ze.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,r,a)=>{let s=false,o=r;for(let l of n){if(l.Find(Es.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof wm.DivertTarget))!==null&&(s=true),l.Find(Nm.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof Yc.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let r=n.content.length-1;r>=0;--r){let a=(0, et.asOrNull)(n.content[r],Es.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let r of this.ancestry){let a=(0, et.asOrNull)(r,Om.FlowBase);if(a)n.push(a);else break}for(let[r,a]of this.namedWeavePoints)for(let s of n){let o=s.ContentWithNameAtLevel(r);if(o&&o!==a){let l=`${a.GetType()} '${r}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,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 n=this.parent;n!==null;n=n.parent)if(n instanceof ul.Sequence||n instanceof Ss.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};bs.Weave=cl;});var Ho=P(Ds=>{Object.defineProperty(Ds,"__esModule",{value:true});Ds.ConditionalSingleBranch=void 0;var Qc=Ce(),As=Oe(),Zc=Ct(),Rm=he(),Vm=mt(),km=fe(),Lm=qt(),Bm=ln(),Wm=ie(),hl=class extends Rm.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 r of this._innerWeave.content){let a=(0, Wm.asOrNull)(r,Lm.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 Qc.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(As.ControlCommand.Duplicate()),this._conditionalDivert=new Zc.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let r=this.ownExpression!==null;r&&t.AddContent(As.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Vm.NativeFunctionCall.CallWithName("==")),r&&t.AddContent(As.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new km.StringValue(`
16
- `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(As.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new Zc.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Qc.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Bm.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);}};Ds.ConditionalSingleBranch=hl;});var th=P(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.CustomFlags=void 0;var eh;(function(i){i[i.ParsingString=1]="ParsingString",i[i.TagActive=2]="TagActive";})(eh||(xs.CustomFlags=eh={}));});var nh=P(_s=>{Object.defineProperty(_s,"__esModule",{value:true});_s.DebugMetadata=void 0;var pl=class i{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new i;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}};_s.DebugMetadata=pl;});var ih=P(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.ExternalDeclaration=void 0;var jm=he(),fl=class extends jm.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}`}};ws.ExternalDeclaration=fl;});var rh=P(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.FlowDecl=void 0;var dl=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};Os.FlowDecl=dl;});var ml=P(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.Wrap=void 0;var qm=he(),gl=class extends qm.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Ts.Wrap=gl;});var sh=P(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.Glue=void 0;var Mm=ml(),Cl=class extends Mm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Ps.Glue=Cl;});var Ns=P(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.Glue=void 0;var $m=je(),yl=class extends $m.InkObject{toString(){return "Glue"}};Fs.Glue=yl;});var oh=P(Is=>{Object.defineProperty(Is,"__esModule",{value:true});Is.IncDecExpression=void 0;var Gm=Zr(),ah=Ye(),Hm=yt(),Jm=mt(),Um=fe(),zm=Wt(),Km=Rn(),Xm=ln(),vl=class extends ah.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=r=>{var a,s;r.AddContent(new Km.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(r):r.AddContent(new Um.IntValue(1)),r.AddContent(Jm.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new zm.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),r.AddContent(this._runtimeAssignment);},this.toString=()=>{var r,a;return this.expression?`${(r=this.varIdentifier)===null||r===void 0?void 0:r.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof ah.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.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=n.isGlobal,!(this.parent instanceof Xm.Weave)&&!(this.parent instanceof Hm.FlowBase)&&!(this.parent instanceof Gm.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Is.IncDecExpression=vl;});var El=P(Rs=>{Object.defineProperty(Rs,"__esModule",{value:true});Rs.IncludedFile=void 0;var Ym=he(),Sl=class extends Ym.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Rs.IncludedFile=Sl;});var lh=P(Vs=>{Object.defineProperty(Vs,"__esModule",{value:true});Vs.InfixOperator=void 0;var bl=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};Vs.InfixOperator=bl;});var Dl=P(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.Knot=void 0;var Qm=yt(),uh=Pn(),Al=class extends Qm.FlowBase{get flowLevel(){return uh.FlowLevel.Knot}constructor(e,t,n,r){super(e,t,n,r);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let r=t.ContentWithNameAtLevel(n,uh.FlowLevel.Knot,false);if(r){let a=this.subFlowsByName.get(n),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,a);}}}};ks.Knot=Al;});var ch=P(Ls=>{Object.defineProperty(Ls,"__esModule",{value:true});Ls.List=void 0;var Zm=Ye(),eC=Me(),tC=Me(),nC=fe(),xl=class extends Zm.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,r;let a=new eC.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let c=this.story.ResolveListItem(l,u,this);if(c===null)l===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}l||(l=((r=c.parent.identifier)===null||r===void 0?void 0:r.name)||null);let h=new tC.InkListItem(l,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new nC.ListValue(a));};}get typeName(){return "List"}};Ls.List=xl;});var wl=P(Bs=>{Object.defineProperty(Bs,"__esModule",{value:true});Bs.ListElementDefinition=void 0;var iC=he(),rC=wt(),_l=class extends iC.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,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,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,rC.SymbolType.ListItem);}};Bs.ListElementDefinition=_l;});var Ol=P(Ws=>{Object.defineProperty(Ws,"__esModule",{value:true});Ws.StatementLevel=void 0;var hh;(function(i){i[i.InnerBlock=0]="InnerBlock",i[i.Stitch=1]="Stitch",i[i.Knot=2]="Knot",i[i.Top=3]="Top";})(hh||(Ws.StatementLevel=hh={}));});var Pl=P(js=>{Object.defineProperty(js,"__esModule",{value:true});js.Stitch=void 0;var sC=yt(),aC=Pn(),Tl=class extends sC.FlowBase{get flowLevel(){return aC.FlowLevel.Stitch}constructor(e,t,n,r){super(e,t,n,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};js.Stitch=Tl;});var Ms=P(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.Tag=void 0;var oC=je(),Fl=class extends oC.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};qs.Tag=Fl;});var Il=P($s=>{Object.defineProperty($s,"__esModule",{value:true});$s.Choice=void 0;var lC=We(),uC=we(),cC=je(),Nl=class i extends cC.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, uC.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new lC.Path(e);}Clone(){let e=new i;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}};$s.Choice=Nl;});var Vl=P(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.ListDefinitionsOrigin=void 0;var hC=Me(),pC=fe(),fC=we(),Rl=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,r]of t.items){let a=hC.InkListItem.fromSerializedKey(n),s=new pC.ListValue(a,r);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 n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, fC.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Gs.ListDefinitionsOrigin=Rl;});var Ln=P(zs=>{Object.defineProperty(zs,"__esModule",{value:true});zs.JsonSerialisation=void 0;var Hs=Ce(),Ge=fe(),ph=Ns(),K=Oe(),kn=sn(),fh=Ct(),dh=xr(),kl=Rn(),gh=Wt(),Ll=mt(),mh=rn(),Ch=Ms(),dC=We(),yh=Il(),gC=sl(),mC=Vl(),Js=Me(),ye=ie(),un=we(),Us=class i{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let r=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, un.throwNullException)("runtimeObj");r.push(o);}return r}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,r),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WriteIntProperty(n,r);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, ye.asOrNull)(t,Hs.Container);if(n){this.WriteRuntimeContainer(e,n);return}let r=(0, ye.asOrNull)(t,fh.Divert);if(r){let C="->";r.isExternal?C="x()":r.pushesToStack&&(r.stackPushType==kn.PushPopType.Function?C="f()":r.stackPushType==kn.PushPopType.Tunnel&&(C="->t->"));let S;r.hasVariableTarget?S=r.variableDivertName:S=r.targetPathString,e.WriteObjectStart(),e.WriteProperty(C,S),r.hasVariableTarget&&e.WriteProperty("var",true),r.isConditional&&e.WriteProperty("c",true),r.externalArgs>0&&e.WriteIntProperty("exArgs",r.externalArgs),e.WriteObjectEnd();return}let a=(0, ye.asOrNull)(t,dh.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, ye.asOrNull)(t,Ge.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, ye.asOrNull)(t,Ge.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, ye.asOrNull)(t,Ge.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, ye.asOrNull)(t,Ge.StringValue);if(u){u.isNewline?e.Write(`
17
- `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let c=(0, ye.asOrNull)(t,Ge.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, ye.asOrNull)(t,Ge.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, un.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let f=(0, ye.asOrNull)(t,Ge.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, ye.asOrNull)(t,ph.Glue)){e.Write("<>");return}let g=(0, ye.asOrNull)(t,K.ControlCommand);if(g){e.Write(i._controlCommandNames[g.commandType]);return}let y=(0, ye.asOrNull)(t,Ll.NativeFunctionCall);if(y){let C=y.name;C=="^"&&(C="L^"),e.Write(C);return}let _=(0, ye.asOrNull)(t,kl.VariableReference);if(_){e.WriteObjectStart();let C=_.pathStringForCount;C!=null?e.WriteProperty("CNT?",C):e.WriteProperty("VAR?",_.name),e.WriteObjectEnd();return}let D=(0, ye.asOrNull)(t,gh.VariableAssignment);if(D){e.WriteObjectStart();let C=D.isGlobal?"VAR=":"temp=";e.WriteProperty(C,D.variableName),D.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, ye.asOrNull)(t,mh.Void)){e.Write("void");return}let p=(0, ye.asOrNull)(t,Ch.Tag);if(p){e.WriteObjectStart(),e.WriteProperty("#",p.text),e.WriteObjectEnd();return}let E=(0, ye.asOrNull)(t,yh.Choice);if(E){this.WriteChoice(e,E);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let r=this.JTokenToRuntimeObject(e[n]);if(r===null)return (0, un.throwNullException)("inkObject");t.set(n,r);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return Ge.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new Ge.FloatValue(parseFloat(n[0]));let r=t[0];if(r=="^")return new Ge.StringValue(t.substring(1));if(r==`
14
+ `.repeat(this.lineIndex-e):null};}PreProcessInputString(e){return e}};Br.CommentEliminator=_o;});var jr=T(Wr=>{Object.defineProperty(Wr,"__esModule",{value:true});Wr.Conditional=void 0;var Ud=ye(),Vc=Pe(),zd=pe(),wo=class extends zd.ParsedObject{constructor(e,t){super(),this.initialCondition=e,this.branches=t,this._reJoinTarget=null,this.GenerateRuntimeObject=()=>{let n=new Ud.Container;this.initialCondition&&n.AddContent(this.initialCondition.runtimeObject);for(let r of this.branches){let a=r.runtimeObject;n.AddContent(a);}return this.initialCondition!==null&&this.branches[0].ownExpression!==null&&!this.branches[this.branches.length-1].isElse&&n.AddContent(Vc.ControlCommand.PopEvaluatedValue()),this._reJoinTarget=Vc.ControlCommand.NoOp(),n.AddContent(this._reJoinTarget),n},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 n of this.branches){if(!n.returnDivert)throw new Error;n.returnDivert.targetPath=t;}super.ResolveReferences(e);}};Wr.Conditional=wo;});var qt=T(qr=>{Object.defineProperty(qr,"__esModule",{value:true});qr.Text=void 0;var Kd=pe(),Xd=de(),Oo=class extends Kd.ParsedObject{constructor(e){super(),this.text=e,this.GenerateRuntimeObject=()=>new Xd.StringValue(this.text),this.toString=()=>this.text;}get typeName(){return "Text"}};qr.Text=Oo;});var $r=T(Mr=>{Object.defineProperty(Mr,"__esModule",{value:true});Mr.ConstantDeclaration=void 0;var Yd=pe(),Qd=Ot(),To=class extends Yd.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,Qd.SymbolType.Var);}};Mr.ConstantDeclaration=To;});var Pn=T(Gr=>{Object.defineProperty(Gr,"__esModule",{value:true});Gr.FlowLevel=void 0;var kc;(function(i){i[i.Story=0]="Story",i[i.Knot=1]="Knot",i[i.Stitch=2]="Stitch",i[i.WeavePoint=3]="WeavePoint";})(kc||(Gr.FlowLevel=kc={}));});var gi=T(Hr=>{Object.defineProperty(Hr,"__esModule",{value:true});Hr.Gather=void 0;var Zd=ye(),eg=pe(),tg=Ot(),Po=class extends eg.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 n=new Zd.Container;if(n.name=this.name,this.story.countAllVisits&&(n.visitsShouldBeCounted=true),n.countingAtStartOnly=true,this.content)for(let r of this.content)n.AddContent(r.runtimeObject);return n},this.toString=()=>{var n,r;return `- ${!((n=this.identifier)===null||n===void 0)&&n.name?"("+((r=this.identifier)===null||r===void 0?void 0:r.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,tg.SymbolType.SubFlowAndWeave);}};Hr.Gather=Po;});var on=T(Ur=>{Object.defineProperty(Ur,"__esModule",{value:true});Ur.Path=void 0;var Jr=ne(),Lc=yt(),Fn=Pn(),ng=ln(),Fo=class{get baseTargetLevel(){return this.baseLevelIsAmbiguous?Fn.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(Jr.filterUndef).join(".")),this._dotSeparatedComponents}constructor(e,t){this._dotSeparatedComponents=null,this.toString=()=>this.components===null||this.components.length===0?this.baseTargetLevel===Fn.FlowLevel.WeavePoint?"-> <next gather point>":"<invalid Path>":`-> ${this.dotSeparatedComponents}`,this.ResolveFromContext=n=>{if(this.components==null||this.components.length==0)return null;let r=this.ResolveBaseTarget(n);return r===null?null:this.components.length>1?this.ResolveTailComponents(r):r},this.ResolveBaseTarget=n=>{let r=this.firstComponent,a=n;for(;a;){let s=a===n,o=this.GetChildFromContext(a,r,null,s);if(o)return o;a=a.parent;}return null},this.ResolveTailComponents=n=>{let r=n;if(!this.components)return null;for(let a=1;a<this.components.length;++a){let s=this.components[a].name,o,l=(0, Jr.asOrNull)(r,Lc.FlowBase);if(l!==null?o=l.flowLevel+1:o=Fn.FlowLevel.WeavePoint,r=this.GetChildFromContext(r,s,o),r===null)break}return r},this.GetChildFromContext=(n,r,a,s=false)=>{let o=a===null,l=(0, Jr.asOrNull)(n,ng.Weave);if(r&&l!==null&&(o||a===Fn.FlowLevel.WeavePoint))return l.WeavePointNamed(r);let u=(0, Jr.asOrNull)(n,Lc.FlowBase);if(r&&u!==null){let c=s||u.flowLevel===Fn.FlowLevel.Knot;return u.ContentWithNameAtLevel(r,a,c)}return null},Object.values(Fn.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"}};Ur.Path=Fo;});var Ro=T(zr=>{Object.defineProperty(zr,"__esModule",{value:true});zr.ReturnType=void 0;var ig=pe(),rg=ye(),No=Pe(),sg=rn(),Io=class extends ig.ParsedObject{constructor(e=null){super(),this.returnedExpression=null,this.GenerateRuntimeObject=()=>{let t=new rg.Container;return this.returnedExpression?t.AddContent(this.returnedExpression.runtimeObject):(t.AddContent(No.ControlCommand.EvalStart()),t.AddContent(new sg.Void),t.AddContent(No.ControlCommand.EvalEnd())),t.AddContent(No.ControlCommand.PopFunction()),t},e&&(this.returnedExpression=this.AddContent(e));}get typeName(){return "ReturnType"}};zr.ReturnType=Io;});var mi=T(Kr=>{Object.defineProperty(Kr,"__esModule",{value:true});Kr.ClosestFlowBase=void 0;function ag(i){let e=i.parent;for(;e;){if(e.hasOwnProperty("iamFlowbase")&&e.iamFlowbase())return e;e=e.parent;}return null}Kr.ClosestFlowBase=ag;});var Yr=T(Xr=>{Object.defineProperty(Xr,"__esModule",{value:true});Xr.Identifier=void 0;var Vo=class i{constructor(e){this.debugMetadata=null,this.toString=()=>this.name||"undefined identifer",this.name=e;}get typeName(){return "Identifier"}static Done(){return new i("DONE")}};Xr.Identifier=Vo;});var yt=T(Qr=>{Object.defineProperty(Qr,"__esModule",{value:true});Qr.FlowBase=void 0;var og=Tn(),ko=In(),lg=Nn(),vt=Pn(),ug=gi(),cg=pe(),hg=on(),pg=Ro(),fg=ye(),dg=Ct(),gg=Wt(),Lo=Ot(),mg=ln(),Cg=mi(),yg=Yr(),Bc=ne(),Bo=class i extends cg.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,n=null,r=false,a=false){super(),this.isFunction=r,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 l,u;let c=[],h=[];this._subFlowsByName=new Map;for(let d of s){let g=(0, Bc.asOrNull)(d,i);g?(this._firstChildFlow===null&&(this._firstChildFlow=g),h.push(d),!((l=g.identifier)===null||l===void 0)&&l.name&&this._subFlowsByName.set((u=g.identifier)===null||u===void 0?void 0:u.name,g)):c.push(d);}o&&c.push(new ug.Gather(null,1),new ko.Divert(new hg.Path(yg.Identifier.Done())));let f=[];return c.length>0&&(this._rootWeave=new mg.Weave(c,0),f.push(this._rootWeave)),h.length>0&&f.push(...h),f},this.ResolveVariableWithName=(s,o)=>{var l;let u={},c=o===null?this:(0, Cg.ClosestFlowBase)(o);if(c){if(c.args!==null){for(let h of c.args)if(((l=h.identifier)===null||l===void 0?void 0:l.name)===s)return u.found=true,u.isArgument=true,u.ownerFlow=c,u}if(c!==this.story&&c.variableDeclarations.has(s))return u.found=true,u.ownerFlow=c,u.isTemporary=true,u}return this.story.variableDeclarations.has(s)?(u.found=true,u.ownerFlow=this.story,u.isGlobal=true,u):(u.found=false,u)},this.AddNewVariableDeclaration=s=>{let o=s.variableName;if(this.variableDeclarations.has(o)){let l=this.variableDeclarations.get(o),u="";l.debugMetadata&&(u=` (${l.debugMetadata})`),this.Error(`found declaration variable '${o}' that was already declared${u}`,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===vt.FlowLevel.Knot||this.flowLevel===vt.FlowLevel.Stitch)&&(o=this.Find(pg.ReturnType)(),o!==null&&this.Error(`Return statements can only be used in knots that are declared as functions: == function ${this.identifier} ==`,o));let l=new fg.Container;l.name=(s=this.identifier)===null||s===void 0?void 0:s.name,this.story.countAllVisits&&(l.visitsShouldBeCounted=true),this.GenerateArgumentVariableAssignments(l);let u=0;for(;this.content!==null&&u<this.content.length;){let c=this.content[u];if(c instanceof i){let h=c,f=h.runtimeObject;u===0&&!h.hasParameters&&this.flowLevel===vt.FlowLevel.Knot&&(this._startingSubFlowDivert=new dg.Divert,l.AddContent(this._startingSubFlowDivert),this._startingSubFlowRuntime=f);let d=f,g=l.namedContent.get(d.name)||null;if(g){let y=`${this.GetType()} already contains flow named '${d.name}' (at ${g.debugMetadata})`;this.Error(y,h);}l.AddToNamedContentOnly(d);}else c&&l.AddContent(c.runtimeObject);u+=1;}return this.flowLevel!==vt.FlowLevel.Story&&!this.isFunction&&this._rootWeave!==null&&o===null&&this._rootWeave.ValidateTermination(this.WarningInTermination),l},this.GenerateArgumentVariableAssignments=s=>{var o;if(!(this.args===null||this.args.length===0))for(let l=this.args.length-1;l>=0;--l){let u=((o=this.args[l].identifier)===null||o===void 0?void 0:o.name)||null,c=new gg.VariableAssignment(u,true);s.AddContent(c);}},this.ContentWithNameAtLevel=(s,o=null,l=false)=>{var u;if((o===this.flowLevel||o===null)&&s===((u=this.identifier)===null||u===void 0?void 0:u.name))return this;if(o===vt.FlowLevel.WeavePoint||o===null){let h=null;if(this._rootWeave&&(h=this._rootWeave.WeavePointNamed(s),h))return h;if(o===vt.FlowLevel.WeavePoint)return l?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:l?this.DeepSearchForAnyLevelContent(s):null},this.DeepSearchForAnyLevelContent=s=>{let o=this.ContentWithNameAtLevel(s,vt.FlowLevel.WeavePoint,false);if(o)return o;for(let[,l]of this._subFlowsByName){let u=l.ContentWithNameAtLevel(s,null,true);if(u)return u}return null},this.CheckForDisallowedFunctionFlowControl=()=>{this.flowLevel!==vt.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[l,u]of this._subFlowsByName)this.Error(`Functions may not contain stitches, but saw '${l}' within the function '${this.identifier}'`,u);if(!this._rootWeave)throw new Error;let s=this._rootWeave.FindAll(ko.Divert)();for(let l of s)!l.isFunctionCall&&!(l.parent instanceof lg.DivertTarget)&&this.Error(`Functions may not contain diverts, but saw '${l}'`,l);let o=this._rootWeave.FindAll(og.Choice)();for(let l of o)this.Error(`Functions may not contain choices, but saw '${l}'`,l);},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 l=(0, Bc.asOrNull)(s,ko.Divert);l&&l.isTunnel&&(o+=` When final tunnel to '${l.target} ->' returns it won't have anywhere to go.`),this.Warning(o,s);},this.toString=()=>`${this.typeName} '${this.identifier}'`,this.identifier=e,this.args=n,t===null&&(t=[]),this.PreProcessTopLevelObjects(t),t=this.SplitWeaveAndSubFlowContent(t,this.GetType()=="Story"&&!a),this.AddContent(t);}PreProcessTopLevelObjects(e){}ResolveReferences(e){var t,n;if(this._startingSubFlowDivert){if(!this._startingSubFlowRuntime)throw new Error;this._startingSubFlowDivert.targetPath=this._startingSubFlowRuntime.path;}if(super.ResolveReferences(e),this.args!==null){for(let r of this.args)e.CheckForNamingCollisions(this,r.identifier,Lo.SymbolType.Arg,"argument");for(let r=0;r<this.args.length;r+=1)for(let a=r+1;a<this.args.length;a+=1)((t=this.args[r].identifier)===null||t===void 0?void 0:t.name)==((n=this.args[a].identifier)===null||n===void 0?void 0:n.name)&&this.Error(`Multiple arguments with the same name: '${this.args[r].identifier}'`);}if(this.flowLevel!==vt.FlowLevel.Story){let r=this.flowLevel===vt.FlowLevel.Knot?Lo.SymbolType.Knot:Lo.SymbolType.SubFlowAndWeave;e.CheckForNamingCollisions(this,this.identifier,r);}}};Qr.FlowBase=Bo;});var es=T(Zr=>{Object.defineProperty(Zr,"__esModule",{value:true});Zr.ContentList=void 0;var vg=ye(),Sg=pe(),Eg=qt(),bg=ne(),Wo=class extends Sg.ParsedObject{get runtimeContainer(){return this.runtimeObject}constructor(e,...t){super(),this.dontFlatten=false,this.TrimTrailingWhitespace=()=>{for(let n=this.content.length-1;n>=0;--n){let r=(0, bg.asOrNull)(this.content[n],Eg.Text);if(r===null)break;if(r.text=r.text.replace(new RegExp(/[ \t]/g),""),r.text.length===0)this.content.splice(n,1);else break}},this.GenerateRuntimeObject=()=>{let n=new vg.Container;if(this.content!==null)for(let r of this.content){let a=r.runtimeObject;a&&n.AddContent(a);}return this.dontFlatten&&this.story.DontFlattenContainer(n),n},this.toString=()=>`ContentList(${this.content.join(", ")})`,e&&this.AddContent(e),t&&this.AddContent(t);}get typeName(){return "ContentList"}};Zr.ContentList=Wo;});var Rn=T(ts=>{Object.defineProperty(ts,"__esModule",{value:true});ts.VariableReference=void 0;var Ag=je(),Dg=We(),jo=class extends Ag.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 Dg.Path(e);}constructor(e=null){super(),this.pathForCount=null,this.name=e;}toString(){return this.name!=null?"var("+this.name+")":"read_count("+this.pathStringForCount+")"}};ts.VariableReference=jo;});var Vn=T(ns=>{Object.defineProperty(ns,"__esModule",{value:true});ns.VariableReference=void 0;var xg=es(),_g=Ye(),Wc=yt(),wg=on(),Og=Rn(),Tg=ln(),Pg=Yr(),jc=ne(),qo=class extends _g.Expression{get name(){return this.path.join(".")}get path(){return this.pathIdentifiers.map(e=>e.name).filter(jc.filterUndef)}get identifier(){if(!this.pathIdentifiers||this.pathIdentifiers.length==0)return null;let e=this.path.join(".");return new Pg.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 n=this.story.constants.get(this.name);if(n){n.GenerateConstantIntoContainer(t),this.isConstantReference=true;return}if(this._runtimeVarRef=new Og.VariableReference(this.name),this.path.length===1||this.path.length===2){let r="",a="";this.path.length===1?r=this.path[0]:(a=this.path[0],r=this.path[1]),this.story.ResolveListItem(a,r,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 wg.Path(this.pathIdentifiers),n=t.ResolveFromContext(this);if(n){if(!n.containerForCounting)throw new Error;if(n.containerForCounting.visitsShouldBeCounted=true,this._runtimeVarRef===null)return;this._runtimeVarRef.pathForCount=n.runtimePath,this._runtimeVarRef.name=null;let r=(0, jc.asOrNull)(n,Wc.FlowBase);r&&r.isFunction&&(this.parent instanceof Tg.Weave||this.parent instanceof xg.ContentList||this.parent instanceof Wc.FlowBase)&&this.Warning(`'${r.identifier}' being used as read count rather than being called as function. Perhaps you intended to write ${r.identifier}()`);return}if(this.path.length>1){let r=`Could not find target for read count: ${t}`;this.path.length<=2&&(r+=`, or couldn't find list item with the name ${this.path.join(",")}`),this.Error(r);return}e.ResolveVariableWithName(this.name,this).found||this.Error(`Unresolved variable: ${this.name}`,this);}};ns.VariableReference=qo;});var Ci=T(as=>{Object.defineProperty(as,"__esModule",{value:true});as.FunctionCall=void 0;var St=Pe(),Fg=In(),Ng=Nn(),Ig=Ye(),Rg=Me(),Vg=de(),rs=mt(),qc=Sr(),kg=on(),Lg=de(),Bg=Vn(),is=ne(),ss=class i extends Ig.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=n=>{let r=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"),n.AddContent(St.ControlCommand.ChoiceCount());else if(this.isTurns)this.args.length>0&&this.Error("The TURNS() function shouldn't take any arguments"),n.AddContent(St.ControlCommand.Turns());else if(this.isTurnsSince||this.isReadCount){let s=(0, is.asOrNull)(this.args[0],Ng.DivertTarget),o=(0, is.asOrNull)(this.args[0],Bg.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(n)):o&&(this._variableReferenceToCount=o,this.AddContent(this._variableReferenceToCount),this._variableReferenceToCount.GenerateIntoContainer(n)),this.isTurnsSince?n.AddContent(St.ControlCommand.TurnsSince()):n.AddContent(St.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, is.asOrNull)(this.args[s],qc.NumberExpression);if(o&&!o.isInt()){let l=s===0?"minimum":"maximum";this.Error(`RANDOM's ${l} parameter should be an integer`);}this.args[s].GenerateIntoContainer(n);}n.AddContent(St.ControlCommand.Random());}else if(this.isSeedRandom){this.args.length!==1&&this.Error("SEED_RANDOM should take 1 parameter - an integer seed");let s=(0, is.asOrNull)(this.args[0],qc.NumberExpression);s&&!s.isInt()&&this.Error("SEED_RANDOM's parameter should be an integer seed"),this.args[0].GenerateIntoContainer(n),n.AddContent(St.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(n);n.AddContent(St.ControlCommand.ListRange());}else if(this.isListRandom)this.args.length!==1&&this.Error("LIST_RANDOM should take 1 parameter - a list"),this.args[0].GenerateIntoContainer(n),n.AddContent(St.ControlCommand.ListRandom());else if(rs.NativeFunctionCall.CallExistsWithName(this.name)){let s=rs.NativeFunctionCall.CallWithName(this.name);if(s.numberOfParameters!==this.args.length){let o=`${i.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(n);n.AddContent(rs.NativeFunctionCall.CallWithName(this.name));}else if(r!==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)n.AddContent(new Lg.StringValue(this.name)),this.args[0].GenerateIntoContainer(n),n.AddContent(St.ControlCommand.ListFromInt());else {let s=new Rg.InkList;s.SetInitialOriginName(this.name),n.AddContent(new Vg.ListValue(s));}else n.AddContent(this._proxyDivert.runtimeObject),a=true;a||this.content.splice(this.content.indexOf(this._proxyDivert),1),this.shouldPopReturnedValue&&n.AddContent(St.ControlCommand.PopEvaluatedValue());},this.toString=()=>{let n=this.args.join(", ");return `${this.name}(${n})`},this._proxyDivert=new Fg.Divert(new kg.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,n=t.runtimeDivert.variableDivertName!=null;if(n){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 r=t.targetContent;if(r===null)n||this.Error(`Failed to find target for TURNS_SINCE: '${t.target}'`);else {if(!r.containerForCounting)throw new Error;r.containerForCounting.turnIndexShouldBeCounted=true;}}else if(this._variableReferenceToCount){let t=this._variableReferenceToCount.runtimeVarRef;if(!t)throw new Error;t.pathForCount!==null&&this.Error(`Should be '${i.name}'(-> '${this._variableReferenceToCount.name}). Usage without the '->' only makes sense for variable targets.`);}}};as.FunctionCall=ss;ss.IsBuiltIn=i=>rs.NativeFunctionCall.CallExistsWithName(i)?true:i==="CHOICE_COUNT"||i==="TURNS_SINCE"||i==="TURNS"||i==="RANDOM"||i==="SEED_RANDOM"||i==="LIST_VALUE"||i==="LIST_RANDOM"||i==="READ_COUNT";});var $o=T(os=>{Object.defineProperty(os,"__esModule",{value:true});os.MultipleConditionExpression=void 0;var Wg=Ye(),jg=mt(),Mo=class extends Wg.Expression{get subExpressions(){return this.content}constructor(e){super(),this.GenerateIntoContainer=t=>{let n=true;for(let r of this.subExpressions)r.GenerateIntoContainer(t),n||t.AddContent(jg.NativeFunctionCall.CallWithName("&&")),n=false;},this.AddContent(e);}get typeName(){return "MultipleConditionExpression"}};os.MultipleConditionExpression=Mo;});var Nn=T(ls=>{Object.defineProperty(ls,"__esModule",{value:true});ls.DivertTarget=void 0;var qg=po(),Mg=Tn(),$g=jr(),Gg=Uo(),Hg=de(),Go=Ye(),Jg=yt(),Mc=Ci(),Ug=$o(),$c=Vn(),Ho=ne(),Jo=class i extends Go.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 Hg.DivertTargetValue,t.AddContent(this.runtimeDivertTargetValue);},this.Equals=t=>{let n=(0, Ho.asOrNull)(t,i);if(!n||!this.divert.target||!n.divert.target)return false;let r=this.divert.target.dotSeparatedComponents,a=n.divert.target.dotSeparatedComponents;return r===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 Go.Expression;){let r=false,a=false,s=t.parent;if(s instanceof qg.BinaryExpression){let o=s;o.opName!=="=="&&o.opName!=="!="?r=true:(o.leftExpression instanceof i||o.leftExpression instanceof $c.VariableReference)&&(o.rightExpression instanceof i||o.rightExpression instanceof $c.VariableReference)||(r=true),a=true;}else if(s instanceof Mc.FunctionCall){let o=s;!o.isTurnsSince&&!o.isReadCount&&(r=true),a=true;}else (s instanceof Go.Expression||s instanceof Ug.MultipleConditionExpression||s instanceof Mg.Choice&&s.condition===t||s instanceof $g.Conditional||s instanceof Gg.ConditionalSingleBranch)&&(r=true,a=true);if(r&&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 n=this.divert.targetContent;if(n!==null){let r=n.containerForCounting;if(r!==null){let s=(0, Ho.asOrNull)(this.parent,Mc.FunctionCall);s&&s.isTurnsSince||(r.visitsShouldBeCounted=true),r.turnIndexShouldBeCounted=true;}let a=(0, Ho.asOrNull)(n,Jg.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}').`);}}};ls.DivertTarget=Jo;});var In=T(us=>{Object.defineProperty(us,"__esModule",{value:true});us.Divert=void 0;var zg=ye(),yi=Pe(),Kg=Ct(),zo=Nn(),Ko=yt(),Xg=Ci(),Yg=pe(),Gc=on(),Qg=We(),Hc=sn(),Zg=de(),Jc=Vn(),em=mi(),vi=ne(),Xo=class extends Yg.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 yi.ControlCommand.End();if(this.isDone)return yi.ControlCommand.Done();this.runtimeDivert=new Kg.Divert,this.ResolveTargetContent(),this.CheckArgumentValidity();let n=this.args!==null&&this.args.length>0;if(n||this.isFunctionCall||this.isTunnel||this.isThread){let r=new zg.Container;if(n){this.isFunctionCall||r.AddContent(yi.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],l=null;if(a&&s<a.length&&(l=a[s]),l&&l.isByReference){let u=(0, vi.asOrNull)(o,Jc.VariableReference);if(!u){this.Error(`Expected variable name to pass by reference to 'ref ${l.identifier}' but saw ${o}`);break}let c=new Gc.Path(u.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 Zg.VariablePointerValue(u.name);r.AddContent(f);}else o.GenerateIntoContainer(r);}this.isFunctionCall||r.AddContent(yi.ControlCommand.EvalEnd());}return this.isThread?r.AddContent(yi.ControlCommand.StartThread()):(this.isFunctionCall||this.isTunnel)&&(this.runtimeDivert.pushesToStack=true,this.runtimeDivert.stackPushType=this.isFunctionCall?Hc.PushPopType.Function:Hc.PushPopType.Tunnel),r.AddContent(this.runtimeDivert),r}return this.runtimeDivert},this.PathAsVariableName=()=>this.target?this.target.firstComponent:null,this.ResolveTargetContent=()=>{if(!(this.isEmpty||this.isEnd)&&this.targetContent===null){let n=this.PathAsVariableName();if(n!==null){let r=(0, vi.asOrNull)((0, em.ClosestFlowBase)(this),Ko.FlowBase);if(r){let a=r.ResolveVariableWithName(n,this);if(a.found){if(a.isArgument&&a.ownerFlow&&a.ownerFlow.args){let s=a.ownerFlow.args.find(o=>{var l;return ((l=o.identifier)===null||l===void 0?void 0:l.name)==n});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=n;return}}}if(!this.target)throw new Error;this.targetContent=this.target.ResolveFromContext(this);}},this.CheckArgumentValidity=()=>{if(this.isEmpty)return;let n=0;if(this.args!==null&&this.args.length>0&&(n=this.args.length),this.targetContent===null)return;let r=(0, vi.asOrNull)(this.targetContent,Ko.FlowBase);if(n===0&&(r===null||!r.hasParameters))return;if(r===null&&n>0){this.Error("target needs to be a knot or stitch in order to pass arguments");return}else if(r!==null&&(r.args===null||!r.args&&n>0)){this.Error(`target (${r.name}) doesn't take parameters`);return}else if(this.parent instanceof zo.DivertTarget){n>0&&this.Error("can't store arguments in a divert target variable");return}let a=r.args.length;if(a!==n){let s;n===0?s="but there weren't any passed to it":n<a?s=`but only got ${n}`:s=`but got ${n}`,this.Error(`to '${r.identifier}' requires ${a} arguments, ${s}`);return}for(let s=0;s<a;++s){let o=r.args[s],l=this.args[s];if(o.isDivertTarget){let u=(0, vi.asOrNull)(l,Jc.VariableReference);if(!(l instanceof zo.DivertTarget)&&u===null)this.Error(`Target '${r.identifier}' expects a divert target for the parameter named -> ${o.identifier} but saw ${l}`,l);else if(u){let c=new Gc.Path(u.pathIdentifiers);c.ResolveFromContext(u)&&this.Error(`Passing read count of '${c.dotSeparatedComponents}' instead of a divert target. You probably meant '${c}'`);}}}if(r===null){this.Error("Can't call as a function or with arguments unless it's a knot or stitch");return}},this.CheckExternalArgumentValidity=n=>{let r=this.target?this.target.firstComponent:null,a=n.externals.get(r);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 '${r}'. Expected ${s} but got ${o}`);},this.toString=()=>{let n="";if(this.target!==null)n+=this.target.toString();else return "-> <empty divert>";return this.isTunnel&&(n+=" ->"),this.isFunctionCall&&(n+=" ()"),n},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, vi.asOrNull)(this.targetContent,Ko.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 zo.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 n=this.targetContent!==null,r=false,a=false;if(this.target){if(this.target.numberOfComponents===1){if(!this.target.firstComponent)throw new Error;if(r=Xg.FunctionCall.IsBuiltIn(this.target.firstComponent),a=e.IsExternal(this.target.firstComponent),r||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 Qg.Path(this.target.firstComponent),this.CheckExternalArgumentValidity(e));return}}}else throw new Error;this.runtimeDivert.variableDivertName==null&&!n&&!r&&!a&&this.Error(`target not found: '${this.target}'`);}Error(e,t=null,n=false){if(t!==this&&t){super.Error(e,t);return}this.isFunctionCall?super.Error(`Function call ${e}`,t,n):super.Error(`Divert ${e}`,t,n);}};us.Divert=Xo;});var Uc=T(cs=>{Object.defineProperty(cs,"__esModule",{value:true});cs.GatherPointToResolve=void 0;var Yo=class{constructor(e,t){this.divert=e,this.targetRuntimeObj=t;}};cs.GatherPointToResolve=Yo;});var zc=T(hs=>{Object.defineProperty(hs,"__esModule",{value:true});hs.SequenceDivertToResolve=void 0;var Qo=class{constructor(e,t){this.divert=e,this.targetContent=t;}};hs.SequenceDivertToResolve=Qo;});var Zo=T(ps=>{Object.defineProperty(ps,"__esModule",{value:true});ps.SequenceType=void 0;var Kc;(function(i){i[i.Stopping=1]="Stopping",i[i.Cycle=2]="Cycle",i[i.Shuffle=4]="Shuffle",i[i.Once=8]="Once";})(Kc||(ps.SequenceType=Kc={}));});var nl=T(gs=>{Object.defineProperty(gs,"__esModule",{value:true});gs.Sequence=void 0;var Xc=ye(),st=Pe(),el=Ct(),Si=de(),fs=mt(),tm=pe(),nm=zc(),ds=Zo(),im=ln(),tl=class extends tm.ParsedObject{constructor(e,t){super(),this.sequenceType=t,this._sequenceDivertsToResolve=[],this.GenerateRuntimeObject=()=>{let n=new Xc.Container;n.visitsShouldBeCounted=true,n.countingAtStartOnly=true,this._sequenceDivertsToResolve=[],n.AddContent(st.ControlCommand.EvalStart()),n.AddContent(st.ControlCommand.VisitIndex());let r=(this.sequenceType&ds.SequenceType.Once)>0,a=(this.sequenceType&ds.SequenceType.Cycle)>0,s=(this.sequenceType&ds.SequenceType.Stopping)>0,o=(this.sequenceType&ds.SequenceType.Shuffle)>0,l=this.sequenceElements.length;if(r&&(l+=1),s||r?(n.AddContent(new Si.IntValue(l-1)),n.AddContent(fs.NativeFunctionCall.CallWithName("MIN"))):a&&(n.AddContent(new Si.IntValue(this.sequenceElements.length)),n.AddContent(fs.NativeFunctionCall.CallWithName("%"))),o){let c=st.ControlCommand.NoOp();if(r||s){let f=s?this.sequenceElements.length-1:this.sequenceElements.length;n.AddContent(st.ControlCommand.Duplicate()),n.AddContent(new Si.IntValue(f)),n.AddContent(fs.NativeFunctionCall.CallWithName("=="));let d=new el.Divert;d.isConditional=true,n.AddContent(d),this.AddDivertToResolve(d,c);}let h=this.sequenceElements.length;s&&(h-=1),n.AddContent(new Si.IntValue(h)),n.AddContent(st.ControlCommand.SequenceShuffleIndex()),(r||s)&&n.AddContent(c);}n.AddContent(st.ControlCommand.EvalEnd());let u=st.ControlCommand.NoOp();for(let c=0;c<l;c+=1){n.AddContent(st.ControlCommand.EvalStart()),n.AddContent(st.ControlCommand.Duplicate()),n.AddContent(new Si.IntValue(c)),n.AddContent(fs.NativeFunctionCall.CallWithName("==")),n.AddContent(st.ControlCommand.EvalEnd());let h=new el.Divert;h.isConditional=true,n.AddContent(h);let f;c<this.sequenceElements.length?f=this.sequenceElements[c].runtimeObject:f=new Xc.Container,f.name=`s${c}`,f.InsertContent(st.ControlCommand.PopEvaluatedValue(),0);let d=new el.Divert;f.AddContent(d),n.AddToNamedContentOnly(f),this.AddDivertToResolve(h,f),this.AddDivertToResolve(d,u);}return n.AddContent(u),n},this.AddDivertToResolve=(n,r)=>{this._sequenceDivertsToResolve.push(new nm.SequenceDivertToResolve(n,r));},this.sequenceType=t,this.sequenceElements=[];for(let n of e){let r=n.content,a=null;r===null||r.length===0?a=n:a=new im.Weave(r),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;}};gs.Sequence=tl;});var rl=T(ms=>{Object.defineProperty(ms,"__esModule",{value:true});ms.TunnelOnwards=void 0;var rm=ye(),Ei=Pe(),sm=Ct(),am=de(),om=pe(),lm=rn(),um=ne(),cm=Rn(),il=class extends om.ParsedObject{constructor(){super(...arguments),this._overrideDivertTarget=null,this._divertAfter=null,this.GenerateRuntimeObject=()=>{let e=new rm.Container;if(e.AddContent(Ei.ControlCommand.EvalStart()),this.divertAfter){let t=this.divertAfter.GenerateRuntimeObject(),n=t;if(n){let a=this.divertAfter.args;if(a!==null&&a.length>0){let s=-1,o=-1;for(let l=0;l<n.content.length;l+=1){let u=n.content[l];u&&(s==-1&&u.commandType===Ei.ControlCommand.CommandType.EvalStart?s=l:u.commandType===Ei.ControlCommand.CommandType.EvalEnd&&(o=l));}for(let l=s+1;l<o;l+=1){let u=n.content[l];u.parent=null,e.AddContent(n.content[l]);}}}let r=(0, um.asOrNull)(t,sm.Divert);if(r!=null&&r.hasVariableTarget){let a=new cm.VariableReference(r.variableDivertName);e.AddContent(a);}else this._overrideDivertTarget=new am.DivertTargetValue,e.AddContent(this._overrideDivertTarget);}else e.AddContent(new lm.Void);return e.AddContent(Ei.ControlCommand.EvalEnd()),e.AddContent(Ei.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);}};ms.TunnelOnwards=il;});var ol=T(Cs=>{Object.defineProperty(Cs,"__esModule",{value:true});Cs.ListDefinition=void 0;var sl=Me(),al=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 n=new sl.InkListItem(this.name,e);this._items.set(n.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[n,r]of this._itemNameToValues)if(r==e)return t=new sl.InkListItem(this.name,n),{result:t,exists:true};return t=sl.InkListItem.Null,{result:t,exists:false}}TryGetValueForItem(e,t){if(!e.itemName)return {result:0,exists:false};let n=this._itemNameToValues.get(e.itemName);return n?{result:n,exists:true}:{result:0,exists:false}}};Cs.ListDefinition=al;});var vs=T(ys=>{Object.defineProperty(ys,"__esModule",{value:true});ys.ListDefinition=void 0;var hm=Me(),pm=Me(),fm=ol(),dm=de(),gm=pe(),mm=Ot(),ll=class extends gm.ParsedObject{get typeName(){return "ListDefinition"}get runtimeListDefinition(){var e;let t=new Map;for(let n of this.itemDefinitions)t.has(n.name)?this.Error(`List '${this.identifier}' contains duplicate items called '${n.name}'`):t.set(n.name,n.seriesValue);return new fm.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=n=>{if(this._elementsByName===null){this._elementsByName=new Map;for(let a of this.itemDefinitions)this._elementsByName.set(a.name,a);}return this._elementsByName.get(n)||null},this.GenerateRuntimeObject=()=>{var n,r;let a=new hm.InkList;for(let s of this.itemDefinitions)if(s.inInitialList){let o=new pm.InkListItem(((n=this.identifier)===null||n===void 0?void 0:n.name)||null,s.name||null);a.Add(o,s.seriesValue);}return a.SetInitialOriginName(((r=this.identifier)===null||r===void 0?void 0:r.name)||""),new dm.ListValue(a)};let t=1;for(let n of this.itemDefinitions)n.explicitValue!==null&&(t=n.explicitValue),n.seriesValue=t,t+=1;this.AddContent(e);}ResolveReferences(e){super.ResolveReferences(e),e.CheckForNamingCollisions(this,this.identifier,mm.SymbolType.List);}};ys.ListDefinition=ll;});var cl=T(Ss=>{Object.defineProperty(Ss,"__esModule",{value:true});Ss.VariableAssignment=void 0;var Cm=ye(),ym=mi(),vm=vs(),Sm=pe(),Yc=Ot(),Em=Wt(),bm=Vn(),Am=ne(),ul=class extends Sm.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:n,listDef:r,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, ym.ClosestFlowBase)(this)),s&&s.AddNewVariableDeclaration(this),this.isGlobalDeclaration)return null;let o=new Cm.Container;return this.expression?o.AddContent(this.expression.runtimeObject):this.listDefinition&&o.AddContent(this.listDefinition.runtimeObject),this._runtimeAssignment=new Em.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=!!n,r instanceof vm.ListDefinition?(this.listDefinition=this.AddContent(r),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?Yc.SymbolType.Var:Yc.SymbolType.Temp),this.isGlobalDeclaration){let t=(0, Am.asOrNull)(this.expression,bm.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);}}};Ss.VariableAssignment=ul;});var ln=T(As=>{Object.defineProperty(As,"__esModule",{value:true});As.Weave=void 0;var Qc=rr(),Ze=Tn(),Es=jr(),Dm=$r(),xm=ye(),bs=In(),_m=Ct(),wm=Nn(),Om=yt(),Et=gi(),Tm=Uc(),Pm=pe(),hl=nl(),Fm=qt(),Nm=rl(),Im=cl(),et=ne(),pl=class i extends Pm.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 n=this.content.length-1;n>=0;--n){e=this.content[n];let r=(0, et.asOrNull)(e,Fm.Text);if(!(r&&r.text===`
15
+ `)&&!this.IsGlobalDeclaration(e))break}let t=(0, et.asOrNull)(e,i);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 n,r,a;let s=[...this.FindAll(Et.Gather)(o=>!(o.name===null||o.name===void 0)),...this.FindAll(Ze.Choice)(o=>!(o.name===null||o.name===void 0))];this._namedWeavePoints=new Map;for(let o of s){let l=this.namedWeavePoints.get(((n=o.identifier)===null||n===void 0?void 0:n.name)||"");if(l){let u=l instanceof Et.Gather?"gather":"choice",c=l;this.Error(`A ${u} with the same label name '${o.name}' already exists in this context on line ${c.debugMetadata?c.debugMetadata.startLineNumber:"NO DEBUG METADATA AVAILABLE"}`,o);}!((r=o.identifier)===null||r===void 0)&&r.name&&this.namedWeavePoints.set((a=o.identifier)===null||a===void 0?void 0:a.name,o);}},this.ConstructWeaveHierarchyFromIndentation=()=>{let n=0;for(;n<this.content.length;){let r=this.content[n];if(r instanceof Ze.Choice||r instanceof Et.Gather){let s=r.indentationDepth-1;if(s>this.baseIndentIndex){let o=n;for(;n<this.content.length;){let h=(0, et.asOrNull)(this.content[n],Ze.Choice)||(0, et.asOrNull)(this.content[n],Et.Gather);if(h!==null&&h.indentationDepth-1<=this.baseIndentIndex)break;n+=1;}let l=n-o,u=this.content.slice(o,o+l);this.content.splice(o,l);let c=new i(u,s);this.InsertContent(o,c),n=o;}}n+=1;}},this.DetermineBaseIndentationFromContent=n=>{for(let r of n)if(r instanceof Ze.Choice||r instanceof Et.Gather)return r.indentationDepth-1;return 0},this.GenerateRuntimeObject=()=>{this._rootContainer=new xm.Container,this.currentContainer=this._rootContainer,this.looseEnds=[],this.gatherPointsToResolve=[];for(let n of this.content)if(n instanceof Ze.Choice||n instanceof Et.Gather)this.AddRuntimeForWeavePoint(n);else if(n instanceof i){let r=n;this.AddRuntimeForNestedWeave(r),this.gatherPointsToResolve.splice(0,0,...r.gatherPointsToResolve);}else this.AddGeneralRuntimeContent(n.runtimeObject);return this.PassLooseEndsToAncestors(),this._rootContainer},this.AddRuntimeForGather=n=>{let r=!this.hasSeenChoiceInSection;this.hasSeenChoiceInSection=false;let a=n.runtimeContainer;if(n.name||(a.name=`g-${this._unnamedGatherCount}`,this._unnamedGatherCount+=1),r){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 Et.Gather&&o.indentationDepth==n.indentationDepth)continue;let l=null;if(o instanceof bs.Divert)l=o.runtimeObject;else {l=new _m.Divert;let u=o;if(!u.runtimeContainer)throw new Error;u.runtimeContainer.AddContent(l);}this.gatherPointsToResolve.push(new Tm.GatherPointToResolve(l,a));}this.looseEnds=[],this.currentContainer=a;},this.AddRuntimeForWeavePoint=n=>{if(n instanceof Et.Gather)this.AddRuntimeForGather(n);else if(n instanceof Ze.Choice){if(!this.currentContainer)throw new Error;this.previousWeavePoint instanceof Et.Gather&&this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1);let r=n;if(this.currentContainer.AddContent(r.runtimeObject),!r.innerContentContainer)throw new Error;r.innerContentContainer.name=`c-${this._choiceCount}`,this.currentContainer.AddToNamedContentOnly(r.innerContentContainer),this._choiceCount+=1,this.hasSeenChoiceInSection=true;}this.addContentToPreviousWeavePoint=false,this.WeavePointHasLooseEnd(n)&&(this.looseEnds.push(n),(0, et.asOrNull)(n,Ze.Choice)&&(this.addContentToPreviousWeavePoint=true)),this.previousWeavePoint=n;},this.AddRuntimeForNestedWeave=n=>{this.AddGeneralRuntimeContent(n.rootContainer),this.previousWeavePoint!==null&&(this.looseEnds.splice(this.looseEnds.indexOf(this.previousWeavePoint),1),this.addContentToPreviousWeavePoint=false);},this.AddGeneralRuntimeContent=n=>{if(n!==null)if(this.addContentToPreviousWeavePoint){if(!this.previousWeavePoint||!this.previousWeavePoint.runtimeContainer)throw new Error;this.previousWeavePoint.runtimeContainer.AddContent(n);}else {if(!this.currentContainer)throw new Error;this.currentContainer.AddContent(n);}},this.PassLooseEndsToAncestors=()=>{if(this.looseEnds.length===0)return;let n=null,r=null,a=false;for(let s=this.parent;s!==null;s=s.parent){let o=(0, et.asOrNull)(s,i);o&&(!a&&n===null&&(n=o),a&&r===null&&(r=o)),(s instanceof hl.Sequence||s instanceof Es.Conditional)&&(a=true);}if(!(n===null&&r===null))for(let s=this.looseEnds.length-1;s>=0;s-=1){let o=this.looseEnds[s],l=false;if(a){if(o instanceof Ze.Choice&&n!==null)n.ReceiveLooseEnd(o),l=true;else if(!(o instanceof Ze.Choice)){let u=n||r;u!==null&&(u.ReceiveLooseEnd(o),l=true);}}else n?.hasOwnProperty("ReceiveLooseEnd")&&n.ReceiveLooseEnd(o),l=true;l&&this.looseEnds.splice(s,1);}},this.ReceiveLooseEnd=n=>{this.looseEnds.push(n);},this.WeavePointNamed=n=>{if(!this.namedWeavePoints)return null;let r=this.namedWeavePoints.get(n);return r||null},this.IsGlobalDeclaration=n=>{let r=(0, et.asOrNull)(n,Im.VariableAssignment);return !!(r&&r.isGlobalDeclaration&&r.isDeclaration||(0, et.asOrNull)(n,Dm.ConstantDeclaration))},this.ContentThatFollowsWeavePoint=n=>{let r=[],a=n;if(a.content!==null)for(let l of a.content)this.IsGlobalDeclaration(l)||r.push(l);let s=(0, et.asOrNull)(a.parent,i);if(s===null)throw new Error("Expected weave point parent to be weave?");let o=s.content.indexOf(a);for(let l=o+1;l<s.content.length;l+=1){let u=s.content[l];if(!this.IsGlobalDeclaration(u)){if(u instanceof Ze.Choice||u instanceof Et.Gather||u instanceof i)break;r.push(u);}}return r},this.ValidateTermination=n=>{if(this.lastParsedSignificantObject instanceof Qc.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,n);}else {for(let a of this.content)if(a instanceof Ze.Choice||a instanceof bs.Divert)return;this.ValidateFlowOfObjectsTerminates(this.content,this,n);}},this.BadNestedTerminationHandler=n=>{let r=null;for(let s=n.parent;s!==null;s=s.parent)if(s instanceof hl.Sequence||s instanceof Es.Conditional){r=(0, et.asOrNull)(s,Es.Conditional);break}let a="Choices nested in conditionals or sequences need to explicitly divert afterwards.";r!==null&&r.FindAll(Ze.Choice)().length===1&&(a=`Choices with conditions should be written: '* {condition} choice'. Otherwise, ${a.toLowerCase()}`),this.Error(a,n);},this.ValidateFlowOfObjectsTerminates=(n,r,a)=>{let s=false,o=r;for(let l of n){if(l.Find(bs.Divert)(c=>!c.isThread&&!c.isTunnel&&!c.isFunctionCall&&!(c.parent instanceof wm.DivertTarget))!==null&&(s=true),l.Find(Nm.TunnelOnwards)()!=null){s=true;break}o=l;}if(!s){if(o instanceof Qc.AuthorWarning)return;a(o);}},this.WeavePointHasLooseEnd=n=>{if(n.content===null)return true;for(let r=n.content.length-1;r>=0;--r){let a=(0, et.asOrNull)(n.content[r],bs.Divert);if(a&&!(a.isThread||a.isTunnel||a.isFunctionCall))return false}return true},this.CheckForWeavePointNamingCollisions=()=>{if(!this.namedWeavePoints)return;let n=[];for(let r of this.ancestry){let a=(0, et.asOrNull)(r,Om.FlowBase);if(a)n.push(a);else break}for(let[r,a]of this.namedWeavePoints)for(let s of n){let o=s.ContentWithNameAtLevel(r);if(o&&o!==a){let l=`${a.GetType()} '${r}' has the same label name as a ${o.GetType()} (on ${o.debugMetadata})`;this.Error(l,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 n=this.parent;n!==null;n=n.parent)if(n instanceof hl.Sequence||n instanceof Es.Conditional){t=true;break}t&&this.ValidateTermination(this.BadNestedTerminationHandler);}for(let t of this.gatherPointsToResolve)t.divert.targetPath=t.targetRuntimeObj.path;this.CheckForWeavePointNamingCollisions();}};As.Weave=pl;});var Uo=T(xs=>{Object.defineProperty(xs,"__esModule",{value:true});xs.ConditionalSingleBranch=void 0;var Zc=ye(),Ds=Pe(),eh=Ct(),Rm=pe(),Vm=mt(),km=de(),Lm=qt(),Bm=ln(),Wm=ne(),fl=class extends Rm.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 r of this._innerWeave.content){let a=(0, Wm.asOrNull)(r,Lm.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 Zc.Container,n=this.matchingEquality&&!this.isElse;if(n&&t.AddContent(Ds.ControlCommand.Duplicate()),this._conditionalDivert=new eh.Divert,this._conditionalDivert.isConditional=!this.isElse,!this.isTrueBranch&&!this.isElse){let r=this.ownExpression!==null;r&&t.AddContent(Ds.ControlCommand.EvalStart()),this.ownExpression&&this.ownExpression.GenerateIntoContainer(t),this.matchingEquality&&t.AddContent(Vm.NativeFunctionCall.CallWithName("==")),r&&t.AddContent(Ds.ControlCommand.EvalEnd());}return t.AddContent(this._conditionalDivert),this._contentContainer=this.GenerateRuntimeForContent(),this._contentContainer.name="b",this.isInline||this._contentContainer.InsertContent(new km.StringValue(`
16
+ `),0),(n||this.isElse&&this.matchingEquality)&&this._contentContainer.InsertContent(Ds.ControlCommand.PopEvaluatedValue(),0),t.AddToNamedContentOnly(this._contentContainer),this.returnDivert=new eh.Divert,this._contentContainer.AddContent(this.returnDivert),t},this.GenerateRuntimeForContent=()=>this._innerWeave===null?new Zc.Container:this._innerWeave.rootContainer,e&&(this._innerWeave=new Bm.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);}};xs.ConditionalSingleBranch=fl;});var nh=T(_s=>{Object.defineProperty(_s,"__esModule",{value:true});_s.CustomFlags=void 0;var th;(function(i){i[i.ParsingString=1]="ParsingString",i[i.TagActive=2]="TagActive";})(th||(_s.CustomFlags=th={}));});var ih=T(ws=>{Object.defineProperty(ws,"__esModule",{value:true});ws.DebugMetadata=void 0;var dl=class i{constructor(){this.startLineNumber=0,this.endLineNumber=0,this.startCharacterNumber=0,this.endCharacterNumber=0,this.fileName=null,this.sourceName=null;}Merge(e){let t=new i;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}};ws.DebugMetadata=dl;});var rh=T(Os=>{Object.defineProperty(Os,"__esModule",{value:true});Os.ExternalDeclaration=void 0;var jm=pe(),gl=class extends jm.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}`}};Os.ExternalDeclaration=gl;});var sh=T(Ts=>{Object.defineProperty(Ts,"__esModule",{value:true});Ts.FlowDecl=void 0;var ml=class{constructor(e,t,n){this.name=e,this.args=t,this.isFunction=n;}};Ts.FlowDecl=ml;});var yl=T(Ps=>{Object.defineProperty(Ps,"__esModule",{value:true});Ps.Wrap=void 0;var qm=pe(),Cl=class extends qm.ParsedObject{constructor(e){super(),this._objToWrap=e,this.GenerateRuntimeObject=()=>this._objToWrap;}};Ps.Wrap=Cl;});var ah=T(Fs=>{Object.defineProperty(Fs,"__esModule",{value:true});Fs.Glue=void 0;var Mm=yl(),vl=class extends Mm.Wrap{constructor(e){super(e);}get typeName(){return "Glue"}};Fs.Glue=vl;});var Is=T(Ns=>{Object.defineProperty(Ns,"__esModule",{value:true});Ns.Glue=void 0;var $m=je(),Sl=class extends $m.InkObject{toString(){return "Glue"}};Ns.Glue=Sl;});var lh=T(Rs=>{Object.defineProperty(Rs,"__esModule",{value:true});Rs.IncDecExpression=void 0;var Gm=es(),oh=Ye(),Hm=yt(),Jm=mt(),Um=de(),zm=Wt(),Km=Rn(),Xm=ln(),El=class extends oh.Expression{constructor(e,t,n){super(),this.varIdentifier=e,this._runtimeAssignment=null,this.expression=null,this.GenerateIntoContainer=r=>{var a,s;r.AddContent(new Km.VariableReference(((a=this.varIdentifier)===null||a===void 0?void 0:a.name)||null)),this.expression?this.expression.GenerateIntoContainer(r):r.AddContent(new Um.IntValue(1)),r.AddContent(Jm.NativeFunctionCall.CallWithName(this.isInc?"+":"-")),this._runtimeAssignment=new zm.VariableAssignment(((s=this.varIdentifier)===null||s===void 0?void 0:s.name)||null,false),r.AddContent(this._runtimeAssignment);},this.toString=()=>{var r,a;return this.expression?`${(r=this.varIdentifier)===null||r===void 0?void 0:r.name}${this.isInc?" += ":" -= "}${this.expression}`:`${(a=this.varIdentifier)===null||a===void 0?void 0:a.name}`+(this.isInc?"++":"--")},t instanceof oh.Expression?(this.expression=t,this.AddContent(this.expression),this.isInc=!!n):this.isInc=t;}get typeName(){return "IncDecExpression"}ResolveReferences(e){var t;super.ResolveReferences(e);let n=e.ResolveVariableWithName(((t=this.varIdentifier)===null||t===void 0?void 0:t.name)||"",this);if(n.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=n.isGlobal,!(this.parent instanceof Xm.Weave)&&!(this.parent instanceof Hm.FlowBase)&&!(this.parent instanceof Gm.ContentList)&&this.Error(`Can't use ${this.incrementDecrementWord} as sub-expression`);}get incrementDecrementWord(){return this.isInc?"increment":"decrement"}};Rs.IncDecExpression=El;});var Al=T(Vs=>{Object.defineProperty(Vs,"__esModule",{value:true});Vs.IncludedFile=void 0;var Ym=pe(),bl=class extends Ym.ParsedObject{constructor(e){super(),this.includedStory=e,this.GenerateRuntimeObject=()=>null;}get typeName(){return "IncludedFile"}};Vs.IncludedFile=bl;});var uh=T(ks=>{Object.defineProperty(ks,"__esModule",{value:true});ks.InfixOperator=void 0;var Dl=class{constructor(e,t,n){this.type=e,this.precedence=t,this.requireWhitespace=n,this.toString=()=>this.type;}};ks.InfixOperator=Dl;});var _l=T(Ls=>{Object.defineProperty(Ls,"__esModule",{value:true});Ls.Knot=void 0;var Qm=yt(),ch=Pn(),xl=class extends Qm.FlowBase{get flowLevel(){return ch.FlowLevel.Knot}constructor(e,t,n,r){super(e,t,n,r);}get typeName(){return this.isFunction?"Function":"Knot"}ResolveReferences(e){super.ResolveReferences(e);let t=this.story;for(let n in this.subFlowsByName){let r=t.ContentWithNameAtLevel(n,ch.FlowLevel.Knot,false);if(r){let a=this.subFlowsByName.get(n),s=`Stitch '${a?a.name:"NO STITCH FOUND"}' has the same name as a knot (on ${r.debugMetadata})`;this.Error(s,a);}}}};Ls.Knot=xl;});var hh=T(Bs=>{Object.defineProperty(Bs,"__esModule",{value:true});Bs.List=void 0;var Zm=Ye(),eC=Me(),tC=Me(),nC=de(),wl=class extends Zm.Expression{constructor(e){super(),this.itemIdentifierList=e,this.GenerateIntoContainer=t=>{var n,r;let a=new eC.InkList;if(this.itemIdentifierList!=null)for(let s of this.itemIdentifierList){let o=((n=s?.name)===null||n===void 0?void 0:n.split("."))||[],l=null,u="";o.length>1?(l=o[0],u=o[1]):u=o[0];let c=this.story.ResolveListItem(l,u,this);if(c===null)l===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}l||(l=((r=c.parent.identifier)===null||r===void 0?void 0:r.name)||null);let h=new tC.InkListItem(l,c.name||null);a.has(h.serialized())?this.Warning(`Duplicate of item '${s}' in list.`):a.Add(h,c.seriesValue);}}t.AddContent(new nC.ListValue(a));};}get typeName(){return "List"}};Bs.List=wl;});var Tl=T(Ws=>{Object.defineProperty(Ws,"__esModule",{value:true});Ws.ListElementDefinition=void 0;var iC=pe(),rC=Ot(),Ol=class extends iC.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,n=null){super(),this.indentifier=e,this.inInitialList=t,this.explicitValue=n,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,rC.SymbolType.ListItem);}};Ws.ListElementDefinition=Ol;});var Pl=T(js=>{Object.defineProperty(js,"__esModule",{value:true});js.StatementLevel=void 0;var ph;(function(i){i[i.InnerBlock=0]="InnerBlock",i[i.Stitch=1]="Stitch",i[i.Knot=2]="Knot",i[i.Top=3]="Top";})(ph||(js.StatementLevel=ph={}));});var Nl=T(qs=>{Object.defineProperty(qs,"__esModule",{value:true});qs.Stitch=void 0;var sC=yt(),aC=Pn(),Fl=class extends sC.FlowBase{get flowLevel(){return aC.FlowLevel.Stitch}constructor(e,t,n,r){super(e,t,n,r),this.baseToString=this.toString,this.toString=()=>`${this.parent!==null?this.parent+" > ":""}${this.baseToString()}`;}get typeName(){return "Stitch"}};qs.Stitch=Fl;});var $s=T(Ms=>{Object.defineProperty(Ms,"__esModule",{value:true});Ms.Tag=void 0;var oC=je(),Il=class extends oC.InkObject{constructor(e){super(),this.text=e.toString()||"";}toString(){return "# "+this.text}};Ms.Tag=Il;});var Vl=T(Gs=>{Object.defineProperty(Gs,"__esModule",{value:true});Gs.Choice=void 0;var lC=We(),uC=Te(),cC=je(),Rl=class i extends cC.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, uC.throwNullException)("Choice.targetPath"):this.targetPath.toString()}set pathStringOnChoice(e){this.targetPath=new lC.Path(e);}Clone(){let e=new i;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}};Gs.Choice=Rl;});var Ll=T(Hs=>{Object.defineProperty(Hs,"__esModule",{value:true});Hs.ListDefinitionsOrigin=void 0;var hC=Me(),pC=de(),fC=Te(),kl=class{constructor(e){this._lists=new Map,this._allUnambiguousListValueCache=new Map;for(let t of e){this._lists.set(t.name,t);for(let[n,r]of t.items){let a=hC.InkListItem.fromSerializedKey(n),s=new pC.ListValue(a,r);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 n=this._lists.get(e);return n?{result:n,exists:true}:{result:t,exists:false}}FindSingleItemListWithName(e){if(e===null)return (0, fC.throwNullException)("name");let t=this._allUnambiguousListValueCache.get(e);return typeof t<"u"?t:null}};Hs.ListDefinitionsOrigin=kl;});var Ln=T(Ks=>{Object.defineProperty(Ks,"__esModule",{value:true});Ks.JsonSerialisation=void 0;var Js=ye(),Ge=de(),fh=Is(),Y=Pe(),kn=sn(),dh=Ct(),gh=_r(),Bl=Rn(),mh=Wt(),Wl=mt(),Ch=rn(),yh=$s(),dC=We(),vh=Vl(),gC=ol(),mC=Ll(),Us=Me(),ve=ne(),un=Te(),zs=class i{static JArrayToRuntimeObjList(e,t=false){let n=e.length;t&&n--;let r=[];for(let a=0;a<n;a++){let s=e[a],o=this.JTokenToRuntimeObject(s);if(o===null)return (0, un.throwNullException)("runtimeObj");r.push(o);}return r}static WriteDictionaryRuntimeObjs(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WritePropertyStart(n),this.WriteRuntimeObject(e,r),e.WritePropertyEnd();e.WriteObjectEnd();}static WriteListRuntimeObjs(e,t){e.WriteArrayStart();for(let n of t)this.WriteRuntimeObject(e,n);e.WriteArrayEnd();}static WriteIntDictionary(e,t){e.WriteObjectStart();for(let[n,r]of t)e.WriteIntProperty(n,r);e.WriteObjectEnd();}static WriteRuntimeObject(e,t){let n=(0, ve.asOrNull)(t,Js.Container);if(n){this.WriteRuntimeContainer(e,n);return}let r=(0, ve.asOrNull)(t,dh.Divert);if(r){let C="->";r.isExternal?C="x()":r.pushesToStack&&(r.stackPushType==kn.PushPopType.Function?C="f()":r.stackPushType==kn.PushPopType.Tunnel&&(C="->t->"));let S;r.hasVariableTarget?S=r.variableDivertName:S=r.targetPathString,e.WriteObjectStart(),e.WriteProperty(C,S),r.hasVariableTarget&&e.WriteProperty("var",true),r.isConditional&&e.WriteProperty("c",true),r.externalArgs>0&&e.WriteIntProperty("exArgs",r.externalArgs),e.WriteObjectEnd();return}let a=(0, ve.asOrNull)(t,gh.ChoicePoint);if(a){e.WriteObjectStart(),e.WriteProperty("*",a.pathStringOnChoice),e.WriteIntProperty("flg",a.flags),e.WriteObjectEnd();return}let s=(0, ve.asOrNull)(t,Ge.BoolValue);if(s){e.WriteBool(s.value);return}let o=(0, ve.asOrNull)(t,Ge.IntValue);if(o){e.WriteInt(o.value);return}let l=(0, ve.asOrNull)(t,Ge.FloatValue);if(l){e.WriteFloat(l.value);return}let u=(0, ve.asOrNull)(t,Ge.StringValue);if(u){u.isNewline?e.Write(`
17
+ `,false):(e.WriteStringStart(),e.WriteStringInner("^"),e.WriteStringInner(u.value),e.WriteStringEnd());return}let c=(0, ve.asOrNull)(t,Ge.ListValue);if(c){this.WriteInkList(e,c);return}let h=(0, ve.asOrNull)(t,Ge.DivertTargetValue);if(h){if(e.WriteObjectStart(),h.value===null)return (0, un.throwNullException)("divTargetVal.value");e.WriteProperty("^->",h.value.componentsString),e.WriteObjectEnd();return}let f=(0, ve.asOrNull)(t,Ge.VariablePointerValue);if(f){e.WriteObjectStart(),e.WriteProperty("^var",f.value),e.WriteIntProperty("ci",f.contextIndex),e.WriteObjectEnd();return}if((0, ve.asOrNull)(t,fh.Glue)){e.Write("<>");return}let g=(0, ve.asOrNull)(t,Y.ControlCommand);if(g){e.Write(i._controlCommandNames[g.commandType]);return}let y=(0, ve.asOrNull)(t,Wl.NativeFunctionCall);if(y){let C=y.name;C=="^"&&(C="L^"),e.Write(C);return}let _=(0, ve.asOrNull)(t,Bl.VariableReference);if(_){e.WriteObjectStart();let C=_.pathStringForCount;C!=null?e.WriteProperty("CNT?",C):e.WriteProperty("VAR?",_.name),e.WriteObjectEnd();return}let D=(0, ve.asOrNull)(t,mh.VariableAssignment);if(D){e.WriteObjectStart();let C=D.isGlobal?"VAR=":"temp=";e.WriteProperty(C,D.variableName),D.isNewDeclaration||e.WriteProperty("re",true),e.WriteObjectEnd();return}if((0, ve.asOrNull)(t,Ch.Void)){e.Write("void");return}let p=(0, ve.asOrNull)(t,yh.Tag);if(p){e.WriteObjectStart(),e.WriteProperty("#",p.text),e.WriteObjectEnd();return}let E=(0, ve.asOrNull)(t,vh.Choice);if(E){this.WriteChoice(e,E);return}throw new Error("Failed to convert runtime object to Json token: "+t)}static JObjectToDictionaryRuntimeObjs(e){let t=new Map;for(let n in e)if(e.hasOwnProperty(n)){let r=this.JTokenToRuntimeObject(e[n]);if(r===null)return (0, un.throwNullException)("inkObject");t.set(n,r);}return t}static JObjectToIntDictionary(e){let t=new Map;for(let n in e)e.hasOwnProperty(n)&&t.set(n,parseInt(e[n]));return t}static JTokenToRuntimeObject(e){if(typeof e=="number"&&!isNaN(e)||typeof e=="boolean")return Ge.Value.Create(e);if(typeof e=="string"){let t=e.toString(),n=/^([0-9]+.[0-9]+f)$/.exec(t);if(n)return new Ge.FloatValue(parseFloat(n[0]));let r=t[0];if(r=="^")return new Ge.StringValue(t.substring(1));if(r==`
18
18
  `&&t.length==1)return new Ge.StringValue(`
19
- `);if(t=="<>")return new ph.Glue;for(let a=0;a<i._controlCommandNames.length;++a){let s=i._controlCommandNames[a];if(t==s)return new K.ControlCommand(a)}if(t=="L^"&&(t="^"),Ll.NativeFunctionCall.CallExistsWithName(t))return Ll.NativeFunctionCall.CallWithName(t);if(t=="->->")return K.ControlCommand.PopTunnel();if(t=="~ret")return K.ControlCommand.PopFunction();if(t=="void")return new mh.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new Ge.DivertTargetValue(new dC.Path(n.toString()));if(t["^var"]){n=t["^var"];let c=new Ge.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,c.contextIndex=parseInt(n)),c}let r=false,a=false,s=kn.PushPopType.Function,o=false;if((n=t["->"])?r=true:(n=t["f()"])?(r=true,a=true,s=kn.PushPopType.Function):(n=t["->t->"])?(r=true,a=true,s=kn.PushPopType.Tunnel):(n=t["x()"])&&(r=true,o=true,a=false,s=kn.PushPopType.Function),r){let c=new fh.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=n.toString();return (n=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(n=t.exArgs)&&(c.externalArgs=parseInt(n)),c}if(n=t["*"]){let c=new dh.ChoicePoint;return c.pathStringOnChoice=n.toString(),(n=t.flg)&&(c.flags=parseInt(n)),c}if(n=t["VAR?"])return new kl.VariableReference(n.toString());if(n=t["CNT?"]){let c=new kl.VariableReference;return c.pathStringForCount=n.toString(),c}let l=false,u=false;if((n=t["VAR="])?(l=true,u=true):(n=t["temp="])&&(l=true,u=false),l){let c=n.toString(),h=!t.re,f=new gh.VariableAssignment(c,h);return f.isGlobal=u,f}if(t["#"]!==void 0)return n=t["#"],new Ch.Tag(n.toString());if(n=t.list){let c=n,h=new Js.InkList;if(n=t.origins){let f=n;h.SetInitialOriginNames(f);}for(let f in c)if(c.hasOwnProperty(f)){let d=c[f],g=new Js.InkListItem(f),y=parseInt(d);h.Add(g,y);}return new Ge.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,n){return JSON.stringify(e,(r,a)=>t?.some(s=>s===r)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, un.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let r=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=r!=null||a>0||s;if(o&&e.WriteObjectStart(),r!=null)for(let[l,u]of r){let c=l,h=(0, ye.asOrNull)(u,Hs.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 Hs.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let r=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, ye.asOrNull)(s,Hs.Container);o&&(o.name=a),r.set(a,s);}t.namedOnlyContent=r;}return t}static JObjectToChoice(e){let t=new yh.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 n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, un.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[r,a]of n){let s=Js.InkListItem.fromSerializedKey(r),o=a;if(s.itemName===null)return (0, un.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(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let r of n.originNames)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let r={};for(let[a,s]of n.items){let o=Js.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, un.throwNullException)("item.itemName");r[o.itemName]=s;}t[n.name]=r;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let r in t)if(t.hasOwnProperty(r)){let a=r.toString(),s=t[r],o=new Map;for(let u in s)if(t.hasOwnProperty(r)){let c=s[u];o.set(u,parseInt(c));}let l=new gC.ListDefinition(a,o);n.push(l);}return new mC.ListDefinitionsOrigin(n)}};zs.JsonSerialisation=Us;Us._controlCommandNames=(()=>{let i=[];i[K.ControlCommand.CommandType.EvalStart]="ev",i[K.ControlCommand.CommandType.EvalOutput]="out",i[K.ControlCommand.CommandType.EvalEnd]="/ev",i[K.ControlCommand.CommandType.Duplicate]="du",i[K.ControlCommand.CommandType.PopEvaluatedValue]="pop",i[K.ControlCommand.CommandType.PopFunction]="~ret",i[K.ControlCommand.CommandType.PopTunnel]="->->",i[K.ControlCommand.CommandType.BeginString]="str",i[K.ControlCommand.CommandType.EndString]="/str",i[K.ControlCommand.CommandType.NoOp]="nop",i[K.ControlCommand.CommandType.ChoiceCount]="choiceCnt",i[K.ControlCommand.CommandType.Turns]="turn",i[K.ControlCommand.CommandType.TurnsSince]="turns",i[K.ControlCommand.CommandType.ReadCount]="readc",i[K.ControlCommand.CommandType.Random]="rnd",i[K.ControlCommand.CommandType.SeedRandom]="srnd",i[K.ControlCommand.CommandType.VisitIndex]="visit",i[K.ControlCommand.CommandType.SequenceShuffleIndex]="seq",i[K.ControlCommand.CommandType.StartThread]="thread",i[K.ControlCommand.CommandType.Done]="done",i[K.ControlCommand.CommandType.End]="end",i[K.ControlCommand.CommandType.ListFromInt]="listInt",i[K.ControlCommand.CommandType.ListRange]="range",i[K.ControlCommand.CommandType.ListRandom]="lrnd",i[K.ControlCommand.CommandType.BeginTag]="#",i[K.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<K.ControlCommand.CommandType.TOTAL_VALUES;++e)if(i[e]==null)throw new Error("Control command not accounted for in serialisation");return i})();});var jl=P(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.CallStack=void 0;var Bl=sn(),vh=We(),CC=xi(),Sh=Ln(),yC=fe(),vC=tn(),bi=fi(),SC=ei(),Eh=xn(),Wl=we(),Ai=class i{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){SC.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=bi.Pointer.Null,arguments[0]instanceof CC.Story){let e=arguments[0];this._startOfRoot=bi.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 i.Thread),this._threads[0].callstack.push(new i.Element(Bl.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let r of n){let a=r,s=new i.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=bi.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.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==Bl.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let r=new i.Element(e,this.currentElement.currentPointer,false);r.evaluationStackHeightWhenPushed=t,r.functionStartInOutputStream=n,this.callStack.push(r);}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 n=this.callStack[t-1],r=(0, Eh.tryGetValueFromMap)(n.temporaryVariables,e,null);return r.exists?r.result:null}SetTemporaryVariable(e,t,n,r=-1){r==-1&&(r=this.currentElementIndex+1);let a=this.callStack[r-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, Eh.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&yC.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(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new vC.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],r=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
- `,t+1,this._threads.length,r?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==Bl.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, Wl.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Di.CallStack=Ai;(function(i){class e{constructor(r,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=r;}Copy(){let r=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return r.temporaryVariables=new Map(this.temporaryVariables),r.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,r.functionStartInOutputStream=this.functionStartInOutputStream,r}}i.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=bi.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let r=arguments[0],a=arguments[1];this.threadIndex=parseInt(r.threadIndex);let s=r.callstack;for(let l of s){let u=l,c=parseInt(u.type),h=bi.Pointer.Null,f,d=u.cPath;if(typeof d<"u"){f=d.toString();let D=a.ContentAtPath(new vh.Path(f));if(h.container=D.container,h.index=parseInt(u.idx),D.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?");D.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!u.exp,y=new e(c,h,g),_=u.temp;typeof _<"u"?y.temporaryVariables=Sh.JsonSerialisation.JObjectToDictionaryRuntimeObjs(_):y.temporaryVariables.clear(),this.callstack.push(y);}let o=r.previousContentObject;if(typeof o<"u"){let l=new vh.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let r=new t;r.threadIndex=this.threadIndex;for(let a of this.callstack)r.callstack.push(a.Copy());return r.previousPointer=this.previousPointer.copy(),r}WriteJson(r){r.WriteObjectStart(),r.WritePropertyStart("callstack"),r.WriteArrayStart();for(let a of this.callstack){if(r.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, Wl.throwNullException)("el.currentPointer.container");r.WriteProperty("cPath",a.currentPointer.container.path.componentsString),r.WriteIntProperty("idx",a.currentPointer.index);}r.WriteProperty("exp",a.inExpressionEvaluation),r.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(r.WritePropertyStart("temp"),Sh.JsonSerialisation.WriteDictionaryRuntimeObjs(r,a.temporaryVariables),r.WritePropertyEnd()),r.WriteObjectEnd();}if(r.WriteArrayEnd(),r.WritePropertyEnd(),r.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, Wl.throwNullException)("this.previousPointer.Resolve()");r.WriteProperty("previousContentObject",a.path.toString());}r.WriteObjectEnd();}}i.Thread=t;})(Ai||(Di.CallStack=Ai={}));});var Ah=P(Xs=>{Object.defineProperty(Xs,"__esModule",{value:true});Xs.VariablesState=void 0;var _e=fe(),EC=ni(),bh=Ln(),Te=ie(),_i=xn(),Mt=we();function bC(){return class{}}var Ks=class i extends bC(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(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 n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new EC.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=_e.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}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(r,a){return a in r?r[a]:r.$(a)},set(r,a,s){return a in r?r[a]=s:r.$(a,s),!0},ownKeys(r){return [...new Set([...r._defaultGlobalVariables.keys(),...r._globalVariables.keys()])]},getOwnPropertyDescriptor(r,a){return {enumerable:!0,configurable:!0,value:r.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Mt.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,n]of this._defaultGlobalVariables){let r=e[t];if(typeof r<"u"){let a=bh.JsonSerialisation.JTokenToRuntimeObject(r);if(a===null)return (0, Mt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let r=t,a=n;if(i.dontSaveDefaultValues&&this._defaultGlobalVariables.has(r)){let s=this._defaultGlobalVariables.get(r);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(r),bh.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Mt.throwNullException)("obj1");if(t===null)return (0, Mt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, Te.asOrNull)(e,_e.BoolValue);if(n!==null)return n.value===(0, Te.asOrThrows)(t,_e.BoolValue).value;let r=(0, Te.asOrNull)(e,_e.IntValue);if(r!==null)return r.value===(0, Te.asOrThrows)(t,_e.IntValue).value;let a=(0, Te.asOrNull)(e,_e.FloatValue);if(a!==null)return a.value===(0, Te.asOrThrows)(t,_e.FloatValue).value;let s=(0, Te.asOrNull)(e,_e.Value),o=(0, Te.asOrNull)(t,_e.Value);if(s!==null&&o!==null)return (0, Te.isEquatable)(s.valueObject)&&(0, Te.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 n=this.GetRawVariableWithName(e,t),r=(0, Te.asOrNull)(n,_e.VariablePointerValue);return r!==null&&(n=this.ValueAtVariablePointer(r)),n}TryGetDefaultVariableValue(e){let t=(0, _i.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 n=null;if(t==0||t==-1){let r=null;if(this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)||(r=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null),r.exists)||this._defaultGlobalVariables!==null&&(r=(0, _i.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),r.exists))return r.result;if(this._listDefsOrigin===null)return (0, Mt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Mt.throwNullException)("name");let r=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, Te.asOrNull)(t,_e.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Te.asOrNull)(this.GetRawVariableWithName(n,r),_e.VariablePointerValue),s!=null&&(n=s.variableName,r=s.contextIndex,a=r==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,r);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, Te.asOrThrows)(e,_e.ListValue),r=(0, Te.asOrThrows)(t,_e.ListValue);n.value&&r.value&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null))),_e.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Mt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Mt.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 n=this.GetRawVariableWithName(e.variableName,t),r=(0, Te.asOrNull)(n,_e.VariablePointerValue);return r??new _e.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Xs.VariablesState=Ks;Ks.dontSaveDefaultValues=true;});var Ml=P(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.PRNG=void 0;var ql=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}};Ys.PRNG=ql;});var Dh=P(Qs=>{Object.defineProperty(Qs,"__esModule",{value:true});Qs.StatePatch=void 0;var $l=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}}};Qs.StatePatch=$l;});var Gl=P(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.SimpleJson=void 0;var wi=class i{static TextToDictionary(e){return new i.Reader(e).ToDictionary()}static TextToArray(e){return new i.Reader(e).ToArray()}};Oi.SimpleJson=wi;(function(i){class e{constructor(r){if(JSON.parse("0",(s,o,l)=>l!=null)){let s=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(r,s);}else {let s=r.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}i.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(r){this.WriteObjectStart(),r(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let r={};if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===i.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(r,a){if(this.WritePropertyStart(r),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(r,a){this.WritePropertyStart(r),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(r,a){this.WritePropertyStart(r),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(r){this.Assert(this.state===i.Writer.State.Object),this._propertyNameStack.push(r),this.IncrementChildCount(),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===i.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===i.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property)),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(r){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=r;}WriteArrayStart(){this.StartNewObject(true);let r=[];if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===i.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(r,a=true){if(r===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(r);}WriteBool(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(r));}WriteInt(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(r)));}WriteFloat(r){r!==null&&(this.StartNewObject(false),r==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):r==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(r)?this._addToCurrentObject(0):this._addToCurrentObject(r));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==i.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(r,a=true){if(this.Assert(this.state===i.Writer.State.String),r===null){console.error("Warning: trying to write a null string");return}this._currentString+=r;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(r){r?this.Assert(this.state===i.Writer.State.None||this.state===i.Writer.State.Property||this.state===i.Writer.State.Array):this.Assert(this.state===i.Writer.State.Property||this.state===i.Writer.State.Array),this.state===i.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===i.Writer.State.Array||this.state===i.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:i.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 r=this._stateStack.pop();r.childCount++,this._stateStack.push(r);}Assert(r){if(!r)throw Error("Assert failed while writing JSON")}_addToCurrentObject(r){this.Assert(this.currentCollection!==null),this.state===i.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(r)):this.state===i.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=r,this._propertyNameStack.pop());}}i.Writer=t,(function(n){(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";})(n.State||(n.State={}));class a{constructor(o){this.type=i.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(t=i.Writer||(i.Writer={}));})(wi||(Oi.SimpleJson=wi={}));});var _h=P(ea=>{Object.defineProperty(ea,"__esModule",{value:true});ea.Flow=void 0;var xh=jl(),Zs=Ln(),AC=we(),Hl=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new xh.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=Zs.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=Zs.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let r=n.choiceThreads;typeof r<"u"&&this.LoadFlowChoiceThreads(r,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>Zs.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, AC.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let r of this.currentChoices)Zs.JsonSerialisation.WriteChoice(n,r);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let r=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(r!==null)n.threadAtGeneration=r.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new xh.CallStack.Thread(a,t);}}}};ea.Flow=Hl;});var Th=P(na=>{Object.defineProperty(na,"__esModule",{value:true});na.StoryState=void 0;var DC=jl(),xC=Ah(),Ae=fe(),$t=sn(),_C=Ms(),Jl=Ns(),wh=We(),Ie=Oe(),Ul=tn(),Gt=Ln(),wC=Ml(),OC=rn(),Bn=fi(),Ti=xn(),Se=ie(),TC=ei(),tt=we(),PC=xi(),FC=Dh(),Oh=Gl(),ta=_h(),NC=Me(),zl=class i{ToJson(e=false){let t=new Oh.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Oh.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new wh.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, Ti.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, tt.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 r=this._patch.TryGetVisitCount(e,0);if(r.exists)return r.result}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let r=this.VisitCountForContainer(e);r++,this._patch.SetVisitCount(e,r);return}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.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 r=this._patch.TryGetTurnIndex(e,0);if(r.exists)return this.currentTurnIndex-r.result}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.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, tt.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, tt.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 Ul.StringBuilder,t=false;for(let n of this.outputStream){let r=(0, Se.asOrNull)(n,Ae.StringValue);if(!t&&r!==null)e.Append(r.value);else {let a=(0, Se.asOrNull)(n,Ie.ControlCommand);a!==null&&(a.commandType==Ie.ControlCommand.CommandType.BeginTag?t=true:a.commandType==Ie.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new Ul.StringBuilder,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
19
+ `);if(t=="<>")return new fh.Glue;for(let a=0;a<i._controlCommandNames.length;++a){let s=i._controlCommandNames[a];if(t==s)return new Y.ControlCommand(a)}if(t=="L^"&&(t="^"),Wl.NativeFunctionCall.CallExistsWithName(t))return Wl.NativeFunctionCall.CallWithName(t);if(t=="->->")return Y.ControlCommand.PopTunnel();if(t=="~ret")return Y.ControlCommand.PopFunction();if(t=="void")return new Ch.Void}if(typeof e=="object"&&!Array.isArray(e)){let t=e,n;if(t["^->"])return n=t["^->"],new Ge.DivertTargetValue(new dC.Path(n.toString()));if(t["^var"]){n=t["^var"];let c=new Ge.VariablePointerValue(n.toString());return "ci"in t&&(n=t.ci,c.contextIndex=parseInt(n)),c}let r=false,a=false,s=kn.PushPopType.Function,o=false;if((n=t["->"])?r=true:(n=t["f()"])?(r=true,a=true,s=kn.PushPopType.Function):(n=t["->t->"])?(r=true,a=true,s=kn.PushPopType.Tunnel):(n=t["x()"])&&(r=true,o=true,a=false,s=kn.PushPopType.Function),r){let c=new dh.Divert;c.pushesToStack=a,c.stackPushType=s,c.isExternal=o;let h=n.toString();return (n=t.var)?c.variableDivertName=h:c.targetPathString=h,c.isConditional=!!t.c,o&&(n=t.exArgs)&&(c.externalArgs=parseInt(n)),c}if(n=t["*"]){let c=new gh.ChoicePoint;return c.pathStringOnChoice=n.toString(),(n=t.flg)&&(c.flags=parseInt(n)),c}if(n=t["VAR?"])return new Bl.VariableReference(n.toString());if(n=t["CNT?"]){let c=new Bl.VariableReference;return c.pathStringForCount=n.toString(),c}let l=false,u=false;if((n=t["VAR="])?(l=true,u=true):(n=t["temp="])&&(l=true,u=false),l){let c=n.toString(),h=!t.re,f=new mh.VariableAssignment(c,h);return f.isGlobal=u,f}if(t["#"]!==void 0)return n=t["#"],new yh.Tag(n.toString());if(n=t.list){let c=n,h=new Us.InkList;if(n=t.origins){let f=n;h.SetInitialOriginNames(f);}for(let f in c)if(c.hasOwnProperty(f)){let d=c[f],g=new Us.InkListItem(f),y=parseInt(d);h.Add(g,y);}return new Ge.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,n){return JSON.stringify(e,(r,a)=>t?.some(s=>s===r)?void 0:a,n)}static WriteRuntimeContainer(e,t,n=false){if(e.WriteArrayStart(),t===null)return (0, un.throwNullException)("container");for(let l of t.content)this.WriteRuntimeObject(e,l);let r=t.namedOnlyContent,a=t.countFlags,s=t.name!=null&&!n,o=r!=null||a>0||s;if(o&&e.WriteObjectStart(),r!=null)for(let[l,u]of r){let c=l,h=(0, ve.asOrNull)(u,Js.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 Js.Container;t.content=this.JArrayToRuntimeObjList(e,true);let n=e[e.length-1];if(n!=null){let r=new Map;for(let a in n)if(a=="#f")t.countFlags=parseInt(n[a]);else if(a=="#n")t.name=n[a].toString();else {let s=this.JTokenToRuntimeObject(n[a]),o=(0, ve.asOrNull)(s,Js.Container);o&&(o.name=a),r.set(a,s);}t.namedOnlyContent=r;}return t}static JObjectToChoice(e){let t=new vh.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 n of t.tags)e.Write(n);e.WriteArrayEnd(),e.WritePropertyEnd();}}static WriteInkList(e,t){let n=t.value;if(n===null)return (0, un.throwNullException)("rawList");e.WriteObjectStart(),e.WritePropertyStart("list"),e.WriteObjectStart();for(let[r,a]of n){let s=Us.InkListItem.fromSerializedKey(r),o=a;if(s.itemName===null)return (0, un.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(),n.Count==0&&n.originNames!=null&&n.originNames.length>0){e.WritePropertyStart("origins"),e.WriteArrayStart();for(let r of n.originNames)e.Write(r);e.WriteArrayEnd(),e.WritePropertyEnd();}e.WriteObjectEnd();}static ListDefinitionsToJToken(e){let t={};for(let n of e.lists){let r={};for(let[a,s]of n.items){let o=Us.InkListItem.fromSerializedKey(a);if(o.itemName===null)return (0, un.throwNullException)("item.itemName");r[o.itemName]=s;}t[n.name]=r;}return t}static JTokenToListDefinitions(e){let t=e,n=[];for(let r in t)if(t.hasOwnProperty(r)){let a=r.toString(),s=t[r],o=new Map;for(let u in s)if(t.hasOwnProperty(r)){let c=s[u];o.set(u,parseInt(c));}let l=new gC.ListDefinition(a,o);n.push(l);}return new mC.ListDefinitionsOrigin(n)}};Ks.JsonSerialisation=zs;zs._controlCommandNames=(()=>{let i=[];i[Y.ControlCommand.CommandType.EvalStart]="ev",i[Y.ControlCommand.CommandType.EvalOutput]="out",i[Y.ControlCommand.CommandType.EvalEnd]="/ev",i[Y.ControlCommand.CommandType.Duplicate]="du",i[Y.ControlCommand.CommandType.PopEvaluatedValue]="pop",i[Y.ControlCommand.CommandType.PopFunction]="~ret",i[Y.ControlCommand.CommandType.PopTunnel]="->->",i[Y.ControlCommand.CommandType.BeginString]="str",i[Y.ControlCommand.CommandType.EndString]="/str",i[Y.ControlCommand.CommandType.NoOp]="nop",i[Y.ControlCommand.CommandType.ChoiceCount]="choiceCnt",i[Y.ControlCommand.CommandType.Turns]="turn",i[Y.ControlCommand.CommandType.TurnsSince]="turns",i[Y.ControlCommand.CommandType.ReadCount]="readc",i[Y.ControlCommand.CommandType.Random]="rnd",i[Y.ControlCommand.CommandType.SeedRandom]="srnd",i[Y.ControlCommand.CommandType.VisitIndex]="visit",i[Y.ControlCommand.CommandType.SequenceShuffleIndex]="seq",i[Y.ControlCommand.CommandType.StartThread]="thread",i[Y.ControlCommand.CommandType.Done]="done",i[Y.ControlCommand.CommandType.End]="end",i[Y.ControlCommand.CommandType.ListFromInt]="listInt",i[Y.ControlCommand.CommandType.ListRange]="range",i[Y.ControlCommand.CommandType.ListRandom]="lrnd",i[Y.ControlCommand.CommandType.BeginTag]="#",i[Y.ControlCommand.CommandType.EndTag]="/#";for(let e=0;e<Y.ControlCommand.CommandType.TOTAL_VALUES;++e)if(i[e]==null)throw new Error("Control command not accounted for in serialisation");return i})();});var Ml=T(Di=>{Object.defineProperty(Di,"__esModule",{value:true});Di.CallStack=void 0;var jl=sn(),Sh=We(),CC=xi(),Eh=Ln(),yC=de(),vC=tn(),bi=fi(),SC=ei(),bh=xn(),ql=Te(),Ai=class i{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){SC.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=bi.Pointer.Null,arguments[0]instanceof CC.Story){let e=arguments[0];this._startOfRoot=bi.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 i.Thread),this._threads[0].callstack.push(new i.Element(jl.PushPopType.Tunnel,this._startOfRoot));}SetJsonToken(e,t){this._threads.length=0;let n=e.threads;for(let r of n){let a=r,s=new i.Thread(a,t);this._threads.push(s);}this._threadCounter=parseInt(e.threadCounter),this._startOfRoot=bi.Pointer.StartOf(t.rootContentContainer);}WriteJson(e){e.WriteObject(t=>{t.WritePropertyStart("threads"),t.WriteArrayStart();for(let n of this._threads)n.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==jl.PushPopType.FunctionEvaluationFromGame}Push(e,t=0,n=0){let r=new i.Element(e,this.currentElement.currentPointer,false);r.evaluationStackHeightWhenPushed=t,r.functionStartInOutputStream=n,this.callStack.push(r);}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 n=this.callStack[t-1],r=(0, bh.tryGetValueFromMap)(n.temporaryVariables,e,null);return r.exists?r.result:null}SetTemporaryVariable(e,t,n,r=-1){r==-1&&(r=this.currentElementIndex+1);let a=this.callStack[r-1];if(!n&&!a.temporaryVariables.get(e))throw new Error("Could not find temporary variable to set: "+e);let s=(0, bh.tryGetValueFromMap)(a.temporaryVariables,e,null);s.exists&&yC.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(n=>{if(n.threadIndex==e)return n});return t.length>0?t[0]:null}get callStack(){return this.currentThread.callstack}get callStackTrace(){let e=new vC.StringBuilder;for(let t=0;t<this._threads.length;t++){let n=this._threads[t],r=t==this._threads.length-1;e.AppendFormat(`=== THREAD {0}/{1} {2}===
20
+ `,t+1,this._threads.length,r?"(current) ":"");for(let a=0;a<n.callstack.length;a++){n.callstack[a].type==jl.PushPopType.Function?e.Append(" [FUNCTION] "):e.Append(" [TUNNEL] ");let s=n.callstack[a].currentPointer;if(!s.isNull){if(e.Append("<SOMEWHERE IN "),s.container===null)return (0, ql.throwNullException)("pointer.container");e.Append(s.container.path.toString()),e.AppendLine(">");}}}return e.toString()}};Di.CallStack=Ai;(function(i){class e{constructor(r,a,s=false){this.evaluationStackHeightWhenPushed=0,this.functionStartInOutputStream=0,this.currentPointer=a.copy(),this.inExpressionEvaluation=s,this.temporaryVariables=new Map,this.type=r;}Copy(){let r=new e(this.type,this.currentPointer,this.inExpressionEvaluation);return r.temporaryVariables=new Map(this.temporaryVariables),r.evaluationStackHeightWhenPushed=this.evaluationStackHeightWhenPushed,r.functionStartInOutputStream=this.functionStartInOutputStream,r}}i.Element=e;class t{constructor(){if(this.threadIndex=0,this.previousPointer=bi.Pointer.Null,this.callstack=[],arguments[0]&&arguments[1]){let r=arguments[0],a=arguments[1];this.threadIndex=parseInt(r.threadIndex);let s=r.callstack;for(let l of s){let u=l,c=parseInt(u.type),h=bi.Pointer.Null,f,d=u.cPath;if(typeof d<"u"){f=d.toString();let D=a.ContentAtPath(new Sh.Path(f));if(h.container=D.container,h.index=parseInt(u.idx),D.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?");D.approximate&&(h.container!==null?a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"', so it was approximated to '"+h.container.path.toString()+"' to recover. Has the story changed since this save data was created?"):a.Warning("When loading state, exact internal story location couldn't be found: '"+f+"' and it may not be recoverable. Has the story changed since this save data was created?"));}let g=!!u.exp,y=new e(c,h,g),_=u.temp;typeof _<"u"?y.temporaryVariables=Eh.JsonSerialisation.JObjectToDictionaryRuntimeObjs(_):y.temporaryVariables.clear(),this.callstack.push(y);}let o=r.previousContentObject;if(typeof o<"u"){let l=new Sh.Path(o.toString());this.previousPointer=a.PointerAtPath(l);}}}Copy(){let r=new t;r.threadIndex=this.threadIndex;for(let a of this.callstack)r.callstack.push(a.Copy());return r.previousPointer=this.previousPointer.copy(),r}WriteJson(r){r.WriteObjectStart(),r.WritePropertyStart("callstack"),r.WriteArrayStart();for(let a of this.callstack){if(r.WriteObjectStart(),!a.currentPointer.isNull){if(a.currentPointer.container===null)return (0, ql.throwNullException)("el.currentPointer.container");r.WriteProperty("cPath",a.currentPointer.container.path.componentsString),r.WriteIntProperty("idx",a.currentPointer.index);}r.WriteProperty("exp",a.inExpressionEvaluation),r.WriteIntProperty("type",a.type),a.temporaryVariables.size>0&&(r.WritePropertyStart("temp"),Eh.JsonSerialisation.WriteDictionaryRuntimeObjs(r,a.temporaryVariables),r.WritePropertyEnd()),r.WriteObjectEnd();}if(r.WriteArrayEnd(),r.WritePropertyEnd(),r.WriteIntProperty("threadIndex",this.threadIndex),!this.previousPointer.isNull){let a=this.previousPointer.Resolve();if(a===null)return (0, ql.throwNullException)("this.previousPointer.Resolve()");r.WriteProperty("previousContentObject",a.path.toString());}r.WriteObjectEnd();}}i.Thread=t;})(Ai||(Di.CallStack=Ai={}));});var Dh=T(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.VariablesState=void 0;var Oe=de(),EC=ni(),Ah=Ln(),Fe=ne(),_i=xn(),Mt=Te();function bC(){return class{}}var Xs=class i extends bC(){variableChangedEvent(e,t){for(let n of this.variableChangedEventCallbacks)n(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 n=this._globalVariables.get(t);this.variableChangedEvent(t,n);}if(this.patch!=null)for(let t of this.patch.changedVariables){let n=this.patch.TryGetGlobal(t,null);n.exists&&e.set(t,n);}return this._changedVariablesForBatchObs=null,e}NotifyObservers(e){for(let[t,n]of e)this.variableChangedEvent(t,n);}get callStack(){return this._callStack}set callStack(e){this._callStack=e;}$(e,t){if(typeof t>"u"){let n=null;return this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists)?n.result.valueObject:(n=this._globalVariables.get(e),typeof n>"u"&&(n=this._defaultGlobalVariables.get(e)),typeof n<"u"?n.valueObject:null)}else {if(typeof this._defaultGlobalVariables.get(e)>"u")throw new EC.StoryException("Cannot assign to a variable ("+e+") that hasn't been declared in the story");let n=Oe.Value.Create(t);if(n==null)throw t==null?new Error("Cannot pass null to VariableState"):new Error("Invalid value passed to VariableState: "+t.toString());this.SetGlobal(e,n);}}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(r,a){return a in r?r[a]:r.$(a)},set(r,a,s){return a in r?r[a]=s:r.$(a,s),!0},ownKeys(r){return [...new Set([...r._defaultGlobalVariables.keys(),...r._globalVariables.keys()])]},getOwnPropertyDescriptor(r,a){return {enumerable:!0,configurable:!0,value:r.$(a)}}})}catch{}}ApplyPatch(){if(this.patch===null)return (0, Mt.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,n]of this._defaultGlobalVariables){let r=e[t];if(typeof r<"u"){let a=Ah.JsonSerialisation.JTokenToRuntimeObject(r);if(a===null)return (0, Mt.throwNullException)("tokenInkObject");this._globalVariables.set(t,a);}else this._globalVariables.set(t,n);}}WriteJson(e){e.WriteObjectStart();for(let[t,n]of this._globalVariables){let r=t,a=n;if(i.dontSaveDefaultValues&&this._defaultGlobalVariables.has(r)){let s=this._defaultGlobalVariables.get(r);if(this.RuntimeObjectsEqual(a,s))continue}e.WritePropertyStart(r),Ah.JsonSerialisation.WriteRuntimeObject(e,a),e.WritePropertyEnd();}e.WriteObjectEnd();}RuntimeObjectsEqual(e,t){if(e===null)return (0, Mt.throwNullException)("obj1");if(t===null)return (0, Mt.throwNullException)("obj2");if(e.constructor!==t.constructor)return false;let n=(0, Fe.asOrNull)(e,Oe.BoolValue);if(n!==null)return n.value===(0, Fe.asOrThrows)(t,Oe.BoolValue).value;let r=(0, Fe.asOrNull)(e,Oe.IntValue);if(r!==null)return r.value===(0, Fe.asOrThrows)(t,Oe.IntValue).value;let a=(0, Fe.asOrNull)(e,Oe.FloatValue);if(a!==null)return a.value===(0, Fe.asOrThrows)(t,Oe.FloatValue).value;let s=(0, Fe.asOrNull)(e,Oe.Value),o=(0, Fe.asOrNull)(t,Oe.Value);if(s!==null&&o!==null)return (0, Fe.isEquatable)(s.valueObject)&&(0, Fe.isEquatable)(o.valueObject)?s.valueObject.Equals(o.valueObject):s.valueObject===o.valueObject;throw new Error("FastRoughDefinitelyEquals: Unsupported runtime object type: "+e.constructor.name)}GetVariableWithName(e,t=-1){let n=this.GetRawVariableWithName(e,t),r=(0, Fe.asOrNull)(n,Oe.VariablePointerValue);return r!==null&&(n=this.ValueAtVariablePointer(r)),n}TryGetDefaultVariableValue(e){let t=(0, _i.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 n=null;if(t==0||t==-1){let r=null;if(this.patch!==null&&(r=this.patch.TryGetGlobal(e,null),r.exists)||(r=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null),r.exists)||this._defaultGlobalVariables!==null&&(r=(0, _i.tryGetValueFromMap)(this._defaultGlobalVariables,e,null),r.exists))return r.result;if(this._listDefsOrigin===null)return (0, Mt.throwNullException)("VariablesState._listDefsOrigin");let a=this._listDefsOrigin.FindSingleItemListWithName(e);if(a)return a}return n=this._callStack.GetTemporaryVariableWithName(e,t),n}ValueAtVariablePointer(e){return this.GetVariableWithName(e.variableName,e.contextIndex)}Assign(e,t){let n=e.variableName;if(n===null)return (0, Mt.throwNullException)("name");let r=-1,a=false;if(e.isNewDeclaration?a=e.isGlobal:a=this.GlobalVariableExistsWithName(n),e.isNewDeclaration){let s=(0, Fe.asOrNull)(t,Oe.VariablePointerValue);s!==null&&(t=this.ResolveVariablePointer(s));}else {let s=null;do s=(0, Fe.asOrNull)(this.GetRawVariableWithName(n,r),Oe.VariablePointerValue),s!=null&&(n=s.variableName,r=s.contextIndex,a=r==0);while(s!=null)}a?this.SetGlobal(n,t):this._callStack.SetTemporaryVariable(n,t,e.isNewDeclaration,r);}SnapshotDefaultGlobals(){this._defaultGlobalVariables=new Map(this._globalVariables);}RetainListOriginsForAssignment(e,t){let n=(0, Fe.asOrThrows)(e,Oe.ListValue),r=(0, Fe.asOrThrows)(t,Oe.ListValue);n.value&&r.value&&r.value.Count==0&&r.value.SetInitialOriginNames(n.value.originNames);}SetGlobal(e,t){let n=null;if(this.patch===null&&(n=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null)),this.patch!==null&&(n=this.patch.TryGetGlobal(e,null),n.exists||(n=(0, _i.tryGetValueFromMap)(this._globalVariables,e,null))),Oe.ListValue.RetainListOriginsForAssignment(n.result,t),e===null)return (0, Mt.throwNullException)("variableName");if(this.patch!==null?this.patch.SetGlobal(e,t):this._globalVariables.set(e,t),this.variableChangedEvent!==null&&n!==null&&t!==n.result)if(this._batchObservingVariableChanges){if(this._changedVariablesForBatchObs===null)return (0, Mt.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 n=this.GetRawVariableWithName(e.variableName,t),r=(0, Fe.asOrNull)(n,Oe.VariablePointerValue);return r??new Oe.VariablePointerValue(e.variableName,t)}GetContextIndexOfVariableNamed(e){return this.GlobalVariableExistsWithName(e)?0:this._callStack.currentElementIndex}ObserveVariableChange(e){this.variableChangedEventCallbacks.push(e);}};Ys.VariablesState=Xs;Xs.dontSaveDefaultValues=true;});var Gl=T(Qs=>{Object.defineProperty(Qs,"__esModule",{value:true});Qs.PRNG=void 0;var $l=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}};Qs.PRNG=$l;});var xh=T(Zs=>{Object.defineProperty(Zs,"__esModule",{value:true});Zs.StatePatch=void 0;var Hl=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}}};Zs.StatePatch=Hl;});var Jl=T(Oi=>{Object.defineProperty(Oi,"__esModule",{value:true});Oi.SimpleJson=void 0;var wi=class i{static TextToDictionary(e){return new i.Reader(e).ToDictionary()}static TextToArray(e){return new i.Reader(e).ToArray()}};Oi.SimpleJson=wi;(function(i){class e{constructor(r){if(JSON.parse("0",(s,o,l)=>l!=null)){let s=(o,l,u)=>Number.isInteger(l)&&u.source.endsWith(".0")?u.source+"f":l;this._rootObject=JSON.parse(r,s);}else {let s=r.replace(/(,\s*)([0-9]+\.[0]+)([,]*)/g,'$1"$2f"$3');this._rootObject=JSON.parse(s);}}ToDictionary(){return this._rootObject}ToArray(){return this._rootObject}}i.Reader=e;class t{constructor(){this._currentPropertyName=null,this._currentString=null,this._stateStack=[],this._collectionStack=[],this._propertyNameStack=[],this._jsonObject=null;}WriteObject(r){this.WriteObjectStart(),r(this),this.WriteObjectEnd();}WriteObjectStart(){this.StartNewObject(true);let r={};if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Object));}WriteObjectEnd(){this.Assert(this.state===i.Writer.State.Object),this._collectionStack.pop(),this._stateStack.pop();}WriteProperty(r,a){if(this.WritePropertyStart(r),arguments[1]instanceof Function){let s=arguments[1];s(this);}else {let s=arguments[1];this.Write(s);}this.WritePropertyEnd();}WriteIntProperty(r,a){this.WritePropertyStart(r),this.WriteInt(a),this.WritePropertyEnd();}WriteFloatProperty(r,a){this.WritePropertyStart(r),this.WriteFloat(a),this.WritePropertyEnd();}WritePropertyStart(r){this.Assert(this.state===i.Writer.State.Object),this._propertyNameStack.push(r),this.IncrementChildCount(),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property));}WritePropertyEnd(){this.Assert(this.state===i.Writer.State.Property),this.Assert(this.childCount===1),this._stateStack.pop();}WritePropertyNameStart(){this.Assert(this.state===i.Writer.State.Object),this.IncrementChildCount(),this._currentPropertyName="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Property)),this._stateStack.push(new i.Writer.StateElement(i.Writer.State.PropertyName));}WritePropertyNameEnd(){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._propertyNameStack.push(this._currentPropertyName),this._currentPropertyName=null,this._stateStack.pop();}WritePropertyNameInner(r){this.Assert(this.state===i.Writer.State.PropertyName),this.Assert(this._currentPropertyName!==null),this._currentPropertyName+=r;}WriteArrayStart(){this.StartNewObject(true);let r=[];if(this.state===i.Writer.State.Property){this.Assert(this.currentCollection!==null),this.Assert(this.currentPropertyName!==null);let a=this._propertyNameStack.pop();this.currentCollection[a]=r,this._collectionStack.push(r);}else this.state===i.Writer.State.Array?(this.Assert(this.currentCollection!==null),this.currentCollection.push(r),this._collectionStack.push(r)):(this.Assert(this.state===i.Writer.State.None),this._jsonObject=r,this._collectionStack.push(r));this._stateStack.push(new i.Writer.StateElement(i.Writer.State.Array));}WriteArrayEnd(){this.Assert(this.state===i.Writer.State.Array),this._collectionStack.pop(),this._stateStack.pop();}Write(r,a=true){if(r===null){console.error("Warning: trying to write a null value");return}this.StartNewObject(false),this._addToCurrentObject(r);}WriteBool(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(r));}WriteInt(r){r!==null&&(this.StartNewObject(false),this._addToCurrentObject(Math.floor(r)));}WriteFloat(r){r!==null&&(this.StartNewObject(false),r==Number.POSITIVE_INFINITY?this._addToCurrentObject(34e37):r==Number.NEGATIVE_INFINITY?this._addToCurrentObject(-34e37):isNaN(r)?this._addToCurrentObject(0):this._addToCurrentObject(r));}WriteNull(){this.StartNewObject(false),this._addToCurrentObject(null);}WriteStringStart(){this.StartNewObject(false),this._currentString="",this._stateStack.push(new i.Writer.StateElement(i.Writer.State.String));}WriteStringEnd(){this.Assert(this.state==i.Writer.State.String),this._stateStack.pop(),this._addToCurrentObject(this._currentString),this._currentString=null;}WriteStringInner(r,a=true){if(this.Assert(this.state===i.Writer.State.String),r===null){console.error("Warning: trying to write a null string");return}this._currentString+=r;}toString(){return this._jsonObject===null?"":JSON.stringify(this._jsonObject)}StartNewObject(r){r?this.Assert(this.state===i.Writer.State.None||this.state===i.Writer.State.Property||this.state===i.Writer.State.Array):this.Assert(this.state===i.Writer.State.Property||this.state===i.Writer.State.Array),this.state===i.Writer.State.Property&&this.Assert(this.childCount===0),(this.state===i.Writer.State.Array||this.state===i.Writer.State.Property)&&this.IncrementChildCount();}get state(){return this._stateStack.length>0?this._stateStack[this._stateStack.length-1].type:i.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 r=this._stateStack.pop();r.childCount++,this._stateStack.push(r);}Assert(r){if(!r)throw Error("Assert failed while writing JSON")}_addToCurrentObject(r){this.Assert(this.currentCollection!==null),this.state===i.Writer.State.Array?(this.Assert(Array.isArray(this.currentCollection)),this.currentCollection.push(r)):this.state===i.Writer.State.Property&&(this.Assert(!Array.isArray(this.currentCollection)),this.Assert(this.currentPropertyName!==null),this.currentCollection[this.currentPropertyName]=r,this._propertyNameStack.pop());}}i.Writer=t,(function(n){(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";})(n.State||(n.State={}));class a{constructor(o){this.type=i.Writer.State.None,this.childCount=0,this.type=o;}}n.StateElement=a;})(t=i.Writer||(i.Writer={}));})(wi||(Oi.SimpleJson=wi={}));});var wh=T(ta=>{Object.defineProperty(ta,"__esModule",{value:true});ta.Flow=void 0;var _h=Ml(),ea=Ln(),AC=Te(),Ul=class{constructor(){let e=arguments[0],t=arguments[1];if(this.name=e,this.callStack=new _h.CallStack(t),arguments[2]){let n=arguments[2];this.callStack.SetJsonToken(n.callstack,t),this.outputStream=ea.JsonSerialisation.JArrayToRuntimeObjList(n.outputStream),this.currentChoices=ea.JsonSerialisation.JArrayToRuntimeObjList(n.currentChoices);let r=n.choiceThreads;typeof r<"u"&&this.LoadFlowChoiceThreads(r,t);}else this.outputStream=[],this.currentChoices=[];}WriteJson(e){e.WriteObjectStart(),e.WriteProperty("callstack",n=>this.callStack.WriteJson(n)),e.WriteProperty("outputStream",n=>ea.JsonSerialisation.WriteListRuntimeObjs(n,this.outputStream));let t=false;for(let n of this.currentChoices){if(n.threadAtGeneration===null)return (0, AC.throwNullException)("c.threadAtGeneration");n.originalThreadIndex=n.threadAtGeneration.threadIndex,this.callStack.ThreadWithIndex(n.originalThreadIndex)===null&&(t||(t=true,e.WritePropertyStart("choiceThreads"),e.WriteObjectStart()),e.WritePropertyStart(n.originalThreadIndex),n.threadAtGeneration.WriteJson(e),e.WritePropertyEnd());}t&&(e.WriteObjectEnd(),e.WritePropertyEnd()),e.WriteProperty("currentChoices",n=>{n.WriteArrayStart();for(let r of this.currentChoices)ea.JsonSerialisation.WriteChoice(n,r);n.WriteArrayEnd();}),e.WriteObjectEnd();}LoadFlowChoiceThreads(e,t){for(let n of this.currentChoices){let r=this.callStack.ThreadWithIndex(n.originalThreadIndex);if(r!==null)n.threadAtGeneration=r.Copy();else {let a=e[`${n.originalThreadIndex}`];n.threadAtGeneration=new _h.CallStack.Thread(a,t);}}}};ta.Flow=Ul;});var Ph=T(ia=>{Object.defineProperty(ia,"__esModule",{value:true});ia.StoryState=void 0;var DC=Ml(),xC=Dh(),De=de(),$t=sn(),_C=$s(),zl=Is(),Oh=We(),Ve=Pe(),Kl=tn(),Gt=Ln(),wC=Gl(),OC=rn(),Bn=fi(),Ti=xn(),Ee=ne(),TC=ei(),tt=Te(),PC=xi(),FC=xh(),Th=Jl(),na=wh(),NC=Me(),Xl=class i{ToJson(e=false){let t=new Th.SimpleJson.Writer;return this.WriteJson(t),t.toString()}toJson(e=false){return this.ToJson(e)}LoadJson(e){let t=Th.SimpleJson.TextToDictionary(e);this.LoadJsonObj(t),this.onDidLoadState!==null&&this.onDidLoadState();}VisitCountAtPathString(e){let t;if(this._patch!==null){let n=this.story.ContentAtPath(new Oh.Path(e)).container;if(n===null)throw new Error("Content at path not found: "+e);if(t=this._patch.TryGetVisitCount(n,0),t.exists)return t.result}return t=(0, Ti.tryGetValueFromMap)(this._visitCounts,e,null),t.exists?t.result:0}VisitCountForContainer(e){if(e===null)return (0, tt.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 r=this._patch.TryGetVisitCount(e,0);if(r.exists)return r.result}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);return n.exists?n.result:0}IncrementVisitCountForContainer(e){if(this._patch!==null){let r=this.VisitCountForContainer(e);r++,this._patch.SetVisitCount(e,r);return}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._visitCounts,t,null);n.exists?this._visitCounts.set(t,n.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 r=this._patch.TryGetTurnIndex(e,0);if(r.exists)return this.currentTurnIndex-r.result}let t=e.path.toString(),n=(0, Ti.tryGetValueFromMap)(this._turnIndices,t,0);return n.exists?this.currentTurnIndex-n.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, tt.throwNullException)("pointer.path"):e.path.toString()}get previousPathString(){let e=this.previousPointer;return e.isNull?null:e.path===null?(0, tt.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 Kl.StringBuilder,t=false;for(let n of this.outputStream){let r=(0, Ee.asOrNull)(n,De.StringValue);if(!t&&r!==null)e.Append(r.value);else {let a=(0, Ee.asOrNull)(n,Ve.ControlCommand);a!==null&&(a.commandType==Ve.ControlCommand.CommandType.BeginTag?t=true:a.commandType==Ve.ControlCommand.CommandType.EndTag&&(t=false));}}this._currentText=this.CleanOutputWhitespace(e.toString()),this._outputStreamTextDirty=false;}return this._currentText}CleanOutputWhitespace(e){let t=new Kl.StringBuilder,n=-1,r=0;for(let a=0;a<e.length;a++){let s=e.charAt(a),o=s==" "||s==" ";o&&n==-1&&(n=a),o||(s!=`
21
21
  `&&n>0&&n!=r&&t.Append(" "),n=-1),s==`
22
- `&&(r=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new Ul.StringBuilder;for(let n of this.outputStream){let r=(0, Se.asOrNull)(n,Ie.ControlCommand);if(r!=null){if(r.commandType==Ie.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(r.commandType==Ie.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, Se.asOrNull)(n,Ae.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, Se.asOrNull)(n,_C.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),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=Bn.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 ta.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new xC.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new wC.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Bn.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,n=(0, Ti.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new ta.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, tt.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new i(this.story);if(t._patch=new FC.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new DC.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,r]of this._namedFlows)t._namedFlows.set(n,r),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,n){(n?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,n]of this._namedFlows)e.WriteProperty(t,r=>n.WriteJson(r));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=>Gt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, tt.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Gt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Gt.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",PC.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let r=t.flows;if(r!=null){let s=r;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[l,u]of o){let c=l,h=u,f=new ta.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new ta.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, tt.throwNullException)("this._namedFlows");this._namedFlows.set(c,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Gt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Gt.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=Gt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new wh.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Gt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Gt.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, Se.asOrNull)(e,Ae.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let r of n)this.PushToOutputStreamIndividual(r);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, tt.throwNullException)("single.value");let n=-1,r=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
22
+ `&&(r=a+1),o||t.Append(s);}return t.toString()}get currentTags(){if(this._outputStreamTagsDirty){this._currentTags=[];let e=false,t=new Kl.StringBuilder;for(let n of this.outputStream){let r=(0, Ee.asOrNull)(n,Ve.ControlCommand);if(r!=null){if(r.commandType==Ve.ControlCommand.CommandType.BeginTag){if(e&&t.Length>0){let a=this.CleanOutputWhitespace(t.toString());this._currentTags.push(a),t.Clear();}e=true;}else if(r.commandType==Ve.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, Ee.asOrNull)(n,De.StringValue);a!==null&&t.Append(a.value);}else {let a=(0, Ee.asOrNull)(n,_C.Tag);a!=null&&a.text!=null&&a.text.length>0&&this._currentTags.push(a.text);}}if(t.Length>0){let n=this.CleanOutputWhitespace(t.toString());this._currentTags.push(n),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=Bn.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 na.Flow(this.kDefaultFlowName,e),this.OutputStreamDirty(),this._aliveFlowNamesDirty=true,this._evaluationStack=[],this._variablesState=new xC.VariablesState(this.callStack,e.listDefinitions),this._visitCounts=new Map,this._turnIndices=new Map,this.currentTurnIndex=-1;let t=new Date().getTime();this.storySeed=new wC.PRNG(t).next()%100,this.previousRandom=0,this.GoToStart();}GoToStart(){this.callStack.currentElement.currentPointer=Bn.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,n=(0, Ti.tryGetValueFromMap)(this._namedFlows,e,null);n.exists?t=n.result:(t=new na.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, tt.throwNullException)("this._namedFlows");this._namedFlows.delete(e),this._aliveFlowNamesDirty=true;}CopyAndStartPatching(e){let t=new i(this.story);if(t._patch=new FC.StatePatch(this._patch),t._currentFlow.name=this._currentFlow.name,t._currentFlow.callStack=new DC.CallStack(this._currentFlow.callStack),t._currentFlow.outputStream.push(...this._currentFlow.outputStream),t.OutputStreamDirty(),e)for(let n of this._currentFlow.currentChoices)t._currentFlow.currentChoices.push(n.Clone());else t._currentFlow.currentChoices.push(...this._currentFlow.currentChoices);if(this._namedFlows!==null){t._namedFlows=new Map;for(let[n,r]of this._namedFlows)t._namedFlows.set(n,r),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,n){(n?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,n]of this._namedFlows)e.WriteProperty(t,r=>n.WriteJson(r));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=>Gt.JsonSerialisation.WriteListRuntimeObjs(t,this.evaluationStack)),!this.divertedPointer.isNull){if(this.divertedPointer.path===null)return (0, tt.throwNullException)("divertedPointer");e.WriteProperty("currentDivertTarget",this.divertedPointer.path.componentsString);}e.WriteProperty("visitCounts",t=>Gt.JsonSerialisation.WriteIntDictionary(t,this._visitCounts)),e.WriteProperty("turnIndices",t=>Gt.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",PC.Story.inkVersionCurrent),e.WriteObjectEnd();}LoadJsonObj(e){let t=e,n=t.inkSaveVersion;if(n==null)throw new Error("ink save format incorrect, can't load.");if(parseInt(n)<this.kMinCompatibleLoadVersion)throw new Error("Ink save format isn't compatible with the current version (saw '"+n+"', but minimum is "+this.kMinCompatibleLoadVersion+"), so can't load.");let r=t.flows;if(r!=null){let s=r;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[l,u]of o){let c=l,h=u,f=new na.Flow(c,this.story,h);if(Object.keys(s).length===1)this._currentFlow=new na.Flow(c,this.story,h);else {if(this._namedFlows===null)return (0, tt.throwNullException)("this._namedFlows");this._namedFlows.set(c,f);}}if(this._namedFlows!=null&&this._namedFlows.size>1){let l=t.currentFlowName;this._currentFlow=this._namedFlows.get(l);}}else {this._namedFlows=null,this._currentFlow.name=this.kDefaultFlowName,this._currentFlow.callStack.SetJsonToken(t.callstackThreads,this.story),this._currentFlow.outputStream=Gt.JsonSerialisation.JArrayToRuntimeObjList(t.outputStream),this._currentFlow.currentChoices=Gt.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=Gt.JsonSerialisation.JArrayToRuntimeObjList(t.evalStack);let a=t.currentDivertTarget;if(a!=null){let s=new Oh.Path(a.toString());this.divertedPointer=this.story.PointerAtPath(s);}this._visitCounts=Gt.JsonSerialisation.JObjectToIntDictionary(t.visitCounts),this._turnIndices=Gt.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, Ee.asOrNull)(e,De.StringValue);if(t!==null){let n=this.TrySplittingHeadTailWhitespace(t);if(n!==null){for(let r of n)this.PushToOutputStreamIndividual(r);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, tt.throwNullException)("single.value");let n=-1,r=-1;for(let c=0;c<t.length;c++){let h=t[c];if(h==`
23
23
  `)n==-1&&(n=c),r=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==`
24
- `)a==-1&&(a=c),s=c;else {if(h==" "||h==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let c=new Ae.StringValue(t.substring(0,n));o.push(c);}o.push(new Ae.StringValue(`
25
- `)),l=r+1;}if(a!=-1&&(u=s),u>l){let c=t.substring(l,u);o.push(new Ae.StringValue(c));}if(a!=-1&&s>r&&(o.push(new Ae.StringValue(`
26
- `)),a<t.length-1)){let c=t.length-a-1,h=new Ae.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, Se.asOrNull)(e,Jl.Glue),n=(0, Se.asOrNull)(e,Ae.StringValue),r=true;if(t)this.TrimNewlinesFromOutputStream(),r=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==$t.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let c=this.outputStream[u],h=c instanceof Ie.ControlCommand?c:null;if((c instanceof Jl.Glue?c:null)!=null){o=u;break}else if(h!=null&&h.commandType==Ie.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(o!=-1&&a!=-1?l=Math.min(a,o):o!=-1?l=o:l=a,l!=-1){if(n.isNewline)r=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let c=u.length-1;c>=0;c--){let h=u[c];if(h.type==$t.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(r=false);}if(r){if(e===null)return (0, tt.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],r=(0, Se.asOrNull)(n,Ie.ControlCommand),a=(0, Se.asOrNull)(n,Ae.StringValue);if(r!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, Se.asOrNull)(this.outputStream[t],Ae.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 Jl.Glue)this.outputStream.splice(e,1);else if(t instanceof Ie.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof Ie.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof Ae.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof Ae.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, Se.asOrNull)(this.outputStream[e],Ie.ControlCommand);if(t instanceof Ie.ControlCommand&&t.commandType==Ie.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, Se.asOrNull)(e,Ae.ListValue);if(t){let n=t.value;if(n===null)return (0, tt.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let r of n.originNames){if(this.story.listDefinitions===null)return (0, tt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(r,null);if(a.result===null)return (0, tt.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, tt.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, Se.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, Se.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Bn.Pointer.Null,this.previousPointer=Bn.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){TC.Debug.Assert(this.callStack.currentElement.type==$t.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],r=(0, Se.asOrNull)(n,Ae.StringValue),a=(0, Se.asOrNull)(n,Ie.ControlCommand);if(r!=null){if(a)break;if(r.isNewline||r.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==$t.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push($t.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Bn.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 NC.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, Se.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(Ae.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==$t.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Bn.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=$t.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 n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack($t.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof OC.Void)return null;let n=(0, Se.asOrThrows)(t,Ae.Value);return n.valueType==Ae.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.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;}};na.StoryState=zl;});var Ph=P(ia=>{Object.defineProperty(ia,"__esModule",{value:true});ia.Stopwatch=void 0;var Kl=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;}};ia.Stopwatch=Kl;});var Nh=P(ra=>{Object.defineProperty(ra,"__esModule",{value:true});ra.ErrorType=void 0;var Fh;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(Fh||(ra.ErrorType=Fh={}));});var xi=P(pn=>{Object.defineProperty(pn,"__esModule",{value:true});pn.Story=pn.InkList=void 0;var Pe=Ce(),Xl=je(),Yl=Ln(),IC=Th(),M=Oe(),nt=sn(),RC=xr(),VC=Il(),Ih=Ct(),L=fe(),Ql=We(),Pi=rn(),sa=Ms(),kC=Wt(),LC=Rn(),BC=mt(),cn=ni(),Zl=Ml(),hn=tn(),WC=Vl(),jC=Ph(),Ht=fi(),Fi=Me(),$=ie(),te=we(),Rh=Gl(),Vh=Nh(),qC=Me();Object.defineProperty(pn,"InkList",{enumerable:true,get:function(){return qC.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Wn=class i extends Xl.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, te.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,n=null;if(arguments[0]instanceof Pe.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let r=arguments[0];n=Rh.SimpleJson.TextToDictionary(r);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new WC.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let r=n,a=r.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>i.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!=i.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${i.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=r.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=r.listDefs)&&(this._listDefinitions=Yl.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, $.asOrThrows)(Yl.JsonSerialisation.JTokenToRuntimeObject(o),Pe.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Rh.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",i.inkVersionCurrent),e.WriteProperty("root",n=>Yl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[r,a]of n.items){let s=Fi.InkListItem.fromSerializedKey(r),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 IC.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, te.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, te.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new Ql.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 n=new jC.Stopwatch;n.Start();let r=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{r=this.ContinueSingleStep();}catch(s){if(!(s instanceof cn.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(r||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((r||!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(nt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(nt.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,Vh.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,Vh.ErrorType.Warning);this.ResetErrors();}else {let s=new hn.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 cn.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, te.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, te.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==i.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==i.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,n,r){if(e===null)return (0, te.throwNullException)("prevText");if(t===null)return (0, te.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
- `;if(n==r&&e.length==t.length&&a)return i.OutputStateChange.NoChange;if(!a)return i.OutputStateChange.NewlineRemoved;if(r>n)return i.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return i.OutputStateChange.ExtendedBeyondNewline}return i.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new hn.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 Pe.Container?t:null}PointerAtPath(e){if(e.length==0)return Ht.Pointer.Null;let t=new Ht.Pointer,n=e.length,r=null;return e.lastComponent===null?(0, te.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,r=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=r.container,t.index=e.lastComponent.index):(r=this.mainContentContainer.ContentAtPath(e),t.container=r.container,t.index=-1),r.obj==null||r.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):r.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+r.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, te.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 n=(0, $.asOrNull)(t.Resolve(),Pe.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=Ht.Pointer.StartOf(n),n=(0, $.asOrNull)(t.Resolve(),Pe.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let r=t.Resolve(),a=this.PerformLogicAndFlowControl(r);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, $.asOrNull)(r,RC.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),r=null,e=false;}if(r instanceof Pe.Container&&(e=false),e){let l=(0, $.asOrNull)(r,L.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);r=new L.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(r):this.state.PushToOutputStream(r);}this.NextContent();let o=(0, $.asOrNull)(r,M.ControlCommand);o&&o.commandType==M.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, $.asOrNull)(s,Pe.Container)||(0, $.asOrNull)(e.container,Pe.Container);for(;o;)this._prevContainers.push(o),o=(0, $.asOrNull)(o.parent,Pe.Container);}let n=t.Resolve();if(n==null)return;let r=(0, $.asOrNull)(n.parent,Pe.Container),a=true;for(;r&&(this._prevContainers.indexOf(r)<0||r.countingAtStartOnly);){let s=r.content.length>0&&n==r.content[0]&&a;s||(a=false),this.VisitContainer(r,s),n=r,r=(0, $.asOrNull)(r.parent,Pe.Container);}}PopChoiceStringAndTags(e){let t=(0, $.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);for(;this.state.evaluationStack.length>0&&(0, $.asOrNull)(this.state.PeekEvaluationStack(),sa.Tag)!=null;){let n=(0, $.asOrNull)(this.state.PopEvaluationStack(),sa.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",r="",a=[];if(e.hasChoiceOnlyContent&&(r=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new VC.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=(n+r).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof L.Value){let n=e;if(n instanceof L.DivertTargetValue){let r=n;return this.Error("Shouldn't use a divert target (to "+r.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof Ih.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,r=this.state.variablesState.GetVariableWithName(n);if(r==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(r instanceof L.DivertTargetValue)){let s=(0, $.asOrNull)(r,L.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof L.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+r+"'.",this.Error(o);}let a=(0, $.asOrThrows)(r,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 M.ControlCommand){let t=e;switch(t.commandType){case M.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case M.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case M.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof Pi.Void)){let S=new L.StringValue(C.toString());this.state.PushToOutputStream(S);}}break;case M.ControlCommand.CommandType.NoOp:break;case M.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case M.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case M.ControlCommand.CommandType.PopFunction:case M.ControlCommand.CommandType.PopTunnel:let n=t.commandType==M.ControlCommand.CommandType.PopFunction?nt.PushPopType.Function:nt.PushPopType.Tunnel,r=null;if(n==nt.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();r=(0, $.asOrNull)(C,L.DivertTargetValue),r===null&&this.Assert(C instanceof Pi.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let C=new Map;C.set(nt.PushPopType.Function,"function return statement (~ return)"),C.set(nt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let S=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(S="end of flow (-> END or choice)");let w="Found "+C.get(n)+", when expected "+S;this.Error(w);}else this.state.PopCallStack(),r&&(this.state.divertedPointer=this.PointerAtPath(r.targetPath));break;case M.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 M.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case M.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],S=0;for(let O=this.state.outputStream.length-1;O>=0;--O){let v=this.state.outputStream[O];S++;let V=(0, $.asOrNull)(v,M.ControlCommand);if(V!=null){if(V.commandType==M.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}v instanceof L.StringValue&&C.push(v);}this.state.PopFromOutputStream(S);let w=new hn.StringBuilder;for(let O of C.reverse())w.Append(O.toString());let b=new sa.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(b);}else this.state.PushToOutputStream(t);break}case M.ControlCommand.CommandType.EndString:{let C=[],S=[],w=0;for(let O=this.state.outputStream.length-1;O>=0;--O){let v=this.state.outputStream[O];w++;let V=(0, $.asOrNull)(v,M.ControlCommand);if(V&&V.commandType==M.ControlCommand.CommandType.BeginString)break;v instanceof sa.Tag&&S.push(v),v instanceof L.StringValue&&C.push(v);}this.state.PopFromOutputStream(w);for(let O of S)this.state.PushToOutputStream(O);C=C.reverse();let b=new hn.StringBuilder;for(let O of C)b.Append(O.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new L.StringValue(b.toString()));break}case M.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new L.IntValue(a));break;case M.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new L.IntValue(this.state.currentTurnIndex+1));break;case M.ControlCommand.CommandType.TurnsSince:case M.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, $.asOrThrows)(s,L.DivertTargetValue),l=(0, $.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Pe.Container),u;l!=null?t.commandType==M.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==M.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new L.IntValue(u));break;case M.ControlCommand.CommandType.Random:{let C=(0, $.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),S=(0, $.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, te.throwNullException)("maxInt.value");if(S.value===null)return (0, te.throwNullException)("minInt.value");let w=C.value-S.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+S.value+" and maximum as "+C.value+". The maximum must be larger");let b=this.state.storySeed+this.state.previousRandom,v=new Zl.PRNG(b).next(),V=v%w+S.value;this.state.PushEvaluationStack(new L.IntValue(V)),this.state.previousRandom=v;break}case M.ControlCommand.CommandType.SeedRandom:let c=(0, $.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, te.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Pi.Void);break;case M.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new L.IntValue(h));break;case M.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new L.IntValue(f));break;case M.ControlCommand.CommandType.StartThread:break;case M.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Ht.Pointer.Null);break;case M.ControlCommand.CommandType.End:this.state.ForceEnd();break;case M.ControlCommand.CommandType.ListFromInt:let d=(0, $.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),g=(0, $.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);if(d===null)throw new cn.StoryException("Passed non-integer when creating a list element from a numerical value.");let y=null;if(this.listDefinitions===null)return (0, te.throwNullException)("this.listDefinitions");let _=this.listDefinitions.TryListGetDefinition(g.value,null);if(_.exists){if(d.value===null)return (0, te.throwNullException)("minInt.value");let C=_.result.TryGetItemWithValue(d.value,Fi.InkListItem.Null);C.exists&&(y=new L.ListValue(C.result,d.value));}else throw new cn.StoryException("Failed to find LIST called "+g.value);y==null&&(y=new L.ListValue),this.state.PushEvaluationStack(y);break;case M.ControlCommand.CommandType.ListRange:let D=(0, $.asOrNull)(this.state.PopEvaluationStack(),L.Value),m=(0, $.asOrNull)(this.state.PopEvaluationStack(),L.Value),p=(0, $.asOrNull)(this.state.PopEvaluationStack(),L.ListValue);if(p===null||m===null||D===null)throw new cn.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(p.value===null)return (0, te.throwNullException)("targetList.value");let E=p.value.ListWithSubRange(m.valueObject,D.valueObject);this.state.PushEvaluationStack(new L.ListValue(E));break;case M.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new cn.StoryException("Expected list for LIST_RANDOM");let S=C.value,w=null;if(S===null)throw (0, te.throwNullException)("list");if(S.Count==0)w=new Fi.InkList;else {let b=this.state.storySeed+this.state.previousRandom,v=new Zl.PRNG(b).next(),V=v%S.Count,I=S.entries();for(let x=0;x<=V-1;x++)I.next();let B=I.next().value,A={Key:Fi.InkListItem.fromSerializedKey(B[0]),Value:B[1]};if(A.Key.originName===null)return (0, te.throwNullException)("randomItem.Key.originName");w=new Fi.InkList(A.Key.originName,this),w.Add(A.Key,A.Value),this.state.previousRandom=v;}this.state.PushEvaluationStack(new L.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof kC.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof LC.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let r=t.containerForCount,a=this.state.VisitCountForContainer(r);n=new L.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==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."),n=new L.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof BC.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),r=t.Call(n);return this.state.PushEvaluationStack(r),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==nt.PushPopType.Function){let r="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(r="("+a.path.toString()+") "),new Error("Story was running a function "+r+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
- `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new Ql.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 n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, te.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, te.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=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 r=this.KnotContainerWithName(e);if(r==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(r,t);let s=new hn.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,l),n?{returned:l,output:o}:l}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(nt.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, te.throwNullException)("funcName");let n=this._externals.get(e),r=null,a=typeof n<"u";if(a&&!n.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&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){r=this.KnotContainerWithName(e),this.Assert(r!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(nt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Ht.Pointer.StartOf(r);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<t;++u){let h=(0, $.asOrThrows)(this.state.PopEvaluationStack(),L.Value).valueObject;s.push(h);}s.reverse();let o=n.function(s),l=null;o!=null?(l=L.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new Pi.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(e,t,n=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:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,r=>{this.Assert(r.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=r.length;s<o;s++)a[s]=this.TryCoerce(r[s]);return t.apply(null,a)},n);}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,n=arguments[1]||new Set;if(arguments[0]instanceof Pe.Container&&(e=arguments[0]),arguments[0]instanceof Xl.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let r="Error: Missing function binding for external";r+=n.size>1?"s":"",r+=": '",r+=Array.from(n).join("', '"),r+="' ",r+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(r);}else if(e!=null){for(let r of e.content){let a=r;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(r,n);}for(let[,r]of e.namedContent)this.ValidateExternalBindings((0, $.asOrNull)(r,Xl.InkObject),n);}else if(t!=null){let r=(0, $.asOrNull)(t,Ih.Divert);if(r&&r.isExternal){let a=r.targetPathString;if(a===null)return (0, te.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.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 n=0,r=e.length;n<r;n++)this.ObserveVariable(e[n],t[n]);}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 n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let r of n){let a=this._variableObservers.get(r);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(r));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof L.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let r=(0, $.asOrThrows)(t,L.Value);for(let a of n)a(e,r.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new Ql.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, te.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof Pe.Container)n=s;else break}let r=false,a=null;for(let s of n.content){let o=(0, $.asOrNull)(s,M.ControlCommand);if(o!=null)o.commandType==M.ControlCommand.CommandType.BeginTag?r=true:o.commandType==M.ControlCommand.CommandType.EndTag&&(r=false);else if(r){let l=(0, $.asOrNull)(s,L.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.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 hn.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new hn.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=Ht.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(nt.PushPopType.Function)?(this.state.PopCallStack(nt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Pi.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, te.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, $.asOrNull)(t.container.parent,Pe.Container);if(!(n instanceof Pe.Container))break;let r=n.content.indexOf(t.container);if(r==-1)break;if(t=new Ht.Pointer(n,r),t.index++,e=true,t.container===null)return (0, te.throwNullException)("pointer.container")}return e||(t=Ht.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(r=>r.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, te.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, te.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, $.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, te.throwNullException)("seqContainer");if(e.value===null)return (0, te.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, $.asOrThrows)(this.state.PopEvaluationStack(),L.IntValue).value;if(a===null)return (0, te.throwNullException)("seqCount");let s=a/n,o=a%n,l=t.path.toString(),u=0;for(let d=0,g=l.length;d<g;d++)u+=l.charCodeAt(d)||0;let c=u+s+this.state.storySeed,h=new Zl.PRNG(Math.floor(c)),f=[];for(let d=0;d<n;++d)f.push(d);for(let d=0;d<=o;++d){let g=h.next()%f.length,y=f[g];if(f.splice(g,1),d==o)return y}throw new Error("Should never reach here")}Error(e,t=false){let n=new cn.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let r=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(r!=null){let s=n?r.endLineNumber:r.startLineNumber;e="RUNTIME "+a+": '"+r.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 n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};pn.Story=Wn;Wn.inkVersionCurrent=21;(function(i){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(i.OutputStateChange||(i.OutputStateChange={}));})(Wn||(pn.Story=Wn={}));});var Lh=P(ca=>{Object.defineProperty(ca,"__esModule",{value:true});ca.Story=void 0;var MC=ir(),$C=Mr(),aa=Ce(),oa=Oe(),Ni=en(),la=yt(),kh=Pn(),GC=El(),HC=ys(),JC=wl(),UC=xi(),jn=wt(),zC=qt(),KC=Wt(),Ii=ie(),XC=mi(),YC=Ci(),QC=on(),ua=class i extends la.FlowBase{get flowLevel(){return kh.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=(n=null)=>{var r,a;this._errorHandler=n,this.constants=new Map;for(let c of this.FindAll($C.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(HC.ListDefinition)())!((r=c.identifier)===null||r===void 0)&&r.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 aa.Container;o.AddContent(oa.ControlCommand.EvalStart());let l=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),l.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let f=new KC.VariableAssignment(c,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(oa.ControlCommand.EvalEnd()),o.AddContent(oa.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(oa.ControlCommand.Done());let u=new UC.Story(s,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let r=this._listDefs.get(n);return r||null},this.ResolveListItem=(n,r,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.ItemNamed(r):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let c=u.ItemNamed(r);c&&(o?this.Error(`Ambiguous item name '${r}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=c,l=u));}return o}},this.FlattenContainersIn=n=>{let r=new Set;if(n.content)for(let a of n.content){let s=(0, Ii.asOrNull)(a,aa.Container);s&&r.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, Ii.asOrNull)(a,aa.Container);s&&r.add(s);}for(let a of r)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let r=(0, Ii.asOrNull)(n.parent,aa.Container);if(r){let a=r.content.indexOf(n);r.content.splice(a,1);let s=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),r.InsertContent(o,a),a+=1;}},this.Error=(n,r,a)=>{let s=a?Ni.ErrorType.Warning:Ni.ErrorType.Error,o="";if(r instanceof MC.AuthorWarning?(o+="TODO: ",s=Ni.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",r&&r.debugMetadata!==null&&r.debugMetadata.startLineNumber>=1&&(r.debugMetadata.fileName!=null&&(o+=`'${r.debugMetadata.fileName}' `),o+=`line ${r.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,s);else throw new Error(n);this._hadError=s===Ni.ErrorType.Error,this._hadWarning=s===Ni.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,r,a,s)=>{n.Error(`${s} '${r}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,r,a,s="")=>{var o;let l=s||n.typeName;if(i.IsReservedKeyword(r?.name)){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(YC.FunctionCall.IsBuiltIn(r?.name||"")){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(r?.name||"",kh.FlowLevel.Knot),c=(0, Ii.asOrNull)(u,la.FlowBase);if(c&&(c!==n||a===jn.SymbolType.Arg)){this.NameConflictError(n,r?.name||"",c,l);return}if(a<jn.SymbolType.List)return;for(let[g,y]of this._listDefs)if(r?.name===g&&n!==y&&y.variableAssignment!==n&&this.NameConflictError(n,r?.name,y,l),!(n instanceof JC.ListElementDefinition))for(let _ of y.itemDefinitions)r?.name===_.name&&this.NameConflictError(n,r?.name||"",_,l);if(a<=jn.SymbolType.Var)return;let h=r?.name&&this.variableDeclarations.get(r?.name)||null;if(h&&h!==n&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(n,r?.name||"",h,l),a<jn.SymbolType.SubFlowAndWeave)return;let d=new QC.Path(r).ResolveFromContext(n);if(d&&d!==n){this.NameConflictError(n,r?.name||"",d,l);return}if(!(a<jn.SymbolType.Arg)&&a!==jn.SymbolType.Arg){let g=(0, Ii.asOrNull)(n,la.FlowBase);if(g||(g=(0, XC.ClosestFlowBase)(n)),g&&g.hasParameters&&g.args){for(let y of g.args)if(((o=y.identifier)===null||o===void 0?void 0:o.name)===r?.name){n.Error(`${l} '${r}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof GC.IncludedFile){let r=n,a=e.indexOf(n);if(e.splice(a,1),r.includedStory){let s=[],o=r.includedStory;if(o.content!=null){for(let l of o.content)l instanceof la.FlowBase?t.push(l):s.push(l);s.push(new zC.Text(`
29
- `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};ca.Story=ua;ua.IsReservedKeyword=i=>{switch(i){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 Wh=P(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.StringExpression=void 0;var Bh=Oe(),ZC=Ye(),ey=qt(),ty=ie(),eu=class i extends ZC.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof ey.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Bh.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Bh.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, ty.asOrNull)(e,i);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),r=t.toString();return n===r}};ha.StringExpression=eu;});var qh=P(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.LegacyTag=qn.Tag=void 0;var ny=he(),jh=Oe(),tu=class extends ny.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?jh.ControlCommand.BeginTag():jh.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};qn.Tag=tu;var iy=ml(),nu=class extends iy.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};qn.LegacyTag=nu;});var Mh=P(pa=>{Object.defineProperty(pa,"__esModule",{value:true});pa.DefaultFileHandler=void 0;var iu=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.")};}};pa.DefaultFileHandler=iu;});var ou=P(ma=>{Object.defineProperty(ma,"__esModule",{value:true});ma.InkParser=void 0;var ry=hc(),sy=ir(),ay=co(),ot=Dc(),xe=hi(),oy=Tn(),ly=Ic(),uy=Wr(),Ri=Ho(),He=Zr(),cy=Mr(),fa=th(),hy=nh(),fn=In(),ru=Nn(),py=Ye(),fy=ih(),$h=rh(),da=Ci(),dy=gi(),gy=sh(),my=Ns(),ga=oh(),Gh=El(),Cy=lh(),yy=Dl(),Hh=ch(),vy=ys(),Sy=wl(),Ey=qo(),Jh=he(),by=on(),Uh=No(),zh=el(),De=Yo(),Re=Ol(),Ay=Pl(),Kh=Lh(),Vi=Wh(),Ot=bo(),Mn=qh(),Tt=qt(),Xh=nl(),su=ll(),au=Vn(),Dy=lo(),Jt=ie(),ki=Xr(),$n=vr(),Yh=en(),xy=Mh(),ae=class i extends Ot.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,n=null,r=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(Re.StatementLevel.Top);return new Kh.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let l=this.Parse(s);if(l===null)return null;let u=[];u.push(l);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),u.push(f);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new hy.DebugMetadata;return l.startLineNumber=(s?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(s?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(s,o,l)=>{let u=(0, Jt.asOrNull)(s,Jh.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let c=Array.isArray(s)?s:null;if(c!==null)for(let f of c)(0, Jt.asOrNull)(f,Jh.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let h=(0, Jt.asOrNull)(s,ki.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(s,o,l=0,u=false)=>{let h=u?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${l+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,u?Yh.ErrorType.Warning:Yh.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(`
30
- \r`);return o?new sy.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=i.ListAllCharacterRanges();for(let l of o)s.AddCharacters(l.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 l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=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 He.ContentList(h));let f=null,d=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(c);let m=this.Parse(this.MixedTextAndLogic);m!==null&&(f=new He.ContentList(m)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let p=this.Parse(this.MixedTextAndLogic);p!==null&&(d=new He.ContentList(p));}this.Whitespace(),this.EndTagIfNecessary(d??c);let y=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let _=!c&&!d&&!f;if(_&&y===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),d||(d=new He.ContentList),this.EndTagIfNecessary(d),y!==null)for(let m of y){let p=(0, Jt.asOrNull)(m,fn.Divert);p&&p.isEmpty||d.AddContent(m);}d.AddContent(new Tt.Text(`
31
- `));let D=new oy.Choice(c,f,d);return l&&(D.identifier=l),D.indentationDepth=o.length,D.hasWeaveStyleInlineBrackets=g,D.condition=u,D.onceOnly=s,D.isInvisibleDefault=_,D},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new Ey.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Ot.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),l=this.Parse(this.BracketedName),u=new dy.Gather(l,o);return this.Newline(),u},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,l=s!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel(Re.StatementLevel.InnerBlock);if(h!==null){o=[new Ri.ConditionalSingleBranch(h)];let d=this.Parse(this.SingleMultilineCondition);d&&(d.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",d),d.isElse=true),o.push(d));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Ri.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let f=0;f<o.length;++f){let d=o[f],g=f===o.length-1;d.ownExpression?(d.matchingEquality=true,h=true):h&&g?(d.matchingEquality=true,d.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",d):f===0?d.isTrueBranch=true:d.isElse=true;}}else {for(let h=0;h<o.length;++h){let f=o[h],d=h===o.length-1;if(f.ownExpression===null)if(d)f.isElse=true;else if(f.isElse){let g=o[o.length-1];g.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",g):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let h of o)h.isInline=u;return new uy.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 l=new Ri.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new Ri.ConditionalSingleBranch(s[1]);u.isElse=true,o.push(u);}}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 l=this.StatementsAtLevel(Re.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new Tt.Text("")]),this.MultilineWhitespace();let u=new Ri.ConditionalSingleBranch(l);return u.ownExpression=s,u.isElse=o,u},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:Ot.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let l=s.length-1,u=s[l];if(u instanceof Tt.Text){let c=u;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(l,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof fn.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Mn.Tag&&s[0].isStart||s.push(new Tt.Text(`
32
- `)),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 l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),l){let u=this.ParseSingleCharacter();s+=u;}}else break}while(true);return s!==null?new Tt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new xe.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new xe.CharacterSet(`{}|
33
- \r\\#`),this._notTextEndCharactersChoice=new xe.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new xe.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 l=this.ParseUntil(s,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;s=[],this.EndTagIfNecessary(s);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new Xh.TunnelOnwards;if(u<l.length-1){let d=(0, Jt.asOrNull)(l[u+1],fn.Divert);f.divertAfter=d;}s.push(f);break}}else {let h=l[u];u<l.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&l.length===1){let u=new fn.Divert(null);u.isEmpty=true,s.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new fn.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new by.Path(s);return new fn.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof Xh.TunnelOnwards)return null;let l=s[0];return l.isTunnel?null:l},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 l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&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 l||u?new ga.IncDecExpression(o,c,l):new su.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof ga.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 Uh.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>s){let c=`right side of '${u.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,u),c);if(h===null)return this.FailRule(l),null;o=this.SucceedRule(l,h);continue}this.FailRule(l);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 l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=Dy.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let c=u==="++";if(!(l instanceof au.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let h=l;l=new ga.IncDecExpression(h.identifier,c);}}return l},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 ru.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new $n.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new $n.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 Tt.Text("")]:o.find(l=>l instanceof fn.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Vi.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new $n.NumberExpression(true,"bool"):s==="false"?new $n.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 da.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||Kh.Story.IsReservedKeyword(s[0].name)?null:new au.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 l=this.Parse(()=>this.Expression(o.precedence));return l?new ay.BinaryExpression(s,l,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 Hh.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${l?.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,l=false)=>{let u=new Cy.InfixOperator(s,o,l);this._binaryOperators.push(u),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(`
24
+ `)a==-1&&(a=c),s=c;else {if(h==" "||h==" ")continue;break}}if(n==-1&&a==-1)return null;let o=[],l=0,u=t.length;if(n!=-1){if(n>0){let c=new De.StringValue(t.substring(0,n));o.push(c);}o.push(new De.StringValue(`
25
+ `)),l=r+1;}if(a!=-1&&(u=s),u>l){let c=t.substring(l,u);o.push(new De.StringValue(c));}if(a!=-1&&s>r&&(o.push(new De.StringValue(`
26
+ `)),a<t.length-1)){let c=t.length-a-1,h=new De.StringValue(t.substring(a+1,a+1+c));o.push(h);}return o}PushToOutputStreamIndividual(e){let t=(0, Ee.asOrNull)(e,zl.Glue),n=(0, Ee.asOrNull)(e,De.StringValue),r=true;if(t)this.TrimNewlinesFromOutputStream(),r=true;else if(n){let a=-1,s=this.callStack.currentElement;s.type==$t.PushPopType.Function&&(a=s.functionStartInOutputStream);let o=-1;for(let u=this.outputStream.length-1;u>=0;u--){let c=this.outputStream[u],h=c instanceof Ve.ControlCommand?c:null;if((c instanceof zl.Glue?c:null)!=null){o=u;break}else if(h!=null&&h.commandType==Ve.ControlCommand.CommandType.BeginString){u>=a&&(a=-1);break}}let l=-1;if(o!=-1&&a!=-1?l=Math.min(a,o):o!=-1?l=o:l=a,l!=-1){if(n.isNewline)r=false;else if(n.isNonWhitespace&&(o>-1&&this.RemoveExistingGlue(),a>-1)){let u=this.callStack.elements;for(let c=u.length-1;c>=0;c--){let h=u[c];if(h.type==$t.PushPopType.Function)h.functionStartInOutputStream=-1;else break}}}else n.isNewline&&(this.outputStreamEndsInNewline||!this.outputStreamContainsContent)&&(r=false);}if(r){if(e===null)return (0, tt.throwNullException)("obj");this.outputStream.push(e),this.OutputStreamDirty();}}TrimNewlinesFromOutputStream(){let e=-1,t=this.outputStream.length-1;for(;t>=0;){let n=this.outputStream[t],r=(0, Ee.asOrNull)(n,Ve.ControlCommand),a=(0, Ee.asOrNull)(n,De.StringValue);if(r!=null||a!=null&&a.isNonWhitespace)break;a!=null&&a.isNewline&&(e=t),t--;}if(e>=0)for(t=e;t<this.outputStream.length;)(0, Ee.asOrNull)(this.outputStream[t],De.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 zl.Glue)this.outputStream.splice(e,1);else if(t instanceof Ve.ControlCommand)break}this.OutputStreamDirty();}get outputStreamEndsInNewline(){if(this.outputStream.length>0)for(let e=this.outputStream.length-1;e>=0&&!(this.outputStream[e]instanceof Ve.ControlCommand);e--){let n=this.outputStream[e];if(n instanceof De.StringValue){if(n.isNewline)return true;if(n.isNonWhitespace)break}}return false}get outputStreamContainsContent(){for(let e of this.outputStream)if(e instanceof De.StringValue)return true;return false}get inStringEvaluation(){for(let e=this.outputStream.length-1;e>=0;e--){let t=(0, Ee.asOrNull)(this.outputStream[e],Ve.ControlCommand);if(t instanceof Ve.ControlCommand&&t.commandType==Ve.ControlCommand.CommandType.BeginString)return true}return false}PushEvaluationStack(e){let t=(0, Ee.asOrNull)(e,De.ListValue);if(t){let n=t.value;if(n===null)return (0, tt.throwNullException)("rawList");if(n.originNames!=null){n.origins||(n.origins=[]),n.origins.length=0;for(let r of n.originNames){if(this.story.listDefinitions===null)return (0, tt.throwNullException)("StoryState.story.listDefinitions");let a=this.story.listDefinitions.TryListGetDefinition(r,null);if(a.result===null)return (0, tt.throwNullException)("StoryState def.result");n.origins.indexOf(a.result)<0&&n.origins.push(a.result);}}}if(e===null)return (0, tt.throwNullException)("obj");this.evaluationStack.push(e);}PopEvaluationStack(e){if(typeof e>"u"){let t=this.evaluationStack.pop();return (0, Ee.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, Ee.nullIfUndefined)(t)}}PeekEvaluationStack(){return this.evaluationStack[this.evaluationStack.length-1]}ForceEnd(){this.callStack.Reset(),this._currentFlow.currentChoices.length=0,this.currentPointer=Bn.Pointer.Null,this.previousPointer=Bn.Pointer.Null,this.didSafeExit=true;}TrimWhitespaceFromFunctionEnd(){TC.Debug.Assert(this.callStack.currentElement.type==$t.PushPopType.Function);let e=this.callStack.currentElement.functionStartInOutputStream;e==-1&&(e=0);for(let t=this.outputStream.length-1;t>=e;t--){let n=this.outputStream[t],r=(0, Ee.asOrNull)(n,De.StringValue),a=(0, Ee.asOrNull)(n,Ve.ControlCommand);if(r!=null){if(a)break;if(r.isNewline||r.isInlineWhitespace)this.outputStream.splice(t,1),this.OutputStreamDirty();else break}}}PopCallStack(e=null){this.callStack.currentElement.type==$t.PushPopType.Function&&this.TrimWhitespaceFromFunctionEnd(),this.callStack.Pop(e);}SetChosenPath(e,t){this._currentFlow.currentChoices.length=0;let n=this.story.PointerAtPath(e);!n.isNull&&n.index==-1&&(n.index=0),this.currentPointer=n,t&&this.currentTurnIndex++;}StartFunctionEvaluationFromGame(e,t){this.callStack.Push($t.PushPopType.FunctionEvaluationFromGame,this.evaluationStack.length),this.callStack.currentElement.currentPointer=Bn.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 NC.InkList))throw new Error("ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must benumber, string, bool or InkList. Argument was "+((0, Ee.nullIfUndefined)(e[t])===null?"null":e[t].constructor.name));this.PushEvaluationStack(De.Value.Create(e[t]));}}TryExitFunctionEvaluationFromGame(){return this.callStack.currentElement.type==$t.PushPopType.FunctionEvaluationFromGame?(this.currentPointer=Bn.Pointer.Null,this.didSafeExit=true,true):false}CompleteFunctionEvaluationFromGame(){if(this.callStack.currentElement.type!=$t.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 n=this.PopEvaluationStack();t===null&&(t=n);}if(this.PopCallStack($t.PushPopType.FunctionEvaluationFromGame),t){if(t instanceof OC.Void)return null;let n=(0, Ee.asOrThrows)(t,De.Value);return n.valueType==De.ValueType.DivertTarget?"-> "+n.valueObject.toString():n.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;}};ia.StoryState=Xl;});var Fh=T(ra=>{Object.defineProperty(ra,"__esModule",{value:true});ra.Stopwatch=void 0;var Yl=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;}};ra.Stopwatch=Yl;});var Ih=T(sa=>{Object.defineProperty(sa,"__esModule",{value:true});sa.ErrorType=void 0;var Nh;(function(i){i[i.Author=0]="Author",i[i.Warning=1]="Warning",i[i.Error=2]="Error";})(Nh||(sa.ErrorType=Nh={}));});var xi=T(pn=>{Object.defineProperty(pn,"__esModule",{value:true});pn.Story=pn.InkList=void 0;var Ne=ye(),Ql=je(),Zl=Ln(),IC=Ph(),$=Pe(),nt=sn(),RC=_r(),VC=Vl(),Rh=Ct(),L=de(),eu=We(),Pi=rn(),aa=$s(),kC=Wt(),LC=Rn(),BC=mt(),cn=ni(),tu=Gl(),hn=tn(),WC=Ll(),jC=Fh(),Ht=fi(),Fi=Me(),H=ne(),te=Te(),Vh=Jl(),kh=Ih(),qC=Me();Object.defineProperty(pn,"InkList",{enumerable:true,get:function(){return qC.InkList}});Number.isInteger||(Number.isInteger=function(e){return typeof e=="number"&&isFinite(e)&&e>-9007199254740992&&e<9007199254740992&&Math.floor(e)===e});var Wn=class i extends Ql.InkObject{get currentChoices(){let e=[];if(this._state===null)return (0, te.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,n=null;if(arguments[0]instanceof Ne.Container)e=arguments[0],typeof arguments[1]<"u"&&(t=arguments[1]),this._mainContentContainer=e;else if(typeof arguments[0]=="string"){let r=arguments[0];n=Vh.SimpleJson.TextToDictionary(r);}else n=arguments[0];if(t!=null&&(this._listDefinitions=new WC.ListDefinitionsOrigin(t)),this._externals=new Map,n!==null){let r=n,a=r.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>i.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!=i.inkVersionCurrent&&console.warn(`WARNING: Version of ink ${i.inkVersionCurrent} used to build story doesn't match current version of engine (${s}). Non-critical, but recommend synchronising.`);let o=r.root;if(o==null)throw new Error("Root node for ink not found. Are you sure it's a valid .ink.json file?");let l;(l=r.listDefs)&&(this._listDefinitions=Zl.JsonSerialisation.JTokenToListDefinitions(l)),this._mainContentContainer=(0, H.asOrThrows)(Zl.JsonSerialisation.JTokenToRuntimeObject(o),Ne.Container),this.ResetState();}}ToJson(e){let t=false;if(e||(t=true,e=new Vh.SimpleJson.Writer),e.WriteObjectStart(),e.WriteIntProperty("inkVersion",i.inkVersionCurrent),e.WriteProperty("root",n=>Zl.JsonSerialisation.WriteRuntimeContainer(n,this._mainContentContainer)),this._listDefinitions!=null){e.WritePropertyStart("listDefs"),e.WriteObjectStart();for(let n of this._listDefinitions.lists){e.WritePropertyStart(n.name),e.WriteObjectStart();for(let[r,a]of n.items){let s=Fi.InkListItem.fromSerializedKey(r),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 IC.StoryState(this),this._state.variablesState.ObserveVariableChange(this.VariableStateDidChangeEvent.bind(this)),this.ResetGlobals();}ResetErrors(){if(this._state===null)return (0, te.throwNullException)("this._state");this._state.ResetErrors();}ResetCallstack(){if(this.IfAsyncWeCant("ResetCallstack"),this._state===null)return (0, te.throwNullException)("this._state");this._state.ForceEnd();}ResetGlobals(){if(this._mainContentContainer.namedContent.get("global decl")){let e=this.state.currentPointer.copy();this.ChoosePath(new eu.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 n=new jC.Stopwatch;n.Start();let r=false;this._sawLookaheadUnsafeFunctionAfterNewline=false;do{try{r=this.ContinueSingleStep();}catch(s){if(!(s instanceof cn.StoryException))throw s;this.AddError(s.message,void 0,s.useEndLineNumber);break}if(r||this._asyncContinueActive&&n.ElapsedMilliseconds>e)break}while(this.canContinue);n.Stop();let a=null;if((r||!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(nt.PushPopType.Tunnel)?this.AddError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"):this.state.callStack.CanPop(nt.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,kh.ErrorType.Error);if(this.state.hasWarning)for(let s of this.state.currentWarnings)this.onError(s,kh.ErrorType.Warning);this.ResetErrors();}else {let s=new hn.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 cn.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, te.throwNullException)("this._stateAtLastNewline.currentTags");if(this.state.currentTags===null)return (0, te.throwNullException)("this.state.currentTags");let e=this.CalculateNewlineOutputStateChange(this._stateSnapshotAtLastNewline.currentText,this.state.currentText,this._stateSnapshotAtLastNewline.currentTags.length,this.state.currentTags.length);if(e==i.OutputStateChange.ExtendedBeyondNewline||this._sawLookaheadUnsafeFunctionAfterNewline)return this.RestoreStateSnapshot(),true;e==i.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,n,r){if(e===null)return (0, te.throwNullException)("prevText");if(t===null)return (0, te.throwNullException)("currText");let a=t.length>=e.length&&e.length>0&&t.charAt(e.length-1)==`
27
+ `;if(n==r&&e.length==t.length&&a)return i.OutputStateChange.NoChange;if(!a)return i.OutputStateChange.NewlineRemoved;if(r>n)return i.OutputStateChange.ExtendedBeyondNewline;for(let s=e.length;s<t.length;s++){let o=t.charAt(s);if(o!=" "&&o!=" ")return i.OutputStateChange.ExtendedBeyondNewline}return i.OutputStateChange.NoChange}ContinueMaximally(){this.IfAsyncWeCant("ContinueMaximally");let e=new hn.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 Ne.Container?t:null}PointerAtPath(e){if(e.length==0)return Ht.Pointer.Null;let t=new Ht.Pointer,n=e.length,r=null;return e.lastComponent===null?(0, te.throwNullException)("path.lastComponent"):(e.lastComponent.isIndex?(n=e.length-1,r=this.mainContentContainer.ContentAtPath(e,void 0,n),t.container=r.container,t.index=e.lastComponent.index):(r=this.mainContentContainer.ContentAtPath(e),t.container=r.container,t.index=-1),r.obj==null||r.obj==this.mainContentContainer&&n>0?this.Error("Failed to find content at path '"+e+"', and no approximation of it was possible."):r.approximate&&this.Warning("Failed to find content at path '"+e+"', so it was approximated to: '"+r.obj.path+"'."),t)}StateSnapshot(){this._stateSnapshotAtLastNewline=this._state,this._state=this._state.CopyAndStartPatching(false);}RestoreStateSnapshot(){this._stateSnapshotAtLastNewline===null&&(0, te.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 n=(0, H.asOrNull)(t.Resolve(),Ne.Container);for(;n&&(this.VisitContainer(n,true),n.content.length!=0);)t=Ht.Pointer.StartOf(n),n=(0, H.asOrNull)(t.Resolve(),Ne.Container);this.state.currentPointer=t.copy(),this._profiler!=null&&this._profiler.Step(this.state.callStack);let r=t.Resolve(),a=this.PerformLogicAndFlowControl(r);if(this.state.currentPointer.isNull)return;a&&(e=false);let s=(0, H.asOrNull)(r,RC.ChoicePoint);if(s){let l=this.ProcessChoice(s);l&&this.state.generatedChoices.push(l),r=null,e=false;}if(r instanceof Ne.Container&&(e=false),e){let l=(0, H.asOrNull)(r,L.VariablePointerValue);if(l&&l.contextIndex==-1){let u=this.state.callStack.ContextForVariableNamed(l.variableName);r=new L.VariablePointerValue(l.variableName,u);}this.state.inExpressionEvaluation?this.state.PushEvaluationStack(r):this.state.PushToOutputStream(r);}this.NextContent();let o=(0, H.asOrNull)(r,$.ControlCommand);o&&o.commandType==$.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, H.asOrNull)(s,Ne.Container)||(0, H.asOrNull)(e.container,Ne.Container);for(;o;)this._prevContainers.push(o),o=(0, H.asOrNull)(o.parent,Ne.Container);}let n=t.Resolve();if(n==null)return;let r=(0, H.asOrNull)(n.parent,Ne.Container),a=true;for(;r&&(this._prevContainers.indexOf(r)<0||r.countingAtStartOnly);){let s=r.content.length>0&&n==r.content[0]&&a;s||(a=false),this.VisitContainer(r,s),n=r,r=(0, H.asOrNull)(r.parent,Ne.Container);}}PopChoiceStringAndTags(e){let t=(0, H.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);for(;this.state.evaluationStack.length>0&&(0, H.asOrNull)(this.state.PeekEvaluationStack(),aa.Tag)!=null;){let n=(0, H.asOrNull)(this.state.PopEvaluationStack(),aa.Tag);n&&e.push(n.text);}return t.value}ProcessChoice(e){let t=true;if(e.hasCondition){let o=this.state.PopEvaluationStack();this.IsTruthy(o)||(t=false);}let n="",r="",a=[];if(e.hasChoiceOnlyContent&&(r=this.PopChoiceStringAndTags(a)||""),e.hasStartContent&&(n=this.PopChoiceStringAndTags(a)||""),e.onceOnly&&this.state.VisitCountForContainer(e.choiceTarget)>0&&(t=false),!t)return null;let s=new VC.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=(n+r).replace(/^[ \t]+|[ \t]+$/g,""),s}IsTruthy(e){let t=false;if(e instanceof L.Value){let n=e;if(n instanceof L.DivertTargetValue){let r=n;return this.Error("Shouldn't use a divert target (to "+r.targetPath+") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"),false}return n.isTruthy}return t}PerformLogicAndFlowControl(e){if(e==null)return false;if(e instanceof Rh.Divert){let t=e;if(t.isConditional){let n=this.state.PopEvaluationStack();if(!this.IsTruthy(n))return true}if(t.hasVariableTarget){let n=t.variableDivertName,r=this.state.variablesState.GetVariableWithName(n);if(r==null)this.Error("Tried to divert using a target from a variable that could not be found ("+n+")");else if(!(r instanceof L.DivertTargetValue)){let s=(0, H.asOrNull)(r,L.IntValue),o="Tried to divert to a target from a variable, but the variable ("+n+") didn't contain a divert target, it ";s instanceof L.IntValue&&s.value==0?o+="was empty/null (the value 0).":o+="contained '"+r+"'.",this.Error(o);}let a=(0, H.asOrThrows)(r,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 $.ControlCommand){let t=e;switch(t.commandType){case $.ControlCommand.CommandType.EvalStart:this.Assert(this.state.inExpressionEvaluation===false,"Already in expression evaluation?"),this.state.inExpressionEvaluation=true;break;case $.ControlCommand.CommandType.EvalEnd:this.Assert(this.state.inExpressionEvaluation===true,"Not in expression evaluation mode"),this.state.inExpressionEvaluation=false;break;case $.ControlCommand.CommandType.EvalOutput:if(this.state.evaluationStack.length>0){let C=this.state.PopEvaluationStack();if(!(C instanceof Pi.Void)){let S=new L.StringValue(C.toString());this.state.PushToOutputStream(S);}}break;case $.ControlCommand.CommandType.NoOp:break;case $.ControlCommand.CommandType.Duplicate:this.state.PushEvaluationStack(this.state.PeekEvaluationStack());break;case $.ControlCommand.CommandType.PopEvaluatedValue:this.state.PopEvaluationStack();break;case $.ControlCommand.CommandType.PopFunction:case $.ControlCommand.CommandType.PopTunnel:let n=t.commandType==$.ControlCommand.CommandType.PopFunction?nt.PushPopType.Function:nt.PushPopType.Tunnel,r=null;if(n==nt.PushPopType.Tunnel){let C=this.state.PopEvaluationStack();r=(0, H.asOrNull)(C,L.DivertTargetValue),r===null&&this.Assert(C instanceof Pi.Void,"Expected void if ->-> doesn't override target");}if(this.state.TryExitFunctionEvaluationFromGame())break;if(this.state.callStack.currentElement.type!=n||!this.state.callStack.canPop){let C=new Map;C.set(nt.PushPopType.Function,"function return statement (~ return)"),C.set(nt.PushPopType.Tunnel,"tunnel onwards statement (->->)");let S=C.get(this.state.callStack.currentElement.type);this.state.callStack.canPop||(S="end of flow (-> END or choice)");let w="Found "+C.get(n)+", when expected "+S;this.Error(w);}else this.state.PopCallStack(),r&&(this.state.divertedPointer=this.PointerAtPath(r.targetPath));break;case $.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 $.ControlCommand.CommandType.BeginTag:this.state.PushToOutputStream(t);break;case $.ControlCommand.CommandType.EndTag:{if(this.state.inStringEvaluation){let C=[],S=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let v=this.state.outputStream[x];S++;let I=(0, H.asOrNull)(v,$.ControlCommand);if(I!=null){if(I.commandType==$.ControlCommand.CommandType.BeginTag)break;this.Error("Unexpected ControlCommand while extracting tag from choice");break}v instanceof L.StringValue&&C.push(v);}this.state.PopFromOutputStream(S);let w=new hn.StringBuilder;for(let x of C.reverse())w.Append(x.toString());let P=new aa.Tag(this.state.CleanOutputWhitespace(w.toString()));this.state.PushEvaluationStack(P);}else this.state.PushToOutputStream(t);break}case $.ControlCommand.CommandType.EndString:{let C=[],S=[],w=0;for(let x=this.state.outputStream.length-1;x>=0;--x){let v=this.state.outputStream[x];w++;let I=(0, H.asOrNull)(v,$.ControlCommand);if(I&&I.commandType==$.ControlCommand.CommandType.BeginString)break;v instanceof aa.Tag&&S.push(v),v instanceof L.StringValue&&C.push(v);}this.state.PopFromOutputStream(w);for(let x of S)this.state.PushToOutputStream(x);C=C.reverse();let P=new hn.StringBuilder;for(let x of C)P.Append(x.toString());this.state.inExpressionEvaluation=true,this.state.PushEvaluationStack(new L.StringValue(P.toString()));break}case $.ControlCommand.CommandType.ChoiceCount:let a=this.state.generatedChoices.length;this.state.PushEvaluationStack(new L.IntValue(a));break;case $.ControlCommand.CommandType.Turns:this.state.PushEvaluationStack(new L.IntValue(this.state.currentTurnIndex+1));break;case $.ControlCommand.CommandType.TurnsSince:case $.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, H.asOrThrows)(s,L.DivertTargetValue),l=(0, H.asOrNull)(this.ContentAtPath(o.targetPath).correctObj,Ne.Container),u;l!=null?t.commandType==$.ControlCommand.CommandType.TurnsSince?u=this.state.TurnsSinceForContainer(l):u=this.state.VisitCountForContainer(l):(t.commandType==$.ControlCommand.CommandType.TurnsSince?u=-1:u=0,this.Warning("Failed to find container for "+t.toString()+" lookup at "+o.targetPath.toString())),this.state.PushEvaluationStack(new L.IntValue(u));break;case $.ControlCommand.CommandType.Random:{let C=(0, H.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),S=(0, H.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, te.throwNullException)("maxInt.value");if(S.value===null)return (0, te.throwNullException)("minInt.value");let w=C.value-S.value+1;(!isFinite(w)||w>Number.MAX_SAFE_INTEGER)&&(w=Number.MAX_SAFE_INTEGER,this.Error("RANDOM was called with a range that exceeds the size that ink numbers can use.")),w<=0&&this.Error("RANDOM was called with minimum as "+S.value+" and maximum as "+C.value+". The maximum must be larger");let P=this.state.storySeed+this.state.previousRandom,v=new tu.PRNG(P).next(),I=v%w+S.value;this.state.PushEvaluationStack(new L.IntValue(I)),this.state.previousRandom=v;break}case $.ControlCommand.CommandType.SeedRandom:let c=(0, H.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, te.throwNullException)("minInt.value");this.state.storySeed=c.value,this.state.previousRandom=0,this.state.PushEvaluationStack(new Pi.Void);break;case $.ControlCommand.CommandType.VisitIndex:let h=this.state.VisitCountForContainer(this.state.currentPointer.container)-1;this.state.PushEvaluationStack(new L.IntValue(h));break;case $.ControlCommand.CommandType.SequenceShuffleIndex:let f=this.NextSequenceShuffleIndex();this.state.PushEvaluationStack(new L.IntValue(f));break;case $.ControlCommand.CommandType.StartThread:break;case $.ControlCommand.CommandType.Done:this.state.callStack.canPopThread?this.state.callStack.PopThread():(this.state.didSafeExit=true,this.state.currentPointer=Ht.Pointer.Null);break;case $.ControlCommand.CommandType.End:this.state.ForceEnd();break;case $.ControlCommand.CommandType.ListFromInt:let d=(0, H.asOrNull)(this.state.PopEvaluationStack(),L.IntValue),g=(0, H.asOrThrows)(this.state.PopEvaluationStack(),L.StringValue);if(d===null)throw new cn.StoryException("Passed non-integer when creating a list element from a numerical value.");let y=null;if(this.listDefinitions===null)return (0, te.throwNullException)("this.listDefinitions");let _=this.listDefinitions.TryListGetDefinition(g.value,null);if(_.exists){if(d.value===null)return (0, te.throwNullException)("minInt.value");let C=_.result.TryGetItemWithValue(d.value,Fi.InkListItem.Null);C.exists&&(y=new L.ListValue(C.result,d.value));}else throw new cn.StoryException("Failed to find LIST called "+g.value);y==null&&(y=new L.ListValue),this.state.PushEvaluationStack(y);break;case $.ControlCommand.CommandType.ListRange:let D=(0, H.asOrNull)(this.state.PopEvaluationStack(),L.Value),m=(0, H.asOrNull)(this.state.PopEvaluationStack(),L.Value),p=(0, H.asOrNull)(this.state.PopEvaluationStack(),L.ListValue);if(p===null||m===null||D===null)throw new cn.StoryException("Expected list, minimum and maximum for LIST_RANGE");if(p.value===null)return (0, te.throwNullException)("targetList.value");let E=p.value.ListWithSubRange(m.valueObject,D.valueObject);this.state.PushEvaluationStack(new L.ListValue(E));break;case $.ControlCommand.CommandType.ListRandom:{let C=this.state.PopEvaluationStack();if(C===null)throw new cn.StoryException("Expected list for LIST_RANDOM");let S=C.value,w=null;if(S===null)throw (0, te.throwNullException)("list");if(S.Count==0)w=new Fi.InkList;else {let P=this.state.storySeed+this.state.previousRandom,v=new tu.PRNG(P).next(),I=v%S.Count,V=S.entries();for(let A=0;A<=I-1;A++)V.next();let R=V.next().value,b={Key:Fi.InkListItem.fromSerializedKey(R[0]),Value:R[1]};if(b.Key.originName===null)return (0, te.throwNullException)("randomItem.Key.originName");w=new Fi.InkList(b.Key.originName,this),w.Add(b.Key,b.Value),this.state.previousRandom=v;}this.state.PushEvaluationStack(new L.ListValue(w));break}default:this.Error("unhandled ControlCommand: "+t);break}return true}else if(e instanceof kC.VariableAssignment){let t=e,n=this.state.PopEvaluationStack();return this.state.variablesState.Assign(t,n),true}else if(e instanceof LC.VariableReference){let t=e,n=null;if(t.pathForCount!=null){let r=t.containerForCount,a=this.state.VisitCountForContainer(r);n=new L.IntValue(a);}else n=this.state.variablesState.GetVariableWithName(t.name),n==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."),n=new L.IntValue(0));return this.state.PushEvaluationStack(n),true}else if(e instanceof BC.NativeFunctionCall){let t=e,n=this.state.PopEvaluationStack(t.numberOfParameters),r=t.Call(n);return this.state.PushEvaluationStack(r),true}return false}ChoosePathString(e,t=true,n=[]){if(this.IfAsyncWeCant("call ChoosePathString right now"),this.onChoosePathString!==null&&this.onChoosePathString(e,n),t)this.ResetCallstack();else if(this.state.callStack.currentElement.type==nt.PushPopType.Function){let r="",a=this.state.callStack.currentElement.currentPointer.container;throw a!=null&&(r="("+a.path.toString()+") "),new Error("Story was running a function "+r+"when you called ChoosePathString("+e+`) - this is almost certainly not not what you want! Full stack trace:
28
+ `+this.state.callStack.callStackTrace)}this.state.PassArgumentsToEvaluationStack(n),this.ChoosePath(new eu.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 n=t[e];if(this.onMakeChoice!==null&&this.onMakeChoice(n),n.threadAtGeneration===null)return (0, te.throwNullException)("choiceToChoose.threadAtGeneration");if(n.targetPath===null)return (0, te.throwNullException)("choiceToChoose.targetPath");this.state.callStack.currentThread=n.threadAtGeneration,this.ChoosePath(n.targetPath);}HasFunction(e){try{return this.KnotContainerWithName(e)!=null}catch{return false}}EvaluateFunction(e,t=[],n=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 r=this.KnotContainerWithName(e);if(r==null)throw new Error("Function doesn't exist: '"+e+"'");let a=[];a.push(...this.state.outputStream),this._state.ResetOutput(),this.state.StartFunctionEvaluationFromGame(r,t);let s=new hn.StringBuilder;for(;this.canContinue;)s.Append(this.Continue());let o=s.toString();this._state.ResetOutput(a);let l=this.state.CompleteFunctionEvaluationFromGame();return this.onCompleteEvaluateFunction!=null&&this.onCompleteEvaluateFunction(e,t,o,l),n?{returned:l,output:o}:l}EvaluateExpression(e){let t=this.state.callStack.elements.length;this.state.callStack.Push(nt.PushPopType.Tunnel),this._temporaryEvaluationContainer=e,this.state.GoToStart();let n=this.state.evaluationStack.length;return this.Continue(),this._temporaryEvaluationContainer=null,this.state.callStack.elements.length>t&&this.state.PopCallStack(),this.state.evaluationStack.length>n?this.state.PopEvaluationStack():null}CallExternalFunction(e,t){if(e===null)return (0, te.throwNullException)("funcName");let n=this._externals.get(e),r=null,a=typeof n<"u";if(a&&!n.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&&!n.lookAheadSafe&&this._stateSnapshotAtLastNewline!==null){this._sawLookaheadUnsafeFunctionAfterNewline=true;return}if(!a)if(this.allowExternalFunctionFallbacks){r=this.KnotContainerWithName(e),this.Assert(r!==null,"Trying to call EXTERNAL function '"+e+"' which has not been bound, and fallback ink function could not be found."),this.state.callStack.Push(nt.PushPopType.Function,void 0,this.state.outputStream.length),this.state.divertedPointer=Ht.Pointer.StartOf(r);return}else this.Assert(false,"Trying to call EXTERNAL function '"+e+"' which has not been bound (and ink fallbacks disabled).");let s=[];for(let u=0;u<t;++u){let h=(0, H.asOrThrows)(this.state.PopEvaluationStack(),L.Value).valueObject;s.push(h);}s.reverse();let o=n.function(s),l=null;o!=null?(l=L.Value.Create(o),this.Assert(l!==null,"Could not create ink value from returned object of type "+typeof o)):l=new Pi.Void,this.state.PushEvaluationStack(l);}BindExternalFunctionGeneral(e,t,n=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:n});}TryCoerce(e){return e}BindExternalFunction(e,t,n=false){this.Assert(t!=null,"Can't bind a null function"),this.BindExternalFunctionGeneral(e,r=>{this.Assert(r.length>=t.length,"External function expected "+t.length+" arguments");let a=[];for(let s=0,o=r.length;s<o;s++)a[s]=this.TryCoerce(r[s]);return t.apply(null,a)},n);}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,n=arguments[1]||new Set;if(arguments[0]instanceof Ne.Container&&(e=arguments[0]),arguments[0]instanceof Ql.InkObject&&(t=arguments[0]),e===null&&t===null)if(this.ValidateExternalBindings(this._mainContentContainer,n),this._hasValidatedExternals=true,n.size==0)this._hasValidatedExternals=true;else {let r="Error: Missing function binding for external";r+=n.size>1?"s":"",r+=": '",r+=Array.from(n).join("', '"),r+="' ",r+=this.allowExternalFunctionFallbacks?", and no fallback ink function found.":" (ink fallbacks disabled)",this.Error(r);}else if(e!=null){for(let r of e.content){let a=r;(a==null||!a.hasValidName)&&this.ValidateExternalBindings(r,n);}for(let[,r]of e.namedContent)this.ValidateExternalBindings((0, H.asOrNull)(r,Ql.InkObject),n);}else if(t!=null){let r=(0, H.asOrNull)(t,Rh.Divert);if(r&&r.isExternal){let a=r.targetPathString;if(a===null)return (0, te.throwNullException)("name");this._externals.has(a)||this.allowExternalFunctionFallbacks&&this.mainContentContainer.namedContent.has(a)||n.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 n=0,r=e.length;n<r;n++)this.ObserveVariable(e[n],t[n]);}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 n=this._variableObservers.get(t);n!=null&&(n.splice(n.indexOf(e),1),n.length===0&&this._variableObservers.delete(t));}else this._variableObservers.delete(t);}else if(e!=null){let n=this._variableObservers.keys();for(let r of n){let a=this._variableObservers.get(r);a!=null&&(a.splice(a.indexOf(e),1),a.length===0&&this._variableObservers.delete(r));}}}}VariableStateDidChangeEvent(e,t){if(this._variableObservers===null)return;let n=this._variableObservers.get(e);if(typeof n<"u"){if(!(t instanceof L.Value))throw new Error("Tried to get the value of a variable that isn't a standard type");let r=(0, H.asOrThrows)(t,L.Value);for(let a of n)a(e,r.valueObject);}}get globalTags(){return this.TagsAtStartOfFlowContainerWithPathString("")}TagsForContentAtPath(e){return this.TagsAtStartOfFlowContainerWithPathString(e)}TagsAtStartOfFlowContainerWithPathString(e){let t=new eu.Path(e),n=this.ContentAtPath(t).container;if(n===null)return (0, te.throwNullException)("flowContainer");for(;;){let s=n.content[0];if(s instanceof Ne.Container)n=s;else break}let r=false,a=null;for(let s of n.content){let o=(0, H.asOrNull)(s,$.ControlCommand);if(o!=null)o.commandType==$.ControlCommand.CommandType.BeginTag?r=true:o.commandType==$.ControlCommand.CommandType.EndTag&&(r=false);else if(r){let l=(0, H.asOrNull)(s,L.StringValue);l!==null?(a===null&&(a=[]),l.value!==null&&a.push(l.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 hn.StringBuilder;return this.mainContentContainer.BuildStringOfHierarchy(e,0,this.state.currentPointer.Resolve()),e.toString()}BuildStringOfContainer(e){let t=new hn.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=Ht.Pointer.Null,this.VisitChangedContainersDueToDivert(),!this.state.currentPointer.isNull))return;if(!this.IncrementContentPointer()){let t=false;this.state.callStack.CanPop(nt.PushPopType.Function)?(this.state.PopCallStack(nt.PushPopType.Function),this.state.inExpressionEvaluation&&this.state.PushEvaluationStack(new Pi.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, te.throwNullException)("pointer.container");for(;t.index>=t.container.content.length;){e=false;let n=(0, H.asOrNull)(t.container.parent,Ne.Container);if(!(n instanceof Ne.Container))break;let r=n.content.indexOf(t.container);if(r==-1)break;if(t=new Ht.Pointer(n,r),t.index++,e=true,t.container===null)return (0, te.throwNullException)("pointer.container")}return e||(t=Ht.Pointer.Null),this.state.callStack.currentElement.currentPointer=t.copy(),e}TryFollowDefaultInvisibleChoice(){let e=this._state.currentChoices,t=e.filter(r=>r.isInvisibleDefault);if(t.length==0||e.length>t.length)return false;let n=t[0];return n.targetPath===null?(0, te.throwNullException)("choice.targetPath"):n.threadAtGeneration===null?(0, te.throwNullException)("choice.threadAtGeneration"):(this.state.callStack.currentThread=n.threadAtGeneration,this._stateSnapshotAtLastNewline!==null&&(this.state.callStack.currentThread=this.state.callStack.ForkThread()),this.ChoosePath(n.targetPath,false),true)}NextSequenceShuffleIndex(){let e=(0, H.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, te.throwNullException)("seqContainer");if(e.value===null)return (0, te.throwNullException)("numElementsIntVal.value");let n=e.value,a=(0, H.asOrThrows)(this.state.PopEvaluationStack(),L.IntValue).value;if(a===null)return (0, te.throwNullException)("seqCount");let s=a/n,o=a%n,l=t.path.toString(),u=0;for(let d=0,g=l.length;d<g;d++)u+=l.charCodeAt(d)||0;let c=u+s+this.state.storySeed,h=new tu.PRNG(Math.floor(c)),f=[];for(let d=0;d<n;++d)f.push(d);for(let d=0;d<=o;++d){let g=h.next()%f.length,y=f[g];if(f.splice(g,1),d==o)return y}throw new Error("Should never reach here")}Error(e,t=false){let n=new cn.StoryException(e);throw n.useEndLineNumber=t,n}Warning(e){this.AddError(e,true);}AddError(e,t=false,n=false){let r=this.currentDebugMetadata,a=t?"WARNING":"ERROR";if(r!=null){let s=n?r.endLineNumber:r.startLineNumber;e="RUNTIME "+a+": '"+r.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 n=this.state.callStack.elements.length-1;n>=0;--n)if(t=this.state.callStack.elements[n].currentPointer,!t.isNull&&t.Resolve()!==null&&(e=t.Resolve().debugMetadata,e!==null))return e;for(let n=this.state.outputStream.length-1;n>=0;--n)if(e=this.state.outputStream[n].debugMetadata,e!==null)return e;return null}get mainContentContainer(){return this._temporaryEvaluationContainer?this._temporaryEvaluationContainer:this._mainContentContainer}};pn.Story=Wn;Wn.inkVersionCurrent=21;(function(i){(function(t){t[t.NoChange=0]="NoChange",t[t.ExtendedBeyondNewline=1]="ExtendedBeyondNewline",t[t.NewlineRemoved=2]="NewlineRemoved";})(i.OutputStateChange||(i.OutputStateChange={}));})(Wn||(pn.Story=Wn={}));});var Bh=T(ha=>{Object.defineProperty(ha,"__esModule",{value:true});ha.Story=void 0;var MC=rr(),$C=$r(),oa=ye(),la=Pe(),Ni=en(),ua=yt(),Lh=Pn(),GC=Al(),HC=vs(),JC=Tl(),UC=xi(),jn=Ot(),zC=qt(),KC=Wt(),Ii=ne(),XC=mi(),YC=Ci(),QC=on(),ca=class i extends ua.FlowBase{get flowLevel(){return Lh.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=(n=null)=>{var r,a;this._errorHandler=n,this.constants=new Map;for(let c of this.FindAll($C.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(HC.ListDefinition)())!((r=c.identifier)===null||r===void 0)&&r.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 oa.Container;o.AddContent(la.ControlCommand.EvalStart());let l=[];for(let[c,h]of this.variableDeclarations)if(h.isGlobalDeclaration){if(h.listDefinition)this._listDefs.set(c,h.listDefinition),o.AddContent(h.listDefinition.runtimeObject),l.push(h.listDefinition.runtimeListDefinition);else {if(!h.expression)throw new Error;h.expression.GenerateIntoContainer(o);}let f=new KC.VariableAssignment(c,true);f.isGlobal=true,o.AddContent(f);}o.AddContent(la.ControlCommand.EvalEnd()),o.AddContent(la.ControlCommand.End()),this.variableDeclarations.size>0&&(o.name="global decl",s.AddToNamedContentOnly(o)),s.AddContent(la.ControlCommand.Done());let u=new UC.Story(s,l);return this.runtimeObject=u,this.hadError||(this.FlattenContainersIn(s),this.ResolveReferences(this),this.hadError)?null:(u.ResetState(),u)},this.ResolveList=n=>{let r=this._listDefs.get(n);return r||null},this.ResolveListItem=(n,r,a=null)=>{let s=null;if(n)return (s=this._listDefs.get(n))?s.ItemNamed(r):null;{let o=null,l=null;for(let[,u]of this._listDefs.entries()){let c=u.ItemNamed(r);c&&(o?this.Error(`Ambiguous item name '${r}' found in multiple sets, including ${l.identifier} and ${u.identifier}`,a,false):(o=c,l=u));}return o}},this.FlattenContainersIn=n=>{let r=new Set;if(n.content)for(let a of n.content){let s=(0, Ii.asOrNull)(a,oa.Container);s&&r.add(s);}if(n.namedContent)for(let[,a]of n.namedContent){let s=(0, Ii.asOrNull)(a,oa.Container);s&&r.add(s);}for(let a of r)this.TryFlattenContainer(a),this.FlattenContainersIn(a);},this.TryFlattenContainer=n=>{if(n.namedContent&&n.namedContent.size>0||n.hasValidName||this._dontFlattenContainers.has(n))return;let r=(0, Ii.asOrNull)(n.parent,oa.Container);if(r){let a=r.content.indexOf(n);r.content.splice(a,1);let s=n.ownDebugMetadata;if(n.content)for(let o of n.content)o.parent=null,s!==null&&o.ownDebugMetadata===null&&(o.debugMetadata=s),r.InsertContent(o,a),a+=1;}},this.Error=(n,r,a)=>{let s=a?Ni.ErrorType.Warning:Ni.ErrorType.Error,o="";if(r instanceof MC.AuthorWarning?(o+="TODO: ",s=Ni.ErrorType.Author):a?o+="WARNING: ":o+="ERROR: ",r&&r.debugMetadata!==null&&r.debugMetadata.startLineNumber>=1&&(r.debugMetadata.fileName!=null&&(o+=`'${r.debugMetadata.fileName}' `),o+=`line ${r.debugMetadata.startLineNumber}: `),o+=n,n=o,this._errorHandler!==null)this._errorHandler(n,s);else throw new Error(n);this._hadError=s===Ni.ErrorType.Error,this._hadWarning=s===Ni.ErrorType.Warning;},this.ResetError=()=>{this._hadError=false,this._hadWarning=false;},this.IsExternal=n=>this.externals.has(n),this.AddExternal=n=>{this.externals.has(n.name)?this.Error(`Duplicate EXTERNAL definition of '${n.name}'`,n,false):n.name&&this.externals.set(n.name,n);},this.DontFlattenContainer=n=>{this._dontFlattenContainers.add(n);},this.NameConflictError=(n,r,a,s)=>{n.Error(`${s} '${r}': name has already been used for a ${a.typeName.toLowerCase()} on ${a.debugMetadata}`);},this.CheckForNamingCollisions=(n,r,a,s="")=>{var o;let l=s||n.typeName;if(i.IsReservedKeyword(r?.name)){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a reserved keyword`);return}else if(YC.FunctionCall.IsBuiltIn(r?.name||"")){n.Error(`'${r}' cannot be used for the name of a ${l.toLowerCase()} because it's a built in function`);return}let u=this.ContentWithNameAtLevel(r?.name||"",Lh.FlowLevel.Knot),c=(0, Ii.asOrNull)(u,ua.FlowBase);if(c&&(c!==n||a===jn.SymbolType.Arg)){this.NameConflictError(n,r?.name||"",c,l);return}if(a<jn.SymbolType.List)return;for(let[g,y]of this._listDefs)if(r?.name===g&&n!==y&&y.variableAssignment!==n&&this.NameConflictError(n,r?.name,y,l),!(n instanceof JC.ListElementDefinition))for(let _ of y.itemDefinitions)r?.name===_.name&&this.NameConflictError(n,r?.name||"",_,l);if(a<=jn.SymbolType.Var)return;let h=r?.name&&this.variableDeclarations.get(r?.name)||null;if(h&&h!==n&&h.isGlobalDeclaration&&h.listDefinition==null&&this.NameConflictError(n,r?.name||"",h,l),a<jn.SymbolType.SubFlowAndWeave)return;let d=new QC.Path(r).ResolveFromContext(n);if(d&&d!==n){this.NameConflictError(n,r?.name||"",d,l);return}if(!(a<jn.SymbolType.Arg)&&a!==jn.SymbolType.Arg){let g=(0, Ii.asOrNull)(n,ua.FlowBase);if(g||(g=(0, XC.ClosestFlowBase)(n)),g&&g.hasParameters&&g.args){for(let y of g.args)if(((o=y.identifier)===null||o===void 0?void 0:o.name)===r?.name){n.Error(`${l} '${r}': name has already been used for a argument to ${g.identifier} on ${g.debugMetadata}`);return}}}};}get typeName(){return "Story"}PreProcessTopLevelObjects(e){super.PreProcessTopLevelObjects(e);let t=[];for(let n of e)if(n instanceof GC.IncludedFile){let r=n,a=e.indexOf(n);if(e.splice(a,1),r.includedStory){let s=[],o=r.includedStory;if(o.content!=null){for(let l of o.content)l instanceof ua.FlowBase?t.push(l):s.push(l);s.push(new zC.Text(`
29
+ `)),e.splice(a,0,...s);}}continue}e.splice(0,0,...t);}};ha.Story=ca;ca.IsReservedKeyword=i=>{switch(i){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 jh=T(pa=>{Object.defineProperty(pa,"__esModule",{value:true});pa.StringExpression=void 0;var Wh=Pe(),ZC=Ye(),ey=qt(),ty=ne(),nu=class i extends ZC.Expression{get isSingleString(){return !(this.content.length!==1||!(this.content[0]instanceof ey.Text))}constructor(e){super(),this.GenerateIntoContainer=t=>{t.AddContent(Wh.ControlCommand.BeginString());for(let n of this.content)t.AddContent(n.runtimeObject);t.AddContent(Wh.ControlCommand.EndString());},this.toString=()=>{let t="";for(let n of this.content)t+=n;return t},this.AddContent(e);}get typeName(){return "String"}Equals(e){let t=(0, ty.asOrNull)(e,i);if(t===null||!this.isSingleString||!t.isSingleString)return false;let n=this.toString(),r=t.toString();return n===r}};pa.StringExpression=nu;});var Mh=T(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.LegacyTag=qn.Tag=void 0;var ny=pe(),qh=Pe(),iu=class extends ny.ParsedObject{constructor(e,t=false){super(),this.GenerateRuntimeObject=()=>this.isStart?qh.ControlCommand.BeginTag():qh.ControlCommand.EndTag(),this.toString=()=>this.isStart?"#StartTag":"#EndTag",this.isStart=e,this.inChoice=t;}get typeName(){return "Tag"}};qn.Tag=iu;var iy=yl(),ru=class extends iy.Wrap{constructor(e){super(e);}get typeName(){return "Tag"}};qn.LegacyTag=ru;});var $h=T(fa=>{Object.defineProperty(fa,"__esModule",{value:true});fa.DefaultFileHandler=void 0;var su=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.")};}};fa.DefaultFileHandler=su;});var uu=T(Ca=>{Object.defineProperty(Ca,"__esModule",{value:true});Ca.InkParser=void 0;var ry=pc(),sy=rr(),ay=po(),at=xc(),_e=hi(),oy=Tn(),ly=Rc(),uy=jr(),Ri=Uo(),He=es(),cy=$r(),da=nh(),hy=ih(),fn=In(),au=Nn(),py=Ye(),fy=rh(),Gh=sh(),ga=Ci(),dy=gi(),gy=ah(),my=Is(),ma=lh(),Hh=Al(),Cy=uh(),yy=_l(),Jh=hh(),vy=vs(),Sy=Tl(),Ey=$o(),Uh=pe(),by=on(),zh=Ro(),Kh=nl(),xe=Zo(),ke=Pl(),Ay=Nl(),Xh=Bh(),Vi=jh(),Tt=Do(),Mn=Mh(),Pt=qt(),Yh=rl(),ou=cl(),lu=Vn(),Dy=co(),Jt=ne(),ki=Yr(),$n=Sr(),Qh=en(),xy=$h(),se=class i extends Tt.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,n=null,r=null,a=null){if(super(e),this.ParseStory=()=>{let s=this.StatementsAtLevel(ke.StatementLevel.Top);return new Xh.Story(s,this._rootParser!==this)},this.SeparatedList=(s,o)=>{let l=this.Parse(s);if(l===null)return null;let u=[];u.push(l);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),u.push(f);}while(true);return u},this.CreateDebugMetadata=(s,o)=>{let l=new hy.DebugMetadata;return l.startLineNumber=(s?.lineIndex||0)+1,l.endLineNumber=o.lineIndex+1,l.startCharacterNumber=(s?.characterInLineIndex||0)+1,l.endCharacterNumber=o.characterInLineIndex+1,l.fileName=this._filename,l},this.RuleDidSucceed=(s,o,l)=>{let u=(0, Jt.asOrNull)(s,Uh.ParsedObject);u&&(u.debugMetadata=this.CreateDebugMetadata(o,l));let c=Array.isArray(s)?s:null;if(c!==null)for(let f of c)(0, Jt.asOrNull)(f,Uh.ParsedObject)&&(f.hasOwnDebugMetadata||(f.debugMetadata=this.CreateDebugMetadata(o,l)));let h=(0, Jt.asOrNull)(s,ki.Identifier);h!=null&&(h.debugMetadata=this.CreateDebugMetadata(o,l));},this.OnStringParserError=(s,o,l=0,u=false)=>{let h=u?"WARNING:":"ERROR:";if(this._filename!==null&&(h+=` '${this._filename}'`),h+=` line ${l+1}: ${s}`,this._externalErrorHandler!==null)this._externalErrorHandler(h,u?Qh.ErrorType.Warning:Qh.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(`
30
+ \r`);return o?new sy.AuthorWarning(o):null},this.ExtendIdentifierCharacterRanges=s=>{let o=i.ListAllCharacterRanges();for(let l of o)s.AddCharacters(l.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 l=this.Parse(this.BracketedName);this.Whitespace(),l!=null&&this.Newline();let u=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 He.ContentList(h));let f=null,d=null,g=this.ParseString("[")!==null;if(g){this.EndTagIfNecessary(c);let m=this.Parse(this.MixedTextAndLogic);m!==null&&(f=new He.ContentList(m)),this.Expect(this.String("]"),"closing ']' for weave-style option"),this.EndTagIfNecessary(f);let p=this.Parse(this.MixedTextAndLogic);p!==null&&(d=new He.ContentList(p));}this.Whitespace(),this.EndTagIfNecessary(d??c);let y=this.Parse(this.MultiDivert);this._parsingChoice=false,this.Whitespace();let _=!c&&!d&&!f;if(_&&y===null&&this.Warning("Choice is completely empty. Interpretting as a default fallback choice. Add a divert arrow to remove this warning: * ->"),!c&&g&&!f&&this.Warning("Blank choice - if you intended a default fallback choice, use the `* ->` syntax"),d||(d=new He.ContentList),this.EndTagIfNecessary(d),y!==null)for(let m of y){let p=(0, Jt.asOrNull)(m,fn.Divert);p&&p.isEmpty||d.AddContent(m);}d.AddContent(new Pt.Text(`
31
+ `));let D=new oy.Choice(c,f,d);return l&&(D.identifier=l),D.indentationDepth=o.length,D.hasWeaveStyleInlineBrackets=g,D.condition=u,D.onceOnly=s,D.isInvisibleDefault=_,D},this.ChoiceCondition=()=>{let s=this.Interleave(this.ChoiceSingleCondition,this.ChoiceConditionsSpace);return s===null?null:s.length===1?s[0]:new Ey.MultipleConditionExpression(s)},this.ChoiceConditionsSpace=()=>(this.Newline(),this.Whitespace(),Tt.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),l=this.Parse(this.BracketedName),u=new dy.Gather(l,o);return this.Newline(),u},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,l=s!==null,u=this.Parse(this.Newline)===null;if(u&&!l)return null;if(u)o=this.InlineConditionalBranches();else {if(o=this.MultilineConditionalBranches(),o===null){if(s){let h=this.StatementsAtLevel(ke.StatementLevel.InnerBlock);if(h!==null){o=[new Ri.ConditionalSingleBranch(h)];let d=this.Parse(this.SingleMultilineCondition);d&&(d.isElse||(this.ErrorWithParsedObject("Expected an '- else:' clause here rather than an extra condition",d),d.isElse=true),o.push(d));}}if(o===null)return null}else if(o.length===1&&o[0].isElse&&s){let h=new Ri.ConditionalSingleBranch(null);h.isTrueBranch=true,o.unshift(h);}if(s){let h=false;for(let f=0;f<o.length;++f){let d=o[f],g=f===o.length-1;d.ownExpression?(d.matchingEquality=true,h=true):h&&g?(d.matchingEquality=true,d.isElse=true):!g&&o.length>2?this.ErrorWithParsedObject("Only final branch can be an 'else'. Did you miss a ':'?",d):f===0?d.isTrueBranch=true:d.isElse=true;}}else {for(let h=0;h<o.length;++h){let f=o[h],d=h===o.length-1;if(f.ownExpression===null)if(d)f.isElse=true;else if(f.isElse){let g=o[o.length-1];g.isElse?this.ErrorWithParsedObject("Multiple 'else' cases. Can have a maximum of one, at the end.",g):this.ErrorWithParsedObject("'else' case in conditional should always be the final one",f);}else this.ErrorWithParsedObject("Branch doesn't have condition. Are you missing a ':'? ",f);}o.length===1&&o[0].ownExpression===null&&this.ErrorWithParsedObject("Condition block with no conditions",o[0]);}}if(o===null)return null;for(let h of o)h.isInline=u;return new uy.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 l=new Ri.ConditionalSingleBranch(s[0]);if(l.isTrueBranch=true,o.push(l),s.length>1){let u=new Ri.ConditionalSingleBranch(s[1]);u.isElse=true,o.push(u);}}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 l=this.StatementsAtLevel(ke.StatementLevel.InnerBlock);s===null&&l===null&&(this.Error("expected content for the conditional branch following '-'"),l=[new Pt.Text("")]),this.MultilineWhitespace();let u=new Ri.ConditionalSingleBranch(l);return u.ownExpression=s,u.isElse=o,u},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:Tt.ParseSuccess,this._nonTextPauseCharacters=null,this._nonTextEndCharacters=null,this._notTextEndCharactersChoice=null,this._notTextEndCharactersString=null,this.TrimEndWhitespace=(s,o)=>{if(s.length>0){let l=s.length-1,u=s[l];if(u instanceof Pt.Text){let c=u;c.text=c.text.replace(new RegExp(/[ \t]+$/g),""),o?c.text+=" ":c.text.length===0&&(s.splice(l,1),this.TrimEndWhitespace(s,false));}}},this.LineOfMixedTextAndLogic=()=>{this.Parse(this.Whitespace);let s=this.Parse(this.MixedTextAndLogic);if(!s||!s.length)return null;let o=s[0];return o&&o.text&&o.text.startsWith("return")&&this.Warning("Do you need a '~' before 'return'? If not, perhaps use a glue: <> (since it's lowercase) or rewrite somehow?"),s.length===0?null:(s[s.length-1]instanceof fn.Divert||this.TrimEndWhitespace(s,false),this.EndTagIfNecessary(s),s.length>0&&s[0]instanceof Mn.Tag&&s[0].isStart||s.push(new Pt.Text(`
32
+ `)),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 l=this.Parse(this.MultiDivert);l!==null&&(o===null&&(o=[]),this.EndTagIfNecessary(o),this.TrimEndWhitespace(o,true),o.push(...l));}return o||null},this.ContentText=()=>this.ContentTextAllowingEscapeChar(),this.ContentTextAllowingEscapeChar=()=>{let s=null;do{let o=this.Parse(this.ContentTextNoEscape),l=this.ParseString("\\")!==null;if(l||o!==null){if(s===null&&(s=""),o!==null&&(s+=String(o)),l){let u=this.ParseSingleCharacter();s+=u;}}else break}while(true);return s!==null?new Pt.Text(s):null},this.ContentTextNoEscape=()=>{this._nonTextPauseCharacters===null&&(this._nonTextPauseCharacters=new _e.CharacterSet("-<")),this._nonTextEndCharacters===null&&(this._nonTextEndCharacters=new _e.CharacterSet(`{}|
33
+ \r\\#`),this._notTextEndCharactersChoice=new _e.CharacterSet(this._nonTextEndCharacters),this._notTextEndCharactersChoice.AddCharacters("[]"),this._notTextEndCharactersString=new _e.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 l=this.ParseUntil(s,this._nonTextPauseCharacters,o);return l!==null?l:null},this.MultiDivert=()=>{this.Whitespace();let s=[],o=this.Parse(this.StartThread);if(o)return s=[o],s;let l=this.Interleave(this.ParseDivertArrowOrTunnelOnwards,this.DivertIdentifierWithArguments);if(!l)return null;s=[],this.EndTagIfNecessary(s);for(let u=0;u<l.length;++u)if(u%2===0){if(l[u]==="->->"){u===0||u===l.length-1||u===l.length-2||this.Error("Tunnel onwards '->->' must only come at the begining or the start of a divert");let f=new Yh.TunnelOnwards;if(u<l.length-1){let d=(0, Jt.asOrNull)(l[u+1],fn.Divert);f.divertAfter=d;}s.push(f);break}}else {let h=l[u];u<l.length-1&&(h.isTunnel=true),s.push(h);}if(s.length===0&&l.length===1){let u=new fn.Divert(null);u.isEmpty=true,s.push(u),this._parsingChoice||this.Error("Empty diverts (->) are only valid on choices");}return s},this.StartThread=()=>{if(this.Whitespace(),this.ParseThreadArrow()===null)return null;this.Whitespace();let s=this.Expect(this.DivertIdentifierWithArguments,"target for new thread",()=>new fn.Divert(null));return s.isThread=true,s},this.DivertIdentifierWithArguments=()=>{this.Whitespace();let s=this.Parse(this.DotSeparatedDivertPathComponents);if(!s)return null;this.Whitespace();let o=this.Parse(this.ExpressionFunctionCallArguments);this.Whitespace();let l=new by.Path(s);return new fn.Divert(l,o)},this.SingleDivert=()=>{let s=this.Parse(this.MultiDivert);if(!s||s.length!==1||s[0]instanceof Yh.TunnelOnwards)return null;let l=s[0];return l.isTunnel?null:l},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 l=this.ParseString("+")!==null,u=this.ParseString("-")!==null;if(l&&u&&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 l||u?new ma.IncDecExpression(o,c,l):new ou.VariableAssignment({variableIdentifier:o,assignedExpression:c,isTemporaryNewDeclaration:s})},this.DisallowIncrement=s=>{s instanceof ma.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 zh.ReturnType(o)},this.Expression=(s=0)=>{this.Whitespace();let o=this.ExpressionUnary();if(o===null)return null;for(this.Whitespace();;){let l=this.BeginRule(),u=this.ParseInfixOperator();if(u!==null&&u.precedence>s){let c=`right side of '${u.type}' expression`,h=this.Expect(()=>this.ExpressionInfixRight(o,u),c);if(h===null)return this.FailRule(l),null;o=this.SucceedRule(l,h);continue}this.FailRule(l);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 l=this.OneOf([this.ExpressionList,this.ExpressionParen,this.ExpressionFunctionCall,this.ExpressionVariableName,this.ExpressionLiteral]);if(l===null&&o!==null&&(l=this.ExpressionUnary()),l===null)return null;o!==null&&(l=Dy.UnaryExpression.WithInner(l,o)),this.Whitespace();let u=this.OneOf([this.String("++"),this.String("--")]);if(u!==null){let c=u==="++";if(!(l instanceof lu.VariableReference))this.Error(`can only increment and decrement variables, but saw '${l}'.`);else {let h=l;l=new ma.IncDecExpression(h.identifier,c);}}return l},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 au.DivertTarget(s))},this.ExpressionInt=()=>{let s=this.ParseInt();return s===null?null:new $n.NumberExpression(s,"int")},this.ExpressionFloat=()=>{let s=this.ParseFloat();return s===null?null:new $n.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 Pt.Text("")]:o.find(l=>l instanceof fn.Divert)&&this.Error("String expressions cannot contain diverts (->)"),new Vi.StringExpression(o)},this.ExpressionBool=()=>{let s=this.Parse(this.Identifier);return s==="true"?new $n.NumberExpression(true,"bool"):s==="false"?new $n.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 ga.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||Xh.Story.IsReservedKeyword(s[0].name)?null:new lu.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 l=this.Parse(()=>this.Expression(o.precedence));return l?new ay.BinaryExpression(s,l,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 Jh.List(s)},this.ListMember=()=>{this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata);if(s===null)return null;if(this.ParseString(".")!==null){let l=this.Expect(this.IdentifierWithMetadata,`element name within the set ${s}`);s.name+=`.${l?.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,l=false)=>{let u=new Cy.InfixOperator(s,o,l);this._binaryOperators.push(u),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(`
34
34
  \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
35
- `),new Gh.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
36
- Error:${c}`);}return u!=null&&(l=new i(u,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Gh.IncludedFile(l)},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(Re.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new yy.Knot(s.name,l,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,l=s?.name==="function";l?(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 ${l?"function":"knot"}`),o=new ki.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new $h.FlowDecl(o,u,l)},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(Re.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Ay.Stitch(s.name,l,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 l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new $h.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new xe.CharacterSet("="),null),[new Tt.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 l=this.Parse(this.IdentifierWithMetadata);if(s==null&&l===null)return null;let u=new ry.Argument;return o!==null&&(u.isDivertTarget=true),s!==null&&s.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=true):(u.isDivertTarget?u.identifier=l:u.identifier=s,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},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 ki.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);l===null&&(l=[]);let u=l.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(Jt.filterUndef);return new fy.ExternalDeclaration(o,u)},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 He.ContentList;o instanceof py.Expression&&!(o instanceof da.FunctionCall||o instanceof ga.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
35
+ `),new Hh.IncludedFile(null);this.AddOpenFilename(o);let l=null,u="";try{u=this._rootParser.fileHandler.LoadInkFileContents(o,this._filename);}catch(c){this.Error(`Failed to load: '${s}'.
36
+ Error:${c}`);}return u!=null&&(l=new i(u,s,this._externalErrorHandler,this._rootParser,this.fileHandler).ParseStory()),this.RemoveOpenFilename(o),new Hh.IncludedFile(l)},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(ke.StatementLevel.Knot),l=this.Expect(o,"at least one line within the knot",this.KnotStitchNoContentRecoveryRule);return new yy.Knot(s.name,l,s.args,s.isFunction)},this.KnotDeclaration=()=>{if(this.Whitespace(),this.KnotTitleEquals()===null)return null;this.Whitespace();let s=this.Parse(this.IdentifierWithMetadata),o,l=s?.name==="function";l?(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 ${l?"function":"knot"}`),o=new ki.Identifier("")),this.Whitespace();let u=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),this.Parse(this.KnotTitleEquals),new Gh.FlowDecl(o,u,l)},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(ke.StatementLevel.Stitch),l=this.Expect(o,"at least one line within the stitch",this.KnotStitchNoContentRecoveryRule);return new Ay.Stitch(s.name,l,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 l=this.Parse(this.BracketedKnotDeclArguments);return this.Whitespace(),new Gh.FlowDecl(o,l,s)},this.KnotStitchNoContentRecoveryRule=()=>(this.ParseUntil(this.KnotDeclaration,new _e.CharacterSet("="),null),[new Pt.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 l=this.Parse(this.IdentifierWithMetadata);if(s==null&&l===null)return null;let u=new ry.Argument;return o!==null&&(u.isDivertTarget=true),s!==null&&s.name==="ref"?(l===null&&this.Error("Expected an parameter name after 'ref'"),u.identifier=l,u.isByReference=true):(u.isDivertTarget?u.identifier=l:u.identifier=s,u.identifier===null&&this.Error("Expected an parameter name"),u.isByReference=false),u},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 ki.Identifier("");this.Whitespace();let l=this.Expect(this.BracketedKnotDeclArguments,`declaration of arguments for EXTERNAL, even if empty, i.e. 'EXTERNAL ${o}()'`);l===null&&(l=[]);let u=l.map(c=>{var h;return (h=c.identifier)===null||h===void 0?void 0:h.name}).filter(Jt.filterUndef);return new fy.ExternalDeclaration(o,u)},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 He.ContentList;o instanceof py.Expression&&!(o instanceof ga.FunctionCall||o instanceof ma.IncDecExpression)&&this.Error(`Logic following a '~' can't be that type of expression. It can only be something like:
37
37
  ~ return
38
38
  ~ var x = blah
39
39
  ~ x++
40
- ~ myFunction()`);let l=(0, Jt.asOrNull)(o,da.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(da.FunctionCall)()!==null&&(o=new He.ContentList(o,new Tt.Text(`
41
- `))),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 u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof $n.NumberExpression||u instanceof Vi.StringExpression||u instanceof ru.DivertTarget||u instanceof au.VariableReference||u instanceof Hh.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"):u instanceof Vi.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new su.VariableAssignment({assignedExpression:u,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 l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new ki.Identifier(o.name),new su.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new vy.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(u=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new Sy.ListElementDefinition(l,s,u)},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 l=this.Expect(this.Expression,"initial value for ");return l instanceof $n.NumberExpression||l instanceof ru.DivertTarget||l instanceof Vi.StringExpression?l instanceof Vi.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new cy.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new gy.Glue(new my.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(l);let u=(0, Jt.asOrNull)(l,He.ContentList);return u||(u=new He.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new zh.Sequence(u,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let c=this.BeginRule(),h=this.ParseObject(u);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 ki.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let l of s)if(!(l>="0"&&l<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new xe.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=De.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new zh.Sequence(l,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case De.SequenceType.Once:case De.SequenceType.Cycle:case De.SequenceType.Stopping:case De.SequenceType.Shuffle:case De.SequenceType.Shuffle|De.SequenceType.Stopping:case De.SequenceType.Shuffle|De.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),De.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new xe.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=De.SequenceType.Once;break;case "&":s|=De.SequenceType.Cycle;break;case "~":s|=De.SequenceType.Shuffle;break;case "$":s|=De.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 l of s)o|=l;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=De.SequenceType.Once;break;case "cycle":s=De.SequenceType.Cycle;break;case "shuffle":s=De.SequenceType.Shuffle;break;case "stopping":s=De.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=[],l=false;for(let u of s)if(u==="|")l||o.push(new He.ContentList),l=false;else {let c=u;c===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new He.ContentList(c)),l=true;}return l||o.push(new He.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(Re.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new Tt.Text(`
42
- `)),new He.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===Re.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],l=this.OneOf(o);return s===Re.StatementLevel.Top&&l instanceof Uh.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let s=Object.values(Re.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 l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=Re.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>Re.StatementLevel.InnerBlock&&l.push(this.Gather),o>=Re.StatementLevel.Knot&&l.push(this.StitchDefinition),l.push(this.Line(this.ListDeclaration)),l.push(this.Line(this.VariableDeclaration)),l.push(this.Line(this.ConstDeclaration)),l.push(this.Line(this.ExternalDeclaration)),l.push(this.Line(this.IncludeStatement)),l.push(this.LogicLine),l.push(this.LineOfMixedTextAndLogic),o<=Re.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=Re.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=Re.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
- \r`),this.ParseNewline(),Ot.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 He.ContentList;o.AddContent(new Mn.Tag(false)),o.AddContent(new Mn.Tag(true)),s=o;}else s=new Mn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new xe.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Ot.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Ot.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?Ot.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Ot.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?Ot.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=n,a===null?this._fileHandler=new xy.DefaultFileHandler:this._fileHandler=a,r===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=r;}PreProcessInputString(e){return new ly.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(fa.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(fa.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(fa.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(fa.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new xe.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 He.ContentList?e.AddContent(new Mn.Tag(false)):e.push(new Mn.Tag(false))),this.tagActive=false);}};ma.InkParser=ae;ae.LatinBasic=ot.CharacterRange.Define("A","z",new xe.CharacterSet().AddRange("[","`"));ae.LatinExtendedA=ot.CharacterRange.Define("\u0100","\u017F");ae.LatinExtendedB=ot.CharacterRange.Define("\u0180","\u024F");ae.Greek=ot.CharacterRange.Define("\u0370","\u03FF",new xe.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));ae.Cyrillic=ot.CharacterRange.Define("\u0400","\u04FF",new xe.CharacterSet().AddRange("\u0482","\u0489"));ae.Armenian=ot.CharacterRange.Define("\u0530","\u058F",new xe.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));ae.Hebrew=ot.CharacterRange.Define("\u0590","\u05FF",new xe.CharacterSet);ae.Arabic=ot.CharacterRange.Define("\u0600","\u06FF",new xe.CharacterSet);ae.Korean=ot.CharacterRange.Define("\uAC00","\uD7AF",new xe.CharacterSet);ae.Latin1Supplement=ot.CharacterRange.Define("\x80","\xFF",new xe.CharacterSet);ae.Chinese=ot.CharacterRange.Define("\u4E00","\u9FFF",new xe.CharacterSet);ae.ListAllCharacterRanges=()=>[ae.LatinBasic,ae.LatinExtendedA,ae.LatinExtendedB,ae.Arabic,ae.Armenian,ae.Cyrillic,ae.Greek,ae.Hebrew,ae.Korean,ae.Latin1Supplement,ae.Chinese];});var Qh=P(Ca=>{Object.defineProperty(Ca,"__esModule",{value:true});Ca.GenerateStoryStats=void 0;var _y=Tn(),wy=In(),Oy=gi(),Ty=Dl(),Py=Pl(),Fy=qt();function Ny(i){let e=i.FindAll(Fy.Text)(),t=0;for(let l of e){let u=0,c=true;for(let h of l.text)h==" "||h==" "||h==`
44
- `||h=="\r"?c=true:c&&(u++,c=false);t+=u;}let n=i.FindAll(Ty.Knot)(),r=i.FindAll(Py.Stitch)(),a=i.FindAll(_y.Choice)(),s=i.FindAll(Oy.Gather)(l=>l.debugMetadata!=null),o=i.FindAll(wy.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:r.length,gathers:s.length,diverts:o.length-1,choices:a.length}}Ca.GenerateStoryStats=Ny;});var Zh=P(ya=>{Object.defineProperty(ya,"__esModule",{value:true});ya.JsonFileHandler=void 0;var lu=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}.`)};}};ya.JsonFileHandler=lu;});var tp=P(Fe=>{Object.defineProperty(Fe,"__esModule",{value:true});Fe.Compiler=Fe.Story=Fe.InkList=Fe.JsonFileHandler=Fe.StatementLevel=Fe.InkParser=Fe.CompilerOptions=void 0;var Iy=Ha(),Ry=uc(),uu=en(),Vy=ou(),ky=fe(),Ly=ie(),By=Qh(),Wy=Ha();Object.defineProperty(Fe,"CompilerOptions",{enumerable:true,get:function(){return Wy.CompilerOptions}});var jy=ou();Object.defineProperty(Fe,"InkParser",{enumerable:true,get:function(){return jy.InkParser}});var qy=Ol();Object.defineProperty(Fe,"StatementLevel",{enumerable:true,get:function(){return qy.StatementLevel}});var My=Zh();Object.defineProperty(Fe,"JsonFileHandler",{enumerable:true,get:function(){return My.JsonFileHandler}});var ep=xi();Object.defineProperty(Fe,"InkList",{enumerable:true,get:function(){return ep.InkList}});Object.defineProperty(Fe,"Story",{enumerable:true,get:function(){return ep.Story}});var cu=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 Vy.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 n;for(let r of this.runtimeStory.state.outputStream){let a=(0, Ly.asOrNull)(r,ky.StringValue);if(a!==null){let s=new Ry.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, By.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let r=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),n>=r&&n<r+s.length)return a;r+=s.length;}return null},this.OnError=(n,r)=>{switch(r){case uu.ErrorType.Author:this._authorMessages.push(n);break;case uu.ErrorType.Warning:this._warnings.push(n);break;case uu.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,r);},this._inputString=e,this._options=t||new Iy.CompilerOptions;}};Fe.Compiler=cu;});var up=P((rx,pu)=>{var Ea=process||{},op=Ea.argv||[],Sa=Ea.env||{},Xy=!(Sa.NO_COLOR||op.includes("--no-color"))&&(!!Sa.FORCE_COLOR||op.includes("--color")||Ea.platform==="win32"||(Ea.stdout||{}).isTTY&&Sa.TERM!=="dumb"||!!Sa.CI),Yy=(i,e,t=i)=>n=>{let r=""+n,a=r.indexOf(e,i.length);return ~a?i+Qy(r,e,t,a)+e:i+r+e},Qy=(i,e,t,n)=>{let r="",a=0;do r+=i.substring(a,n)+t,a=n+e.length,n=i.indexOf(e,a);while(~n);return r+i.substring(a)},lp=(i=Xy)=>{let e=i?Yy:()=>String;return {isColorSupported:i,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")}};pu.exports=lp();pu.exports.createColors=lp;});var Bi=P((dx,xp)=>{var Ep="[^\\\\/]",Qv="(?=.)",bp="[^/]",gu="(?:\\/|$)",Ap="(?:^|\\/)",mu=`\\.{1,2}${gu}`,Zv="(?!\\.)",e0=`(?!${Ap}${mu})`,t0=`(?!\\.{0,1}${gu})`,n0=`(?!${mu})`,i0="[^.\\/]",r0=`${bp}*?`,s0="/",Dp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Qv,QMARK:bp,END_ANCHOR:gu,DOTS_SLASH:mu,NO_DOT:Zv,NO_DOTS:e0,NO_DOT_SLASH:t0,NO_DOTS_SLASH:n0,QMARK_NO_DOT:i0,STAR:r0,START_ANCHOR:Ap,SEP:s0},a0={...Dp,SLASH_LITERAL:"[\\\\/]",QMARK:Ep,STAR:`${Ep}*?`,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:"\\"},o0={__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"};xp.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:o0,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(i){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${i.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(i){return i===true?a0:Dp}};});var Wi=P(Je=>{var{REGEX_BACKSLASH:l0,REGEX_REMOVE_BACKSLASH:u0,REGEX_SPECIAL_CHARS:c0,REGEX_SPECIAL_CHARS_GLOBAL:h0}=Bi();Je.isObject=i=>i!==null&&typeof i=="object"&&!Array.isArray(i);Je.hasRegexChars=i=>c0.test(i);Je.isRegexChar=i=>i.length===1&&Je.hasRegexChars(i);Je.escapeRegex=i=>i.replace(h0,"\\$1");Je.toPosixSlashes=i=>i.replace(l0,"/");Je.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let i=navigator.platform.toLowerCase();return i==="win32"||i==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Je.removeBackslashes=i=>i.replace(u0,e=>e==="\\"?"":e);Je.escapeLast=(i,e,t)=>{let n=i.lastIndexOf(e,t);return n===-1?i:i[n-1]==="\\"?Je.escapeLast(i,e,n-1):`${i.slice(0,n)}\\${i.slice(n)}`};Je.removePrefix=(i,e={})=>{let t=i;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Je.wrapOutput=(i,e={},t={})=>{let n=t.contains?"":"^",r=t.contains?"":"$",a=`${n}(?:${i})${r}`;return e.negated===true&&(a=`(?:^(?!${a}).*$)`),a};Je.basename=(i,{windows:e}={})=>{let t=i.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n};});var Ip=P((mx,Np)=>{var _p=Wi(),{CHAR_ASTERISK:Cu,CHAR_AT:p0,CHAR_BACKWARD_SLASH:ji,CHAR_COMMA:f0,CHAR_DOT:yu,CHAR_EXCLAMATION_MARK:vu,CHAR_FORWARD_SLASH:Fp,CHAR_LEFT_CURLY_BRACE:Su,CHAR_LEFT_PARENTHESES:Eu,CHAR_LEFT_SQUARE_BRACKET:d0,CHAR_PLUS:g0,CHAR_QUESTION_MARK:wp,CHAR_RIGHT_CURLY_BRACE:m0,CHAR_RIGHT_PARENTHESES:Op,CHAR_RIGHT_SQUARE_BRACKET:C0}=Bi(),Tp=i=>i===Fp||i===ji,Pp=i=>{i.isPrefix!==true&&(i.depth=i.isGlobstar?1/0:1);},y0=(i,e)=>{let t=e||{},n=i.length-1,r=t.parts===true||t.scanToEnd===true,a=[],s=[],o=[],l=i,u=-1,c=0,h=0,f=false,d=false,g=false,y=false,_=false,D=false,m=false,p=false,E=false,C=false,S=0,w,b,O={value:"",depth:0,isGlob:false},v=()=>u>=n,V=()=>l.charCodeAt(u+1),I=()=>(w=b,l.charCodeAt(++u));for(;u<n;){b=I();let j;if(b===ji){m=O.backslashes=true,b=I(),b===Su&&(D=true);continue}if(D===true||b===Su){for(S++;v()!==true&&(b=I());){if(b===ji){m=O.backslashes=true,I();continue}if(b===Su){S++;continue}if(D!==true&&b===yu&&(b=I())===yu){if(f=O.isBrace=true,g=O.isGlob=true,C=true,r===true)continue;break}if(D!==true&&b===f0){if(f=O.isBrace=true,g=O.isGlob=true,C=true,r===true)continue;break}if(b===m0&&(S--,S===0)){D=false,f=O.isBrace=true,C=true;break}}if(r===true)continue;break}if(b===Fp){if(a.push(u),s.push(O),O={value:"",depth:0,isGlob:false},C===true)continue;if(w===yu&&u===c+1){c+=2;continue}h=u+1;continue}if(t.noext!==true&&(b===g0||b===p0||b===Cu||b===wp||b===vu)===true&&V()===Eu){if(g=O.isGlob=true,y=O.isExtglob=true,C=true,b===vu&&u===c&&(E=true),r===true){for(;v()!==true&&(b=I());){if(b===ji){m=O.backslashes=true,b=I();continue}if(b===Op){g=O.isGlob=true,C=true;break}}continue}break}if(b===Cu){if(w===Cu&&(_=O.isGlobstar=true),g=O.isGlob=true,C=true,r===true)continue;break}if(b===wp){if(g=O.isGlob=true,C=true,r===true)continue;break}if(b===d0){for(;v()!==true&&(j=I());){if(j===ji){m=O.backslashes=true,I();continue}if(j===C0){d=O.isBracket=true,g=O.isGlob=true,C=true;break}}if(r===true)continue;break}if(t.nonegate!==true&&b===vu&&u===c){p=O.negated=true,c++;continue}if(t.noparen!==true&&b===Eu){if(g=O.isGlob=true,r===true){for(;v()!==true&&(b=I());){if(b===Eu){m=O.backslashes=true,b=I();continue}if(b===Op){C=true;break}}continue}break}if(g===true){if(C=true,r===true)continue;break}}t.noext===true&&(y=false,g=false);let B=l,A="",x="";c>0&&(A=l.slice(0,c),l=l.slice(c),h-=c),B&&g===true&&h>0?(B=l.slice(0,h),x=l.slice(h)):g===true?(B="",x=l):B=l,B&&B!==""&&B!=="/"&&B!==l&&Tp(B.charCodeAt(B.length-1))&&(B=B.slice(0,-1)),t.unescape===true&&(x&&(x=_p.removeBackslashes(x)),B&&m===true&&(B=_p.removeBackslashes(B)));let Q={prefix:A,input:i,start:c,base:B,glob:x,isBrace:f,isBracket:d,isGlob:g,isExtglob:y,isGlobstar:_,negated:p,negatedExtglob:E};if(t.tokens===true&&(Q.maxDepth=0,Tp(b)||s.push(O),Q.tokens=s),t.parts===true||t.tokens===true){let j;for(let ne=0;ne<a.length;ne++){let Ve=j?j+1:c,ke=a[ne],it=i.slice(Ve,ke);t.tokens&&(ne===0&&c!==0?(s[ne].isPrefix=true,s[ne].value=A):s[ne].value=it,Pp(s[ne]),Q.maxDepth+=s[ne].depth),(ne!==0||it!=="")&&o.push(it),j=ke;}if(j&&j+1<i.length){let ne=i.slice(j+1);o.push(ne),t.tokens&&(s[s.length-1].value=ne,Pp(s[s.length-1]),Q.maxDepth+=s[s.length-1].depth);}Q.slashes=a,Q.parts=o;}return Q};Np.exports=y0;});var Lp=P((Cx,kp)=>{var qi=Bi(),Ke=Wi(),{MAX_LENGTH:Aa,POSIX_REGEX_SOURCE:v0,REGEX_NON_SPECIAL_CHARS:S0,REGEX_SPECIAL_CHARS_BACKREF:E0,REPLACEMENTS:Rp}=qi,b0=(i,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...i,e);i.sort();let t=`[${i.join("-")}]`;try{new RegExp(t);}catch{return i.map(r=>Ke.escapeRegex(r)).join("..")}return t},Gn=(i,e)=>`Missing ${i}: "${e}" - use "\\\\${e}" to match literal characters`,Vp=i=>{let e=[],t=0,n=0,r=0,a="",s=false;for(let o of i){if(s===true){a+=o,s=false;continue}if(o==="\\"){a+=o,s=true;continue}if(o==='"'){r=r===1?0:1,a+=o;continue}if(r===0){if(o==="[")t++;else if(o==="]"&&t>0)t--;else if(t===0){if(o==="(")n++;else if(o===")"&&n>0)n--;else if(o==="|"&&n===0){e.push(a),a="";continue}}}a+=o;}return e.push(a),e},A0=i=>{let e=false;for(let t of i){if(e===true){e=false;continue}if(t==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(t))return false}return true},Au=i=>{let e=i.trim(),t=true;for(;t===true;)t=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=true);if(A0(e))return e.replace(/\\(.)/g,"$1")},D0=i=>{let e=i.map(Au).filter(Boolean);for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let r=e[t],a=e[n],s=r[0];if(!(!s||r!==s.repeat(r.length)||a!==s.repeat(a.length))&&(r===a||r.startsWith(a)||a.startsWith(r)))return true}return false},bu=(i,e=true)=>{if(i[0]!=="+"&&i[0]!=="*"||i[1]!=="(")return;let t=0,n=0,r=0,a=false;for(let s=1;s<i.length;s++){let o=i[s];if(a===true){a=false;continue}if(o==="\\"){a=true;continue}if(o==='"'){r=r===1?0:1;continue}if(r!==1){if(o==="["){t++;continue}if(o==="]"&&t>0){t--;continue}if(!(t>0)){if(o==="("){n++;continue}if(o===")"&&(n--,n===0))return e===true&&s!==i.length-1?void 0:{type:i[0],body:i.slice(2,s),end:s}}}}},x0=i=>`${i.length===1?Ke.escapeRegex(i[0]):`[${i.map(t=>Ke.escapeRegex(t)).join("")}]`}*`,_0=i=>{let e=0,t=[];for(;e<i.length;){let n=bu(i.slice(e),false);if(!n||n.type!=="*")return;let r=Vp(n.body).map(s=>s.trim());if(r.length!==1)return;let a=Au(r[0]);if(!a||a.length!==1)return;t.push(a),e+=n.end+1;}if(!(t.length<1))return t},w0=i=>{let e=0,t=i.trim(),n=bu(t);for(;n;)e++,t=n.body.trim(),n=bu(t);return e},O0=(i,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:qi.DEFAULT_MAX_EXTGLOB_RECURSION,n=Vp(i).map(o=>o.trim());if(n.length>1&&(n.some(o=>o==="")||n.some(o=>/^[*?]+$/.test(o))||D0(n)))return {risky:true};let r=[],a=false,s=true;for(let o of n){let l=_0(o);if(l){a=true,r.push(...l);continue}let u=Au(o);if(u&&u.length===1){r.push(u);continue}if(s=false,w0(o)>t)return {risky:true}}return a?s?{risky:true,safeOutput:x0([...new Set(r)])}:{risky:true}:{risky:false}},Du=(i,e)=>{if(typeof i!="string")throw new TypeError("Expected a string");i=Rp[i]||i;let t={...e},n=typeof t.maxLength=="number"?Math.min(Aa,t.maxLength):Aa,r=i.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);let a={type:"bos",value:"",output:t.prepend||""},s=[a],o=t.capture?"":"?:",l=qi.globChars(t.windows),u=qi.extglobChars(l),{DOT_LITERAL:c,PLUS_LITERAL:h,SLASH_LITERAL:f,ONE_CHAR:d,DOTS_SLASH:g,NO_DOT:y,NO_DOT_SLASH:_,NO_DOTS_SLASH:D,QMARK:m,QMARK_NO_DOT:p,STAR:E,START_ANCHOR:C}=l,S=F=>`(${o}(?:(?!${C}${F.dot?g:c}).)*?)`,w=t.dot?"":y,b=t.dot?m:p,O=t.bash===true?S(t):E;t.capture&&(O=`(${O})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let v={input:i,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};i=Ke.removePrefix(i,v),r=i.length;let V=[],I=[],B=[],A=a,x,Q=()=>v.index===r-1,j=v.peek=(F=1)=>i[v.index+F],ne=v.advance=()=>i[++v.index]||"",Ve=()=>i.slice(v.index+1),ke=(F="",Y=0)=>{v.consumed+=F,v.index+=Y;},it=F=>{v.output+=F.output!=null?F.output:F.value,ke(F.value);},Da=()=>{let F=1;for(;j()==="!"&&(j(2)!=="("||j(3)==="?");)ne(),v.start++,F++;return F%2===0?false:(v.negated=true,v.start++,true)},gn=F=>{v[F]++,B.push(F);},lt=F=>{v[F]--,B.pop();},R=F=>{if(A.type==="globstar"){let Y=v.braces>0&&(F.type==="comma"||F.type==="brace"),N=F.extglob===true||V.length&&(F.type==="pipe"||F.type==="paren");F.type!=="slash"&&F.type!=="paren"&&!Y&&!N&&(v.output=v.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=O,v.output+=A.output);}if(V.length&&F.type!=="paren"&&(V[V.length-1].inner+=F.value),(F.value||F.output)&&it(F),A&&A.type==="text"&&F.type==="text"){A.output=(A.output||A.value)+F.value,A.value+=F.value;return}F.prev=A,s.push(F),A=F;},Le=(F,Y)=>{let N={...u[Y],conditions:1,inner:""};N.prev=A,N.parens=v.parens,N.output=v.output,N.startIndex=v.index,N.tokensIndex=s.length;let G=(t.capture?"(":"")+N.open;gn("parens"),R({type:F,value:Y,output:v.output?"":d}),R({type:"paren",extglob:true,value:ne(),output:G}),V.push(N);},rt=F=>{let Y=i.slice(F.startIndex,v.index+1),N=i.slice(F.startIndex+2,v.index),G=O0(N,t);if((F.type==="plus"||F.type==="star")&&G.risky){let re=G.safeOutput?(F.output?"":d)+(t.capture?`(${G.safeOutput})`:G.safeOutput):void 0,ut=s[F.tokensIndex];ut.type="text",ut.value=Y,ut.output=re||Ke.escapeRegex(Y);for(let ct=F.tokensIndex+1;ct<s.length;ct++)s[ct].value="",s[ct].output="",delete s[ct].suffix;v.output=F.output+ut.output,v.backtrack=true,R({type:"paren",extglob:true,value:x,output:""}),lt("parens");return}let oe=F.close+(t.capture?")":""),ve;if(F.type==="negate"){let re=O;if(F.inner&&F.inner.length>1&&F.inner.includes("/")&&(re=S(t)),(re!==O||Q()||/^\)+$/.test(Ve()))&&(oe=F.close=`)$))${re}`),F.inner.includes("*")&&(ve=Ve())&&/^\.[^\\/.]+$/.test(ve)){let ut=Du(ve,{...e,fastpaths:false}).output;oe=F.close=`)${ut})${re})`;}F.prev.type==="bos"&&(v.negatedExtglob=true);}R({type:"paren",extglob:true,value:x,output:oe}),lt("parens");};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(i)){let F=false,Y=i.replace(E0,(N,G,oe,ve,re,ut)=>ve==="\\"?(F=true,N):ve==="?"?G?G+ve+(re?m.repeat(re.length):""):ut===0?b+(re?m.repeat(re.length):""):m.repeat(oe.length):ve==="."?c.repeat(oe.length):ve==="*"?G?G+ve+(re?O:""):O:G?N:`\\${N}`);return F===true&&(t.unescape===true?Y=Y.replace(/\\/g,""):Y=Y.replace(/\\+/g,N=>N.length%2===0?"\\\\":N?"\\":"")),Y===i&&t.contains===true?(v.output=i,v):(v.output=Ke.wrapOutput(Y,v,e),v)}for(;!Q();){if(x=ne(),x==="\0")continue;if(x==="\\"){let N=j();if(N==="/"&&t.bash!==true||N==="."||N===";")continue;if(!N){x+="\\",R({type:"text",value:x});continue}let G=/^\\+/.exec(Ve()),oe=0;if(G&&G[0].length>2&&(oe=G[0].length,v.index+=oe,oe%2!==0&&(x+="\\")),t.unescape===true?x=ne():x+=ne(),v.brackets===0){R({type:"text",value:x});continue}}if(v.brackets>0&&(x!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==false&&x===":"){let N=A.value.slice(1);if(N.includes("[")&&(A.posix=true,N.includes(":"))){let G=A.value.lastIndexOf("["),oe=A.value.slice(0,G),ve=A.value.slice(G+2),re=v0[ve];if(re){A.value=oe+re,v.backtrack=true,ne(),!a.output&&s.indexOf(A)===1&&(a.output=d);continue}}}(x==="["&&j()!==":"||x==="-"&&j()==="]")&&(x=`\\${x}`),x==="]"&&(A.value==="["||A.value==="[^")&&(x=`\\${x}`),t.posix===true&&x==="!"&&A.value==="["&&(x="^"),A.value+=x,it({value:x});continue}if(v.quotes===1&&x!=='"'){x=Ke.escapeRegex(x),A.value+=x,it({value:x});continue}if(x==='"'){v.quotes=v.quotes===1?0:1,t.keepQuotes===true&&R({type:"text",value:x});continue}if(x==="("){gn("parens"),R({type:"paren",value:x});continue}if(x===")"){if(v.parens===0&&t.strictBrackets===true)throw new SyntaxError(Gn("opening","("));let N=V[V.length-1];if(N&&v.parens===N.parens+1){rt(V.pop());continue}R({type:"paren",value:x,output:v.parens?")":"\\)"}),lt("parens");continue}if(x==="["){if(t.nobracket===true||!Ve().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true)throw new SyntaxError(Gn("closing","]"));x=`\\${x}`;}else gn("brackets");R({type:"bracket",value:x});continue}if(x==="]"){if(t.nobracket===true||A&&A.type==="bracket"&&A.value.length===1){R({type:"text",value:x,output:`\\${x}`});continue}if(v.brackets===0){if(t.strictBrackets===true)throw new SyntaxError(Gn("opening","["));R({type:"text",value:x,output:`\\${x}`});continue}lt("brackets");let N=A.value.slice(1);if(A.posix!==true&&N[0]==="^"&&!N.includes("/")&&(x=`/${x}`),A.value+=x,it({value:x}),t.literalBrackets===false||Ke.hasRegexChars(N))continue;let G=Ke.escapeRegex(A.value);if(v.output=v.output.slice(0,-A.value.length),t.literalBrackets===true){v.output+=G,A.value=G;continue}A.value=`(${o}${G}|${A.value})`,v.output+=A.value;continue}if(x==="{"&&t.nobrace!==true){gn("braces");let N={type:"brace",value:x,output:"(",outputIndex:v.output.length,tokensIndex:v.tokens.length};I.push(N),R(N);continue}if(x==="}"){let N=I[I.length-1];if(t.nobrace===true||!N){R({type:"text",value:x,output:x});continue}let G=")";if(N.dots===true){let oe=s.slice(),ve=[];for(let re=oe.length-1;re>=0&&(s.pop(),oe[re].type!=="brace");re--)oe[re].type!=="dots"&&ve.unshift(oe[re].value);G=b0(ve,t),v.backtrack=true;}if(N.comma!==true&&N.dots!==true){let oe=v.output.slice(0,N.outputIndex),ve=v.tokens.slice(N.tokensIndex);N.value=N.output="\\{",x=G="\\}",v.output=oe;for(let re of ve)v.output+=re.output||re.value;}R({type:"brace",value:x,output:G}),lt("braces"),I.pop();continue}if(x==="|"){V.length>0&&V[V.length-1].conditions++,R({type:"text",value:x});continue}if(x===","){let N=x,G=I[I.length-1];G&&B[B.length-1]==="braces"&&(G.comma=true,N="|"),R({type:"comma",value:x,output:N});continue}if(x==="/"){if(A.type==="dot"&&v.index===v.start+1){v.start=v.index+1,v.consumed="",v.output="",s.pop(),A=a;continue}R({type:"slash",value:x,output:f});continue}if(x==="."){if(v.braces>0&&A.type==="dot"){A.value==="."&&(A.output=c);let N=I[I.length-1];A.type="dots",A.output+=x,A.value+=x,N.dots=true;continue}if(v.braces+v.parens===0&&A.type!=="bos"&&A.type!=="slash"){R({type:"text",value:x,output:c});continue}R({type:"dot",value:x,output:c});continue}if(x==="?"){if(!(A&&A.value==="(")&&t.noextglob!==true&&j()==="("&&j(2)!=="?"){Le("qmark",x);continue}if(A&&A.type==="paren"){let G=j(),oe=x;(A.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(Ve()))&&(oe=`\\${x}`),R({type:"text",value:x,output:oe});continue}if(t.dot!==true&&(A.type==="slash"||A.type==="bos")){R({type:"qmark",value:x,output:p});continue}R({type:"qmark",value:x,output:m});continue}if(x==="!"){if(t.noextglob!==true&&j()==="("&&(j(2)!=="?"||!/[!=<:]/.test(j(3)))){Le("negate",x);continue}if(t.nonegate!==true&&v.index===0){Da();continue}}if(x==="+"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){Le("plus",x);continue}if(A&&A.value==="("||t.regex===false){R({type:"plus",value:x,output:h});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||v.parens>0){R({type:"plus",value:x});continue}R({type:"plus",value:h});continue}if(x==="@"){if(t.noextglob!==true&&j()==="("&&j(2)!=="?"){R({type:"at",extglob:true,value:x,output:""});continue}R({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let N=S0.exec(Ve());N&&(x+=N[0],v.index+=N[0].length),R({type:"text",value:x});continue}if(A&&(A.type==="globstar"||A.star===true)){A.type="star",A.star=true,A.value+=x,A.output=O,v.backtrack=true,v.globstar=true,ke(x);continue}let F=Ve();if(t.noextglob!==true&&/^\([^?]/.test(F)){Le("star",x);continue}if(A.type==="star"){if(t.noglobstar===true){ke(x);continue}let N=A.prev,G=N.prev,oe=N.type==="slash"||N.type==="bos",ve=G&&(G.type==="star"||G.type==="globstar");if(t.bash===true&&(!oe||F[0]&&F[0]!=="/")){R({type:"star",value:x,output:""});continue}let re=v.braces>0&&(N.type==="comma"||N.type==="brace"),ut=V.length&&(N.type==="pipe"||N.type==="paren");if(!oe&&N.type!=="paren"&&!re&&!ut){R({type:"star",value:x,output:""});continue}for(;F.slice(0,3)==="/**";){let ct=i[v.index+4];if(ct&&ct!=="/")break;F=F.slice(3),ke("/**",3);}if(N.type==="bos"&&Q()){A.type="globstar",A.value+=x,A.output=S(t),v.output=A.output,v.globstar=true,ke(x);continue}if(N.type==="slash"&&N.prev.type!=="bos"&&!ve&&Q()){v.output=v.output.slice(0,-(N.output+A.output).length),N.output=`(?:${N.output}`,A.type="globstar",A.output=S(t)+(t.strictSlashes?")":"|$)"),A.value+=x,v.globstar=true,v.output+=N.output+A.output,ke(x);continue}if(N.type==="slash"&&N.prev.type!=="bos"&&F[0]==="/"){let ct=F[1]!==void 0?"|$":"";v.output=v.output.slice(0,-(N.output+A.output).length),N.output=`(?:${N.output}`,A.type="globstar",A.output=`${S(t)}${f}|${f}${ct})`,A.value+=x,v.output+=N.output+A.output,v.globstar=true,ke(x+ne()),R({type:"slash",value:"/",output:""});continue}if(N.type==="bos"&&F[0]==="/"){A.type="globstar",A.value+=x,A.output=`(?:^|${f}|${S(t)}${f})`,v.output=A.output,v.globstar=true,ke(x+ne()),R({type:"slash",value:"/",output:""});continue}v.output=v.output.slice(0,-A.output.length),A.type="globstar",A.output=S(t),A.value+=x,v.output+=A.output,v.globstar=true,ke(x);continue}let Y={type:"star",value:x,output:O};if(t.bash===true){Y.output=".*?",(A.type==="bos"||A.type==="slash")&&(Y.output=w+Y.output),R(Y);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===true){Y.output=x,R(Y);continue}(v.index===v.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(v.output+=_,A.output+=_):t.dot===true?(v.output+=D,A.output+=D):(v.output+=w,A.output+=w),j()!=="*"&&(v.output+=d,A.output+=d)),R(Y);}for(;v.brackets>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing","]"));v.output=Ke.escapeLast(v.output,"["),lt("brackets");}for(;v.parens>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing",")"));v.output=Ke.escapeLast(v.output,"("),lt("parens");}for(;v.braces>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing","}"));v.output=Ke.escapeLast(v.output,"{"),lt("braces");}if(t.strictSlashes!==true&&(A.type==="star"||A.type==="bracket")&&R({type:"maybe_slash",value:"",output:`${f}?`}),v.backtrack===true){v.output="";for(let F of v.tokens)v.output+=F.output!=null?F.output:F.value,F.suffix&&(v.output+=F.suffix);}return v};Du.fastpaths=(i,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(Aa,t.maxLength):Aa,r=i.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);i=Rp[i]||i;let{DOT_LITERAL:a,SLASH_LITERAL:s,ONE_CHAR:o,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:c,NO_DOTS_SLASH:h,STAR:f,START_ANCHOR:d}=qi.globChars(t.windows),g=t.dot?c:u,y=t.dot?h:u,_=t.capture?"":"?:",D={negated:false,prefix:""},m=t.bash===true?".*?":f;t.capture&&(m=`(${m})`);let p=w=>w.noglobstar===true?m:`(${_}(?:(?!${d}${w.dot?l:a}).)*?)`,E=w=>{switch(w){case "*":return `${g}${o}${m}`;case ".*":return `${a}${o}${m}`;case "*.*":return `${g}${m}${a}${o}${m}`;case "*/*":return `${g}${m}${s}${o}${y}${m}`;case "**":return g+p(t);case "**/*":return `(?:${g}${p(t)}${s})?${y}${o}${m}`;case "**/*.*":return `(?:${g}${p(t)}${s})?${y}${m}${a}${o}${m}`;case "**/.*":return `(?:${g}${p(t)}${s})?${a}${o}${m}`;default:{let b=/^(.*?)\.(\w+)$/.exec(w);if(!b)return;let O=E(b[1]);return O?O+a+b[2]:void 0}}},C=Ke.removePrefix(i,D),S=E(C);return S&&t.strictSlashes!==true&&(S+=`${s}?`),S};kp.exports=Du;});var jp=P((yx,Wp)=>{var T0=Ip(),xu=Lp(),Bp=Wi(),P0=Bi(),F0=i=>i&&typeof i=="object"&&!Array.isArray(i),me=(i,e,t=false)=>{if(Array.isArray(i)){let c=i.map(f=>me(f,e,t));return f=>{for(let d of c){let g=d(f);if(g)return g}return false}}let n=F0(i)&&i.tokens&&i.input;if(i===""||typeof i!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},a=r.windows,s=n?me.compileRe(i,e):me.makeRe(i,e,false,true),o=s.state;delete s.state;let l=()=>false;if(r.ignore){let c={...e,ignore:null,onMatch:null,onResult:null};l=me(r.ignore,c,t);}let u=(c,h=false)=>{let{isMatch:f,match:d,output:g}=me.test(c,s,e,{glob:i,posix:a}),y={glob:i,state:o,regex:s,posix:a,input:c,output:g,match:d,isMatch:f};return typeof r.onResult=="function"&&r.onResult(y),f===false?(y.isMatch=false,h?y:false):l(c)?(typeof r.onIgnore=="function"&&r.onIgnore(y),y.isMatch=false,h?y:false):(typeof r.onMatch=="function"&&r.onMatch(y),h?y:true)};return t&&(u.state=o),u};me.test=(i,e,t,{glob:n,posix:r}={})=>{if(typeof i!="string")throw new TypeError("Expected input to be a string");if(i==="")return {isMatch:false,output:""};let a=t||{},s=a.format||(r?Bp.toPosixSlashes:null),o=i===n,l=o&&s?s(i):i;return o===false&&(l=s?s(i):i,o=l===n),(o===false||a.capture===true)&&(a.matchBase===true||a.basename===true?o=me.matchBase(i,e,t,r):o=e.exec(l)),{isMatch:!!o,match:o,output:l}};me.matchBase=(i,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:me.makeRe(e,t)).test(Bp.basename(i,{windows:n}));me.isMatch=(i,e,t)=>me(e,t)(i);me.parse=(i,e)=>Array.isArray(i)?i.map(t=>me.parse(t,e)):xu(i,{...e,fastpaths:false});me.scan=(i,e)=>T0(i,e);me.compileRe=(i,e,t=false,n=false)=>{if(t===true)return i.output;let r=e||{},a=r.contains?"":"^",s=r.contains?"":"$",o=`${a}(?:${i.output})${s}`;i&&i.negated===true&&(o=`^(?!${o}).*$`);let l=me.toRegex(o,e);return n===true&&(l.state=i),l};me.makeRe=(i,e={},t=false,n=false)=>{if(!i||typeof i!="string")throw new TypeError("Expected a non-empty string");let r={negated:false,fastpaths:true};return e.fastpaths!==false&&(i[0]==="."||i[0]==="*")&&(r.output=xu.fastpaths(i,e)),r.output||(r=xu(i,e)),me.compileRe(r,e,t,n)};me.toRegex=(i,e)=>{try{let t=e||{};return new RegExp(i,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===true)throw t;return /$^/}};me.constants=P0;Wp.exports=me;});var Gp=P((vx,$p)=>{var qp=jp(),N0=Wi();function Mp(i,e,t=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:N0.isWindows()}),qp(i,e,t)}Object.assign(Mp,qp);$p.exports=Mp;});var Un="/__pixi-vn-ink/hashtag-commands",$i="/__pixi-vn-ink/text-replaces";var z;(r=>(r.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),r.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),r.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),r.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(z||={});var gf=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,mf=/[\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]/,Cf=/[\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]/,xa={Space_Separator:gf,ID_Start:mf,ID_Continue:Cf},ge={isSpaceSeparator(i){return typeof i=="string"&&xa.Space_Separator.test(i)},isIdStartChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="$"||i==="_"||xa.ID_Start.test(i))},isIdContinueChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="$"||i==="_"||i==="\u200C"||i==="\u200D"||xa.ID_Continue.test(i))},isDigit(i){return typeof i=="string"&&/[0-9]/.test(i)},isHexDigit(i){return typeof i=="string"&&/[0-9A-Fa-f]/.test(i)}},wa,Ne,At,Hi,Nt,st,Ee,Pa,Kn,yf=function(e,t){wa=String(e),Ne="start",At=[],Hi=0,Nt=1,st=0,Ee=void 0,Pa=void 0,Kn=void 0;do Ee=vf(),bf[Ne]();while(Ee.type!=="eof");return typeof t=="function"?Oa({"":Kn},"",t):Kn};function Oa(i,e,t){let n=i[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let r=0;r<n.length;r++){let a=String(r),s=Oa(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let r in n){let a=Oa(n,r,t);a===void 0?delete n[r]:Object.defineProperty(n,r,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(i,e,n)}var q,W,zn,bt,H;function vf(){for(q="default",W="",zn=false,bt=1;;){H=Dt();let i=ku[q]();if(i)return i}}function Dt(){if(wa[Hi])return String.fromCodePoint(wa.codePointAt(Hi))}function T(){let i=Dt();return i===`
45
- `?(Nt++,st=0):i?st+=i.length:st++,i&&(Hi+=i.length),i}var ku={default(){switch(H){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
- `:case "\r":case "\u2028":case "\u2029":T();return;case "/":T(),q="comment";return;case void 0:return T(),le("eof")}if(ge.isSpaceSeparator(H)){T();return}return ku[Ne]()},comment(){switch(H){case "*":T(),q="multiLineComment";return;case "/":T(),q="singleLineComment";return}throw ue(T())},multiLineComment(){switch(H){case "*":T(),q="multiLineCommentAsterisk";return;case void 0:throw ue(T())}T();},multiLineCommentAsterisk(){switch(H){case "*":T();return;case "/":T(),q="default";return;case void 0:throw ue(T())}T(),q="multiLineComment";},singleLineComment(){switch(H){case `
47
- `:case "\r":case "\u2028":case "\u2029":T(),q="default";return;case void 0:return T(),le("eof")}T();},value(){switch(H){case "{":case "[":return le("punctuator",T());case "n":return T(),Xt("ull"),le("null",null);case "t":return T(),Xt("rue"),le("boolean",true);case "f":return T(),Xt("alse"),le("boolean",false);case "-":case "+":T()==="-"&&(bt=-1),q="sign";return;case ".":W=T(),q="decimalPointLeading";return;case "0":W=T(),q="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":W=T(),q="decimalInteger";return;case "I":return T(),Xt("nfinity"),le("numeric",1/0);case "N":return T(),Xt("aN"),le("numeric",NaN);case '"':case "'":zn=T()==='"',W="",q="string";return}throw ue(T())},identifierNameStartEscape(){if(H!=="u")throw ue(T());T();let i=Ta();switch(i){case "$":case "_":break;default:if(!ge.isIdStartChar(i))throw Vu();break}W+=i,q="identifierName";},identifierName(){switch(H){case "$":case "_":case "\u200C":case "\u200D":W+=T();return;case "\\":T(),q="identifierNameEscape";return}if(ge.isIdContinueChar(H)){W+=T();return}return le("identifier",W)},identifierNameEscape(){if(H!=="u")throw ue(T());T();let i=Ta();switch(i){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!ge.isIdContinueChar(i))throw Vu();break}W+=i,q="identifierName";},sign(){switch(H){case ".":W=T(),q="decimalPointLeading";return;case "0":W=T(),q="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":W=T(),q="decimalInteger";return;case "I":return T(),Xt("nfinity"),le("numeric",bt*(1/0));case "N":return T(),Xt("aN"),le("numeric",NaN)}throw ue(T())},zero(){switch(H){case ".":W+=T(),q="decimalPoint";return;case "e":case "E":W+=T(),q="decimalExponent";return;case "x":case "X":W+=T(),q="hexadecimal";return}return le("numeric",bt*0)},decimalInteger(){switch(H){case ".":W+=T(),q="decimalPoint";return;case "e":case "E":W+=T(),q="decimalExponent";return}if(ge.isDigit(H)){W+=T();return}return le("numeric",bt*Number(W))},decimalPointLeading(){if(ge.isDigit(H)){W+=T(),q="decimalFraction";return}throw ue(T())},decimalPoint(){switch(H){case "e":case "E":W+=T(),q="decimalExponent";return}if(ge.isDigit(H)){W+=T(),q="decimalFraction";return}return le("numeric",bt*Number(W))},decimalFraction(){switch(H){case "e":case "E":W+=T(),q="decimalExponent";return}if(ge.isDigit(H)){W+=T();return}return le("numeric",bt*Number(W))},decimalExponent(){switch(H){case "+":case "-":W+=T(),q="decimalExponentSign";return}if(ge.isDigit(H)){W+=T(),q="decimalExponentInteger";return}throw ue(T())},decimalExponentSign(){if(ge.isDigit(H)){W+=T(),q="decimalExponentInteger";return}throw ue(T())},decimalExponentInteger(){if(ge.isDigit(H)){W+=T();return}return le("numeric",bt*Number(W))},hexadecimal(){if(ge.isHexDigit(H)){W+=T(),q="hexadecimalInteger";return}throw ue(T())},hexadecimalInteger(){if(ge.isHexDigit(H)){W+=T();return}return le("numeric",bt*Number(W))},string(){switch(H){case "\\":T(),W+=Sf();return;case '"':if(zn)return T(),le("string",W);W+=T();return;case "'":if(!zn)return T(),le("string",W);W+=T();return;case `
48
- `:case "\r":throw ue(T());case "\u2028":case "\u2029":Af(H);break;case void 0:throw ue(T())}W+=T();},start(){switch(H){case "{":case "[":return le("punctuator",T())}q="value";},beforePropertyName(){switch(H){case "$":case "_":W=T(),q="identifierName";return;case "\\":T(),q="identifierNameStartEscape";return;case "}":return le("punctuator",T());case '"':case "'":zn=T()==='"',q="string";return}if(ge.isIdStartChar(H)){W+=T(),q="identifierName";return}throw ue(T())},afterPropertyName(){if(H===":")return le("punctuator",T());throw ue(T())},beforePropertyValue(){q="value";},afterPropertyValue(){switch(H){case ",":case "}":return le("punctuator",T())}throw ue(T())},beforeArrayValue(){if(H==="]")return le("punctuator",T());q="value";},afterArrayValue(){switch(H){case ",":case "]":return le("punctuator",T())}throw ue(T())},end(){throw ue(T())}};function le(i,e){return {type:i,value:e,line:Nt,column:st}}function Xt(i){for(let e of i){if(Dt()!==e)throw ue(T());T();}}function Sf(){switch(Dt()){case "b":return T(),"\b";case "f":return T(),"\f";case "n":return T(),`
49
- `;case "r":return T(),"\r";case "t":return T()," ";case "v":return T(),"\v";case "0":if(T(),ge.isDigit(Dt()))throw ue(T());return "\0";case "x":return T(),Ef();case "u":return T(),Ta();case `
50
- `:case "\u2028":case "\u2029":return T(),"";case "\r":return T(),Dt()===`
51
- `&&T(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw ue(T());case void 0:throw ue(T())}return T()}function Ef(){let i="",e=Dt();if(!ge.isHexDigit(e)||(i+=T(),e=Dt(),!ge.isHexDigit(e)))throw ue(T());return i+=T(),String.fromCodePoint(parseInt(i,16))}function Ta(){let i="",e=4;for(;e-- >0;){let t=Dt();if(!ge.isHexDigit(t))throw ue(T());i+=T();}return String.fromCodePoint(parseInt(i,16))}var bf={start(){if(Ee.type==="eof")throw Yt();_a();},beforePropertyName(){switch(Ee.type){case "identifier":case "string":Pa=Ee.value,Ne="afterPropertyName";return;case "punctuator":Gi();return;case "eof":throw Yt()}},afterPropertyName(){if(Ee.type==="eof")throw Yt();Ne="beforePropertyValue";},beforePropertyValue(){if(Ee.type==="eof")throw Yt();_a();},beforeArrayValue(){if(Ee.type==="eof")throw Yt();if(Ee.type==="punctuator"&&Ee.value==="]"){Gi();return}_a();},afterPropertyValue(){if(Ee.type==="eof")throw Yt();switch(Ee.value){case ",":Ne="beforePropertyName";return;case "}":Gi();}},afterArrayValue(){if(Ee.type==="eof")throw Yt();switch(Ee.value){case ",":Ne="beforeArrayValue";return;case "]":Gi();}},end(){}};function _a(){let i;switch(Ee.type){case "punctuator":switch(Ee.value){case "{":i={};break;case "[":i=[];break}break;case "null":case "boolean":case "numeric":case "string":i=Ee.value;break}if(Kn===void 0)Kn=i;else {let e=At[At.length-1];Array.isArray(e)?e.push(i):Object.defineProperty(e,Pa,{value:i,writable:true,enumerable:true,configurable:true});}if(i!==null&&typeof i=="object")At.push(i),Array.isArray(i)?Ne="beforeArrayValue":Ne="beforePropertyName";else {let e=At[At.length-1];e==null?Ne="end":Array.isArray(e)?Ne="afterArrayValue":Ne="afterPropertyValue";}}function Gi(){At.pop();let i=At[At.length-1];i==null?Ne="end":Array.isArray(i)?Ne="afterArrayValue":Ne="afterPropertyValue";}function ue(i){return Ji(i===void 0?`JSON5: invalid end of input at ${Nt}:${st}`:`JSON5: invalid character '${Lu(i)}' at ${Nt}:${st}`)}function Yt(){return Ji(`JSON5: invalid end of input at ${Nt}:${st}`)}function Vu(){return st-=5,Ji(`JSON5: invalid identifier character at ${Nt}:${st}`)}function Af(i){console.warn(`JSON5: '${Lu(i)}' in strings is not valid ECMAScript; consider escaping`);}function Lu(i){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[i])return e[i];if(i<" "){let t=i.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return i}function Ji(i){let e=new SyntaxError(i);return e.lineNumber=Nt,e.columnNumber=st,e}var Df=function(e,t,n){let r=[],a="",s,o,l="",u;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,u=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let y of t){let _;typeof y=="string"?_=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(_=String(y)),_!==void 0&&s.indexOf(_)<0&&s.push(_);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),c("",{"":e});function c(y,_){let D=_[y];switch(D!=null&&(typeof D.toJSON5=="function"?D=D.toJSON5(y):typeof D.toJSON=="function"&&(D=D.toJSON(y))),o&&(D=o.call(_,y,D)),D instanceof Number?D=Number(D):D instanceof String?D=String(D):D instanceof Boolean&&(D=D.valueOf()),D){case null:return "null";case true:return "true";case false:return "false"}if(typeof D=="string")return h(D);if(typeof D=="number")return String(D);if(typeof D=="object")return Array.isArray(D)?g(D):f(D)}function h(y){let _={"'":.1,'"':.2},D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},m="";for(let E=0;E<y.length;E++){let C=y[E];switch(C){case "'":case '"':_[C]++,m+=C;continue;case "\0":if(ge.isDigit(y[E+1])){m+="\\x00";continue}}if(D[C]){m+=D[C];continue}if(C<" "){let S=C.charCodeAt(0).toString(16);m+="\\x"+("00"+S).substring(S.length);continue}m+=C;}let p=u||Object.keys(_).reduce((E,C)=>_[E]<_[C]?E:C);return m=m.replace(new RegExp(p,"g"),D[p]),p+m+p}function f(y){if(r.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");r.push(y);let _=a;a=a+l;let D=s||Object.keys(y),m=[];for(let E of D){let C=c(E,y);if(C!==void 0){let S=d(E)+":";l!==""&&(S+=" "),S+=C,m.push(S);}}let p;if(m.length===0)p="{}";else {let E;if(l==="")E=m.join(","),p="{"+E+"}";else {let C=`,
40
+ ~ myFunction()`);let l=(0, Jt.asOrNull)(o,ga.FunctionCall);return l&&(l.shouldPopReturnedValue=true),o.Find(ga.FunctionCall)()!==null&&(o=new He.ContentList(o,new Pt.Text(`
41
+ `))),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 u=this.Expect(this.Expression,"initial value for ");return u?(u instanceof $n.NumberExpression||u instanceof Vi.StringExpression||u instanceof au.DivertTarget||u instanceof lu.VariableReference||u instanceof Jh.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"):u instanceof Vi.StringExpression&&(u.isSingleString||this.Error("Constant strings cannot contain any logic.")),new ou.VariableAssignment({assignedExpression:u,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 l=this.Expect(this.ListDefinition,"list item names");return l?(l.identifier=new ki.Identifier(o.name),new ou.VariableAssignment({variableIdentifier:o,listDef:l})):null},this.ListDefinition=()=>{this.AnyWhitespace();let s=this.SeparatedList(this.ListElementDefinition,this.ListElementDefinitionSeparator);return s===null?null:new vy.ListDefinition(s)},this.ListElementDefinitionSeparator=()=>(this.AnyWhitespace(),this.ParseString(",")===null?null:(this.AnyWhitespace(),",")),this.ListElementDefinition=()=>{let s=this.ParseString("(")!==null,o=s;this.Whitespace();let l=this.Parse(this.IdentifierWithMetadata);if(l===null)return null;this.Whitespace(),s&&this.ParseString(")")!=null&&(o=false,this.Whitespace());let u=null;if(this.ParseString("=")!==null){this.Whitespace();let c=this.Expect(this.ExpressionInt,"value to be assigned to list item");c!==null&&(u=c.value),o&&(this.Whitespace(),this.ParseString(")")!==null&&(o=false));}return o&&this.Error("Expected closing ')'"),new Sy.ListElementDefinition(l,s,u)},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 l=this.Expect(this.Expression,"initial value for ");return l instanceof $n.NumberExpression||l instanceof au.DivertTarget||l instanceof Vi.StringExpression?l instanceof Vi.StringExpression&&(l.isSingleString||this.Error("Constant strings cannot contain any logic.")):this.Error("initial value for a constant must be a number or divert target"),new cy.ConstantDeclaration(o,l)},this.InlineLogicOrGlueOrStartTag=()=>this.OneOf([this.InlineLogic,this.Glue,this.StartTag]),this.Glue=()=>this.ParseString("<>")!==null?new gy.Glue(new my.Glue):null,this.InlineLogic=()=>{if(this.ParseString("{")===null)return null;let s=this.parsingStringExpression,o=this.tagActive;this.Whitespace();let l=this.Expect(this.InnerLogic,"some kind of logic, conditional or sequence within braces: { ... }");if(l===null)return this.parsingStringExpression=s,null;this.DisallowIncrement(l);let u=(0, Jt.asOrNull)(l,He.ContentList);return u||(u=new He.ContentList(l)),this.Whitespace(),this.Expect(this.String("}"),"closing brace '}' for inline logic"),this.parsingStringExpression=s,o||this.EndTagIfNecessary(u),u},this.InnerLogic=()=>{this.Whitespace();let s=this.ParseObject(this.SequenceTypeAnnotation);if(s!==null){let u=this.Expect(this.InnerSequenceObjects,"sequence elements (for cycle/stoping etc)");return u===null?null:new Kh.Sequence(u,s)}let o=this.Parse(this.ConditionExpression);if(o)return this.Expect(()=>this.InnerConditionalContent(o),"conditional content following query");let l=[this.InnerConditionalContent,this.InnerSequence,this.InnerExpression];for(let u of l){let c=this.BeginRule(),h=this.ParseObject(u);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 ki.Identifier(s)},this.Identifier=()=>{let s=this.ParseCharactersFromCharSet(this.identifierCharSet);if(s===null)return null;let o=true;for(let l of s)if(!(l>="0"&&l<="9")){o=false;break}return o?null:s},this._sequenceTypeSymbols=new _e.CharacterSet("!&~$"),this.InnerSequence=()=>{this.Whitespace();let s=xe.SequenceType.Stopping,o=this.Parse(this.SequenceTypeAnnotation);o!==null&&(s=o);let l=this.Parse(this.InnerSequenceObjects);return l===null||l.length<=1?null:new Kh.Sequence(l,s)},this.SequenceTypeAnnotation=()=>{let s=this.Parse(this.SequenceTypeSymbolAnnotation);if(s===null&&(s=this.Parse(this.SequenceTypeWordAnnotation)),s===null)return null;switch(s){case xe.SequenceType.Once:case xe.SequenceType.Cycle:case xe.SequenceType.Stopping:case xe.SequenceType.Shuffle:case xe.SequenceType.Shuffle|xe.SequenceType.Stopping:case xe.SequenceType.Shuffle|xe.SequenceType.Once:break;default:return this.Error(`Sequence type combination not supported: ${s}`),xe.SequenceType.Stopping}return s},this.SequenceTypeSymbolAnnotation=()=>{this._sequenceTypeSymbols===null&&(this._sequenceTypeSymbols=new _e.CharacterSet("!&~$ "));let s=0,o=this.ParseCharactersFromCharSet(this._sequenceTypeSymbols);if(o===null)return null;for(let l of o)switch(l){case "!":s|=xe.SequenceType.Once;break;case "&":s|=xe.SequenceType.Cycle;break;case "~":s|=xe.SequenceType.Shuffle;break;case "$":s|=xe.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 l of s)o|=l;return o},this.SequenceTypeSingleWord=()=>{let s=null,o=this.Parse(this.IdentifierWithMetadata);if(o!==null)switch(o.name){case "once":s=xe.SequenceType.Once;break;case "cycle":s=xe.SequenceType.Cycle;break;case "shuffle":s=xe.SequenceType.Shuffle;break;case "stopping":s=xe.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=[],l=false;for(let u of s)if(u==="|")l||o.push(new He.ContentList),l=false;else {let c=u;c===null?this.Error(`Expected content, but got ${u} (this is an ink compiler bug!)`):o.push(new He.ContentList(c)),l=true;}return l||o.push(new He.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(ke.StatementLevel.InnerBlock);return s===null?this.MultilineWhitespace():s.unshift(new Pt.Text(`
42
+ `)),new He.ContentList(s)},this._statementRulesAtLevel=[],this._statementBreakRulesAtLevel=[],this.StatementsAtLevel=s=>(s===ke.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],l=this.OneOf(o);return s===ke.StatementLevel.Top&&l instanceof zh.ReturnType&&this.Error("should not have return statement outside of a knot"),l},this.StatementsBreakForLevel=s=>{this.Whitespace();let o=this._statementBreakRulesAtLevel[s],l=this.OneOf(o);return l===null?null:l},this.GenerateStatementLevelRules=()=>{let s=Object.values(ke.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 l=[],u=[];l.push(this.Line(this.MultiDivert)),o>=ke.StatementLevel.Top&&l.push(this.KnotDefinition),l.push(this.Line(this.Choice)),l.push(this.Line(this.AuthorWarning)),o>ke.StatementLevel.InnerBlock&&l.push(this.Gather),o>=ke.StatementLevel.Knot&&l.push(this.StitchDefinition),l.push(this.Line(this.ListDeclaration)),l.push(this.Line(this.VariableDeclaration)),l.push(this.Line(this.ConstDeclaration)),l.push(this.Line(this.ExternalDeclaration)),l.push(this.Line(this.IncludeStatement)),l.push(this.LogicLine),l.push(this.LineOfMixedTextAndLogic),o<=ke.StatementLevel.Knot&&u.push(this.KnotDeclaration),o<=ke.StatementLevel.Stitch&&u.push(this.StitchDeclaration),o<=ke.StatementLevel.InnerBlock&&(u.push(this.ParseDashNotArrow),u.push(this.String("}"))),this._statementRulesAtLevel[o]=l,this._statementBreakRulesAtLevel[o]=u;}},this.SkipToNextLine=()=>(this.ParseUntilCharactersFromString(`
43
+ \r`),this.ParseNewline(),Tt.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 He.ContentList;o.AddContent(new Mn.Tag(false)),o.AddContent(new Mn.Tag(true)),s=o;}else s=new Mn.Tag(true);return this.tagActive=true,this.Whitespace(),s},this._inlineWhitespaceChars=new _e.CharacterSet(" "),this.EndOfLine=()=>this.OneOf([this.Newline,this.EndOfFile]),this.Newline=()=>(this.Whitespace(),this.ParseNewline()!==null?Tt.ParseSuccess:null),this.EndOfFile=()=>(this.Whitespace(),this.endOfInput?Tt.ParseSuccess:null),this.MultilineWhitespace=()=>{let s=this.OneOrMore(this.Newline);return s===null?null:s.length>=1?Tt.ParseSuccess:null},this.Whitespace=()=>this.ParseCharactersFromCharSet(this._inlineWhitespaceChars)!==null?Tt.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?Tt.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=n,a===null?this._fileHandler=new xy.DefaultFileHandler:this._fileHandler=a,r===null){if(this._rootParser=this,this._openFilenames=[],this._filename!==null){let s=this.fileHandler.ResolveInkFilename(this._filename);this._openFilenames.push(s);}}else this._rootParser=r;}PreProcessInputString(e){return new ly.CommentEliminator(e).Process()}get parsingStringExpression(){return this.GetFlag(Number(da.CustomFlags.ParsingString))}set parsingStringExpression(e){this.SetFlag(Number(da.CustomFlags.ParsingString),e);}get tagActive(){return this.GetFlag(Number(da.CustomFlags.TagActive))}set tagActive(e){this.SetFlag(Number(da.CustomFlags.TagActive),e);}get identifierCharSet(){return this._identifierCharSet===null&&((this._identifierCharSet=new _e.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 He.ContentList?e.AddContent(new Mn.Tag(false)):e.push(new Mn.Tag(false))),this.tagActive=false);}};Ca.InkParser=se;se.LatinBasic=at.CharacterRange.Define("A","z",new _e.CharacterSet().AddRange("[","`"));se.LatinExtendedA=at.CharacterRange.Define("\u0100","\u017F");se.LatinExtendedB=at.CharacterRange.Define("\u0180","\u024F");se.Greek=at.CharacterRange.Define("\u0370","\u03FF",new _e.CharacterSet().AddRange("\u0378","\u0385").AddCharacters("\u0374\u0375\u0378\u0387\u038B\u038D\u03A2"));se.Cyrillic=at.CharacterRange.Define("\u0400","\u04FF",new _e.CharacterSet().AddRange("\u0482","\u0489"));se.Armenian=at.CharacterRange.Define("\u0530","\u058F",new _e.CharacterSet().AddCharacters("\u0530").AddRange("\u0557","\u0560").AddRange("\u0588","\u058E"));se.Hebrew=at.CharacterRange.Define("\u0590","\u05FF",new _e.CharacterSet);se.Arabic=at.CharacterRange.Define("\u0600","\u06FF",new _e.CharacterSet);se.Korean=at.CharacterRange.Define("\uAC00","\uD7AF",new _e.CharacterSet);se.Latin1Supplement=at.CharacterRange.Define("\x80","\xFF",new _e.CharacterSet);se.Chinese=at.CharacterRange.Define("\u4E00","\u9FFF",new _e.CharacterSet);se.ListAllCharacterRanges=()=>[se.LatinBasic,se.LatinExtendedA,se.LatinExtendedB,se.Arabic,se.Armenian,se.Cyrillic,se.Greek,se.Hebrew,se.Korean,se.Latin1Supplement,se.Chinese];});var Zh=T(ya=>{Object.defineProperty(ya,"__esModule",{value:true});ya.GenerateStoryStats=void 0;var _y=Tn(),wy=In(),Oy=gi(),Ty=_l(),Py=Nl(),Fy=qt();function Ny(i){let e=i.FindAll(Fy.Text)(),t=0;for(let l of e){let u=0,c=true;for(let h of l.text)h==" "||h==" "||h==`
44
+ `||h=="\r"?c=true:c&&(u++,c=false);t+=u;}let n=i.FindAll(Ty.Knot)(),r=i.FindAll(Py.Stitch)(),a=i.FindAll(_y.Choice)(),s=i.FindAll(Oy.Gather)(l=>l.debugMetadata!=null),o=i.FindAll(wy.Divert)();return {words:t,knots:n.length,functions:n.filter(l=>l.isFunction).length,stitches:r.length,gathers:s.length,diverts:o.length-1,choices:a.length}}ya.GenerateStoryStats=Ny;});var ep=T(va=>{Object.defineProperty(va,"__esModule",{value:true});va.JsonFileHandler=void 0;var cu=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}.`)};}};va.JsonFileHandler=cu;});var np=T(Ie=>{Object.defineProperty(Ie,"__esModule",{value:true});Ie.Compiler=Ie.Story=Ie.InkList=Ie.JsonFileHandler=Ie.StatementLevel=Ie.InkParser=Ie.CompilerOptions=void 0;var Iy=Ua(),Ry=cc(),hu=en(),Vy=uu(),ky=de(),Ly=ne(),By=Zh(),Wy=Ua();Object.defineProperty(Ie,"CompilerOptions",{enumerable:true,get:function(){return Wy.CompilerOptions}});var jy=uu();Object.defineProperty(Ie,"InkParser",{enumerable:true,get:function(){return jy.InkParser}});var qy=Pl();Object.defineProperty(Ie,"StatementLevel",{enumerable:true,get:function(){return qy.StatementLevel}});var My=ep();Object.defineProperty(Ie,"JsonFileHandler",{enumerable:true,get:function(){return My.JsonFileHandler}});var tp=xi();Object.defineProperty(Ie,"InkList",{enumerable:true,get:function(){return tp.InkList}});Object.defineProperty(Ie,"Story",{enumerable:true,get:function(){return tp.Story}});var pu=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 Vy.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 n;for(let r of this.runtimeStory.state.outputStream){let a=(0, Ly.asOrNull)(r,ky.StringValue);if(a!==null){let s=new Ry.DebugSourceRange(((n=a.value)===null||n===void 0?void 0:n.length)||0,a.debugMetadata,a.value||"unknown");this.debugSourceRanges.push(s);}}},this.GenerateStats=()=>this._parsedStory===null?null:(0, By.GenerateStoryStats)(this._parsedStory),this.DebugMetadataForContentAtOffset=n=>{let r=0,a=null;for(let s of this.debugSourceRanges){if(s.debugMetadata!==null&&(a=s.debugMetadata),n>=r&&n<r+s.length)return a;r+=s.length;}return null},this.OnError=(n,r)=>{switch(r){case hu.ErrorType.Author:this._authorMessages.push(n);break;case hu.ErrorType.Warning:this._warnings.push(n);break;case hu.ErrorType.Error:this._errors.push(n);break}this.options.errorHandler!==null&&this.options.errorHandler(n,r);},this._inputString=e,this._options=t||new Iy.CompilerOptions;}};Ie.Compiler=pu;});var up=T((rx,gu)=>{var ba=process||{},op=ba.argv||[],Ea=ba.env||{},Xy=!(Ea.NO_COLOR||op.includes("--no-color"))&&(!!Ea.FORCE_COLOR||op.includes("--color")||ba.platform==="win32"||(ba.stdout||{}).isTTY&&Ea.TERM!=="dumb"||!!Ea.CI),Yy=(i,e,t=i)=>n=>{let r=""+n,a=r.indexOf(e,i.length);return ~a?i+Qy(r,e,t,a)+e:i+r+e},Qy=(i,e,t,n)=>{let r="",a=0;do r+=i.substring(a,n)+t,a=n+e.length,n=i.indexOf(e,a);while(~n);return r+i.substring(a)},lp=(i=Xy)=>{let e=i?Yy:()=>String;return {isColorSupported:i,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")}};gu.exports=lp();gu.exports.createColors=lp;});var Bi=T((dx,xp)=>{var Ep="[^\\\\/]",Qv="(?=.)",bp="[^/]",yu="(?:\\/|$)",Ap="(?:^|\\/)",vu=`\\.{1,2}${yu}`,Zv="(?!\\.)",e0=`(?!${Ap}${vu})`,t0=`(?!\\.{0,1}${yu})`,n0=`(?!${vu})`,i0="[^.\\/]",r0=`${bp}*?`,s0="/",Dp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Qv,QMARK:bp,END_ANCHOR:yu,DOTS_SLASH:vu,NO_DOT:Zv,NO_DOTS:e0,NO_DOT_SLASH:t0,NO_DOTS_SLASH:n0,QMARK_NO_DOT:i0,STAR:r0,START_ANCHOR:Ap,SEP:s0},a0={...Dp,SLASH_LITERAL:"[\\\\/]",QMARK:Ep,STAR:`${Ep}*?`,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:"\\"},o0={__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"};xp.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:o0,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(i){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${i.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(i){return i===true?a0:Dp}};});var Wi=T(Je=>{var{REGEX_BACKSLASH:l0,REGEX_REMOVE_BACKSLASH:u0,REGEX_SPECIAL_CHARS:c0,REGEX_SPECIAL_CHARS_GLOBAL:h0}=Bi();Je.isObject=i=>i!==null&&typeof i=="object"&&!Array.isArray(i);Je.hasRegexChars=i=>c0.test(i);Je.isRegexChar=i=>i.length===1&&Je.hasRegexChars(i);Je.escapeRegex=i=>i.replace(h0,"\\$1");Je.toPosixSlashes=i=>i.replace(l0,"/");Je.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let i=navigator.platform.toLowerCase();return i==="win32"||i==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Je.removeBackslashes=i=>i.replace(u0,e=>e==="\\"?"":e);Je.escapeLast=(i,e,t)=>{let n=i.lastIndexOf(e,t);return n===-1?i:i[n-1]==="\\"?Je.escapeLast(i,e,n-1):`${i.slice(0,n)}\\${i.slice(n)}`};Je.removePrefix=(i,e={})=>{let t=i;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Je.wrapOutput=(i,e={},t={})=>{let n=t.contains?"":"^",r=t.contains?"":"$",a=`${n}(?:${i})${r}`;return e.negated===true&&(a=`(?:^(?!${a}).*$)`),a};Je.basename=(i,{windows:e}={})=>{let t=i.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n};});var Ip=T((mx,Np)=>{var _p=Wi(),{CHAR_ASTERISK:Su,CHAR_AT:p0,CHAR_BACKWARD_SLASH:ji,CHAR_COMMA:f0,CHAR_DOT:Eu,CHAR_EXCLAMATION_MARK:bu,CHAR_FORWARD_SLASH:Fp,CHAR_LEFT_CURLY_BRACE:Au,CHAR_LEFT_PARENTHESES:Du,CHAR_LEFT_SQUARE_BRACKET:d0,CHAR_PLUS:g0,CHAR_QUESTION_MARK:wp,CHAR_RIGHT_CURLY_BRACE:m0,CHAR_RIGHT_PARENTHESES:Op,CHAR_RIGHT_SQUARE_BRACKET:C0}=Bi(),Tp=i=>i===Fp||i===ji,Pp=i=>{i.isPrefix!==true&&(i.depth=i.isGlobstar?1/0:1);},y0=(i,e)=>{let t=e||{},n=i.length-1,r=t.parts===true||t.scanToEnd===true,a=[],s=[],o=[],l=i,u=-1,c=0,h=0,f=false,d=false,g=false,y=false,_=false,D=false,m=false,p=false,E=false,C=false,S=0,w,P,x={value:"",depth:0,isGlob:false},v=()=>u>=n,I=()=>l.charCodeAt(u+1),V=()=>(w=P,l.charCodeAt(++u));for(;u<n;){P=V();let B;if(P===ji){m=x.backslashes=true,P=V(),P===Au&&(D=true);continue}if(D===true||P===Au){for(S++;v()!==true&&(P=V());){if(P===ji){m=x.backslashes=true,V();continue}if(P===Au){S++;continue}if(D!==true&&P===Eu&&(P=V())===Eu){if(f=x.isBrace=true,g=x.isGlob=true,C=true,r===true)continue;break}if(D!==true&&P===f0){if(f=x.isBrace=true,g=x.isGlob=true,C=true,r===true)continue;break}if(P===m0&&(S--,S===0)){D=false,f=x.isBrace=true,C=true;break}}if(r===true)continue;break}if(P===Fp){if(a.push(u),s.push(x),x={value:"",depth:0,isGlob:false},C===true)continue;if(w===Eu&&u===c+1){c+=2;continue}h=u+1;continue}if(t.noext!==true&&(P===g0||P===p0||P===Su||P===wp||P===bu)===true&&I()===Du){if(g=x.isGlob=true,y=x.isExtglob=true,C=true,P===bu&&u===c&&(E=true),r===true){for(;v()!==true&&(P=V());){if(P===ji){m=x.backslashes=true,P=V();continue}if(P===Op){g=x.isGlob=true,C=true;break}}continue}break}if(P===Su){if(w===Su&&(_=x.isGlobstar=true),g=x.isGlob=true,C=true,r===true)continue;break}if(P===wp){if(g=x.isGlob=true,C=true,r===true)continue;break}if(P===d0){for(;v()!==true&&(B=V());){if(B===ji){m=x.backslashes=true,V();continue}if(B===C0){d=x.isBracket=true,g=x.isGlob=true,C=true;break}}if(r===true)continue;break}if(t.nonegate!==true&&P===bu&&u===c){p=x.negated=true,c++;continue}if(t.noparen!==true&&P===Du){if(g=x.isGlob=true,r===true){for(;v()!==true&&(P=V());){if(P===Du){m=x.backslashes=true,P=V();continue}if(P===Op){C=true;break}}continue}break}if(g===true){if(C=true,r===true)continue;break}}t.noext===true&&(y=false,g=false);let R=l,b="",A="";c>0&&(b=l.slice(0,c),l=l.slice(c),h-=c),R&&g===true&&h>0?(R=l.slice(0,h),A=l.slice(h)):g===true?(R="",A=l):R=l,R&&R!==""&&R!=="/"&&R!==l&&Tp(R.charCodeAt(R.length-1))&&(R=R.slice(0,-1)),t.unescape===true&&(A&&(A=_p.removeBackslashes(A)),R&&m===true&&(R=_p.removeBackslashes(R)));let he={prefix:b,input:i,start:c,base:R,glob:A,isBrace:f,isBracket:d,isGlob:g,isExtglob:y,isGlobstar:_,negated:p,negatedExtglob:E};if(t.tokens===true&&(he.maxDepth=0,Tp(P)||s.push(x),he.tokens=s),t.parts===true||t.tokens===true){let B;for(let U=0;U<a.length;U++){let Le=B?B+1:c,we=a[U],ot=i.slice(Le,we);t.tokens&&(U===0&&c!==0?(s[U].isPrefix=true,s[U].value=b):s[U].value=ot,Pp(s[U]),he.maxDepth+=s[U].depth),(U!==0||ot!=="")&&o.push(ot),B=we;}if(B&&B+1<i.length){let U=i.slice(B+1);o.push(U),t.tokens&&(s[s.length-1].value=U,Pp(s[s.length-1]),he.maxDepth+=s[s.length-1].depth);}he.slashes=a,he.parts=o;}return he};Np.exports=y0;});var Lp=T((Cx,kp)=>{var qi=Bi(),Ke=Wi(),{MAX_LENGTH:Da,POSIX_REGEX_SOURCE:v0,REGEX_NON_SPECIAL_CHARS:S0,REGEX_SPECIAL_CHARS_BACKREF:E0,REPLACEMENTS:Rp}=qi,b0=(i,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...i,e);i.sort();let t=`[${i.join("-")}]`;try{new RegExp(t);}catch{return i.map(r=>Ke.escapeRegex(r)).join("..")}return t},Gn=(i,e)=>`Missing ${i}: "${e}" - use "\\\\${e}" to match literal characters`,Vp=i=>{let e=[],t=0,n=0,r=0,a="",s=false;for(let o of i){if(s===true){a+=o,s=false;continue}if(o==="\\"){a+=o,s=true;continue}if(o==='"'){r=r===1?0:1,a+=o;continue}if(r===0){if(o==="[")t++;else if(o==="]"&&t>0)t--;else if(t===0){if(o==="(")n++;else if(o===")"&&n>0)n--;else if(o==="|"&&n===0){e.push(a),a="";continue}}}a+=o;}return e.push(a),e},A0=i=>{let e=false;for(let t of i){if(e===true){e=false;continue}if(t==="\\"){e=true;continue}if(/[?*+@!()[\]{}]/.test(t))return false}return true},_u=i=>{let e=i.trim(),t=true;for(;t===true;)t=false,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=true);if(A0(e))return e.replace(/\\(.)/g,"$1")},D0=i=>{let e=i.map(_u).filter(Boolean);for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let r=e[t],a=e[n],s=r[0];if(!(!s||r!==s.repeat(r.length)||a!==s.repeat(a.length))&&(r===a||r.startsWith(a)||a.startsWith(r)))return true}return false},xu=(i,e=true)=>{if(i[0]!=="+"&&i[0]!=="*"||i[1]!=="(")return;let t=0,n=0,r=0,a=false;for(let s=1;s<i.length;s++){let o=i[s];if(a===true){a=false;continue}if(o==="\\"){a=true;continue}if(o==='"'){r=r===1?0:1;continue}if(r!==1){if(o==="["){t++;continue}if(o==="]"&&t>0){t--;continue}if(!(t>0)){if(o==="("){n++;continue}if(o===")"&&(n--,n===0))return e===true&&s!==i.length-1?void 0:{type:i[0],body:i.slice(2,s),end:s}}}}},x0=i=>`${i.length===1?Ke.escapeRegex(i[0]):`[${i.map(t=>Ke.escapeRegex(t)).join("")}]`}*`,_0=i=>{let e=0,t=[];for(;e<i.length;){let n=xu(i.slice(e),false);if(!n||n.type!=="*")return;let r=Vp(n.body).map(s=>s.trim());if(r.length!==1)return;let a=_u(r[0]);if(!a||a.length!==1)return;t.push(a),e+=n.end+1;}if(!(t.length<1))return t},w0=i=>{let e=0,t=i.trim(),n=xu(t);for(;n;)e++,t=n.body.trim(),n=xu(t);return e},O0=(i,e)=>{if(e.maxExtglobRecursion===false)return {risky:false};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:qi.DEFAULT_MAX_EXTGLOB_RECURSION,n=Vp(i).map(o=>o.trim());if(n.length>1&&(n.some(o=>o==="")||n.some(o=>/^[*?]+$/.test(o))||D0(n)))return {risky:true};let r=[],a=false,s=true;for(let o of n){let l=_0(o);if(l){a=true,r.push(...l);continue}let u=_u(o);if(u&&u.length===1){r.push(u);continue}if(s=false,w0(o)>t)return {risky:true}}return a?s?{risky:true,safeOutput:x0([...new Set(r)])}:{risky:true}:{risky:false}},wu=(i,e)=>{if(typeof i!="string")throw new TypeError("Expected a string");i=Rp[i]||i;let t={...e},n=typeof t.maxLength=="number"?Math.min(Da,t.maxLength):Da,r=i.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);let a={type:"bos",value:"",output:t.prepend||""},s=[a],o=t.capture?"":"?:",l=qi.globChars(t.windows),u=qi.extglobChars(l),{DOT_LITERAL:c,PLUS_LITERAL:h,SLASH_LITERAL:f,ONE_CHAR:d,DOTS_SLASH:g,NO_DOT:y,NO_DOT_SLASH:_,NO_DOTS_SLASH:D,QMARK:m,QMARK_NO_DOT:p,STAR:E,START_ANCHOR:C}=l,S=F=>`(${o}(?:(?!${C}${F.dot?g:c}).)*?)`,w=t.dot?"":y,P=t.dot?m:p,x=t.bash===true?S(t):E;t.capture&&(x=`(${x})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let v={input:i,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};i=Ke.removePrefix(i,v),r=i.length;let I=[],V=[],R=[],b=a,A,he=()=>v.index===r-1,B=v.peek=(F=1)=>i[v.index+F],U=v.advance=()=>i[++v.index]||"",Le=()=>i.slice(v.index+1),we=(F="",G=0)=>{v.consumed+=F,v.index+=G;},ot=F=>{v.output+=F.output!=null?F.output:F.value,we(F.value);},$i=()=>{let F=1;for(;B()==="!"&&(B(2)!=="("||B(3)==="?");)U(),v.start++,F++;return F%2===0?false:(v.negated=true,v.start++,true)},gn=F=>{v[F]++,R.push(F);},lt=F=>{v[F]--,R.pop();},q=F=>{if(b.type==="globstar"){let G=v.braces>0&&(F.type==="comma"||F.type==="brace"),N=F.extglob===true||I.length&&(F.type==="pipe"||F.type==="paren");F.type!=="slash"&&F.type!=="paren"&&!G&&!N&&(v.output=v.output.slice(0,-b.output.length),b.type="star",b.value="*",b.output=x,v.output+=b.output);}if(I.length&&F.type!=="paren"&&(I[I.length-1].inner+=F.value),(F.value||F.output)&&ot(F),b&&b.type==="text"&&F.type==="text"){b.output=(b.output||b.value)+F.value,b.value+=F.value;return}F.prev=b,s.push(F),b=F;},ae=(F,G)=>{let N={...u[G],conditions:1,inner:""};N.prev=b,N.parens=v.parens,N.output=v.output,N.startIndex=v.index,N.tokensIndex=s.length;let M=(t.capture?"(":"")+N.open;gn("parens"),q({type:F,value:G,output:v.output?"":d}),q({type:"paren",extglob:true,value:U(),output:M}),I.push(N);},it=F=>{let G=i.slice(F.startIndex,v.index+1),N=i.slice(F.startIndex+2,v.index),M=O0(N,t);if((F.type==="plus"||F.type==="star")&&M.risky){let ie=M.safeOutput?(F.output?"":d)+(t.capture?`(${M.safeOutput})`:M.safeOutput):void 0,ut=s[F.tokensIndex];ut.type="text",ut.value=G,ut.output=ie||Ke.escapeRegex(G);for(let ct=F.tokensIndex+1;ct<s.length;ct++)s[ct].value="",s[ct].output="",delete s[ct].suffix;v.output=F.output+ut.output,v.backtrack=true,q({type:"paren",extglob:true,value:A,output:""}),lt("parens");return}let oe=F.close+(t.capture?")":""),Se;if(F.type==="negate"){let ie=x;if(F.inner&&F.inner.length>1&&F.inner.includes("/")&&(ie=S(t)),(ie!==x||he()||/^\)+$/.test(Le()))&&(oe=F.close=`)$))${ie}`),F.inner.includes("*")&&(Se=Le())&&/^\.[^\\/.]+$/.test(Se)){let ut=wu(Se,{...e,fastpaths:false}).output;oe=F.close=`)${ut})${ie})`;}F.prev.type==="bos"&&(v.negatedExtglob=true);}q({type:"paren",extglob:true,value:A,output:oe}),lt("parens");};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(i)){let F=false,G=i.replace(E0,(N,M,oe,Se,ie,ut)=>Se==="\\"?(F=true,N):Se==="?"?M?M+Se+(ie?m.repeat(ie.length):""):ut===0?P+(ie?m.repeat(ie.length):""):m.repeat(oe.length):Se==="."?c.repeat(oe.length):Se==="*"?M?M+Se+(ie?x:""):x:M?N:`\\${N}`);return F===true&&(t.unescape===true?G=G.replace(/\\/g,""):G=G.replace(/\\+/g,N=>N.length%2===0?"\\\\":N?"\\":"")),G===i&&t.contains===true?(v.output=i,v):(v.output=Ke.wrapOutput(G,v,e),v)}for(;!he();){if(A=U(),A==="\0")continue;if(A==="\\"){let N=B();if(N==="/"&&t.bash!==true||N==="."||N===";")continue;if(!N){A+="\\",q({type:"text",value:A});continue}let M=/^\\+/.exec(Le()),oe=0;if(M&&M[0].length>2&&(oe=M[0].length,v.index+=oe,oe%2!==0&&(A+="\\")),t.unescape===true?A=U():A+=U(),v.brackets===0){q({type:"text",value:A});continue}}if(v.brackets>0&&(A!=="]"||b.value==="["||b.value==="[^")){if(t.posix!==false&&A===":"){let N=b.value.slice(1);if(N.includes("[")&&(b.posix=true,N.includes(":"))){let M=b.value.lastIndexOf("["),oe=b.value.slice(0,M),Se=b.value.slice(M+2),ie=v0[Se];if(ie){b.value=oe+ie,v.backtrack=true,U(),!a.output&&s.indexOf(b)===1&&(a.output=d);continue}}}(A==="["&&B()!==":"||A==="-"&&B()==="]")&&(A=`\\${A}`),A==="]"&&(b.value==="["||b.value==="[^")&&(A=`\\${A}`),t.posix===true&&A==="!"&&b.value==="["&&(A="^"),b.value+=A,ot({value:A});continue}if(v.quotes===1&&A!=='"'){A=Ke.escapeRegex(A),b.value+=A,ot({value:A});continue}if(A==='"'){v.quotes=v.quotes===1?0:1,t.keepQuotes===true&&q({type:"text",value:A});continue}if(A==="("){gn("parens"),q({type:"paren",value:A});continue}if(A===")"){if(v.parens===0&&t.strictBrackets===true)throw new SyntaxError(Gn("opening","("));let N=I[I.length-1];if(N&&v.parens===N.parens+1){it(I.pop());continue}q({type:"paren",value:A,output:v.parens?")":"\\)"}),lt("parens");continue}if(A==="["){if(t.nobracket===true||!Le().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true)throw new SyntaxError(Gn("closing","]"));A=`\\${A}`;}else gn("brackets");q({type:"bracket",value:A});continue}if(A==="]"){if(t.nobracket===true||b&&b.type==="bracket"&&b.value.length===1){q({type:"text",value:A,output:`\\${A}`});continue}if(v.brackets===0){if(t.strictBrackets===true)throw new SyntaxError(Gn("opening","["));q({type:"text",value:A,output:`\\${A}`});continue}lt("brackets");let N=b.value.slice(1);if(b.posix!==true&&N[0]==="^"&&!N.includes("/")&&(A=`/${A}`),b.value+=A,ot({value:A}),t.literalBrackets===false||Ke.hasRegexChars(N))continue;let M=Ke.escapeRegex(b.value);if(v.output=v.output.slice(0,-b.value.length),t.literalBrackets===true){v.output+=M,b.value=M;continue}b.value=`(${o}${M}|${b.value})`,v.output+=b.value;continue}if(A==="{"&&t.nobrace!==true){gn("braces");let N={type:"brace",value:A,output:"(",outputIndex:v.output.length,tokensIndex:v.tokens.length};V.push(N),q(N);continue}if(A==="}"){let N=V[V.length-1];if(t.nobrace===true||!N){q({type:"text",value:A,output:A});continue}let M=")";if(N.dots===true){let oe=s.slice(),Se=[];for(let ie=oe.length-1;ie>=0&&(s.pop(),oe[ie].type!=="brace");ie--)oe[ie].type!=="dots"&&Se.unshift(oe[ie].value);M=b0(Se,t),v.backtrack=true;}if(N.comma!==true&&N.dots!==true){let oe=v.output.slice(0,N.outputIndex),Se=v.tokens.slice(N.tokensIndex);N.value=N.output="\\{",A=M="\\}",v.output=oe;for(let ie of Se)v.output+=ie.output||ie.value;}q({type:"brace",value:A,output:M}),lt("braces"),V.pop();continue}if(A==="|"){I.length>0&&I[I.length-1].conditions++,q({type:"text",value:A});continue}if(A===","){let N=A,M=V[V.length-1];M&&R[R.length-1]==="braces"&&(M.comma=true,N="|"),q({type:"comma",value:A,output:N});continue}if(A==="/"){if(b.type==="dot"&&v.index===v.start+1){v.start=v.index+1,v.consumed="",v.output="",s.pop(),b=a;continue}q({type:"slash",value:A,output:f});continue}if(A==="."){if(v.braces>0&&b.type==="dot"){b.value==="."&&(b.output=c);let N=V[V.length-1];b.type="dots",b.output+=A,b.value+=A,N.dots=true;continue}if(v.braces+v.parens===0&&b.type!=="bos"&&b.type!=="slash"){q({type:"text",value:A,output:c});continue}q({type:"dot",value:A,output:c});continue}if(A==="?"){if(!(b&&b.value==="(")&&t.noextglob!==true&&B()==="("&&B(2)!=="?"){ae("qmark",A);continue}if(b&&b.type==="paren"){let M=B(),oe=A;(b.value==="("&&!/[!=<:]/.test(M)||M==="<"&&!/<([!=]|\w+>)/.test(Le()))&&(oe=`\\${A}`),q({type:"text",value:A,output:oe});continue}if(t.dot!==true&&(b.type==="slash"||b.type==="bos")){q({type:"qmark",value:A,output:p});continue}q({type:"qmark",value:A,output:m});continue}if(A==="!"){if(t.noextglob!==true&&B()==="("&&(B(2)!=="?"||!/[!=<:]/.test(B(3)))){ae("negate",A);continue}if(t.nonegate!==true&&v.index===0){$i();continue}}if(A==="+"){if(t.noextglob!==true&&B()==="("&&B(2)!=="?"){ae("plus",A);continue}if(b&&b.value==="("||t.regex===false){q({type:"plus",value:A,output:h});continue}if(b&&(b.type==="bracket"||b.type==="paren"||b.type==="brace")||v.parens>0){q({type:"plus",value:A});continue}q({type:"plus",value:h});continue}if(A==="@"){if(t.noextglob!==true&&B()==="("&&B(2)!=="?"){q({type:"at",extglob:true,value:A,output:""});continue}q({type:"text",value:A});continue}if(A!=="*"){(A==="$"||A==="^")&&(A=`\\${A}`);let N=S0.exec(Le());N&&(A+=N[0],v.index+=N[0].length),q({type:"text",value:A});continue}if(b&&(b.type==="globstar"||b.star===true)){b.type="star",b.star=true,b.value+=A,b.output=x,v.backtrack=true,v.globstar=true,we(A);continue}let F=Le();if(t.noextglob!==true&&/^\([^?]/.test(F)){ae("star",A);continue}if(b.type==="star"){if(t.noglobstar===true){we(A);continue}let N=b.prev,M=N.prev,oe=N.type==="slash"||N.type==="bos",Se=M&&(M.type==="star"||M.type==="globstar");if(t.bash===true&&(!oe||F[0]&&F[0]!=="/")){q({type:"star",value:A,output:""});continue}let ie=v.braces>0&&(N.type==="comma"||N.type==="brace"),ut=I.length&&(N.type==="pipe"||N.type==="paren");if(!oe&&N.type!=="paren"&&!ie&&!ut){q({type:"star",value:A,output:""});continue}for(;F.slice(0,3)==="/**";){let ct=i[v.index+4];if(ct&&ct!=="/")break;F=F.slice(3),we("/**",3);}if(N.type==="bos"&&he()){b.type="globstar",b.value+=A,b.output=S(t),v.output=b.output,v.globstar=true,we(A);continue}if(N.type==="slash"&&N.prev.type!=="bos"&&!Se&&he()){v.output=v.output.slice(0,-(N.output+b.output).length),N.output=`(?:${N.output}`,b.type="globstar",b.output=S(t)+(t.strictSlashes?")":"|$)"),b.value+=A,v.globstar=true,v.output+=N.output+b.output,we(A);continue}if(N.type==="slash"&&N.prev.type!=="bos"&&F[0]==="/"){let ct=F[1]!==void 0?"|$":"";v.output=v.output.slice(0,-(N.output+b.output).length),N.output=`(?:${N.output}`,b.type="globstar",b.output=`${S(t)}${f}|${f}${ct})`,b.value+=A,v.output+=N.output+b.output,v.globstar=true,we(A+U()),q({type:"slash",value:"/",output:""});continue}if(N.type==="bos"&&F[0]==="/"){b.type="globstar",b.value+=A,b.output=`(?:^|${f}|${S(t)}${f})`,v.output=b.output,v.globstar=true,we(A+U()),q({type:"slash",value:"/",output:""});continue}v.output=v.output.slice(0,-b.output.length),b.type="globstar",b.output=S(t),b.value+=A,v.output+=b.output,v.globstar=true,we(A);continue}let G={type:"star",value:A,output:x};if(t.bash===true){G.output=".*?",(b.type==="bos"||b.type==="slash")&&(G.output=w+G.output),q(G);continue}if(b&&(b.type==="bracket"||b.type==="paren")&&t.regex===true){G.output=A,q(G);continue}(v.index===v.start||b.type==="slash"||b.type==="dot")&&(b.type==="dot"?(v.output+=_,b.output+=_):t.dot===true?(v.output+=D,b.output+=D):(v.output+=w,b.output+=w),B()!=="*"&&(v.output+=d,b.output+=d)),q(G);}for(;v.brackets>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing","]"));v.output=Ke.escapeLast(v.output,"["),lt("brackets");}for(;v.parens>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing",")"));v.output=Ke.escapeLast(v.output,"("),lt("parens");}for(;v.braces>0;){if(t.strictBrackets===true)throw new SyntaxError(Gn("closing","}"));v.output=Ke.escapeLast(v.output,"{"),lt("braces");}if(t.strictSlashes!==true&&(b.type==="star"||b.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${f}?`}),v.backtrack===true){v.output="";for(let F of v.tokens)v.output+=F.output!=null?F.output:F.value,F.suffix&&(v.output+=F.suffix);}return v};wu.fastpaths=(i,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(Da,t.maxLength):Da,r=i.length;if(r>n)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`);i=Rp[i]||i;let{DOT_LITERAL:a,SLASH_LITERAL:s,ONE_CHAR:o,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:c,NO_DOTS_SLASH:h,STAR:f,START_ANCHOR:d}=qi.globChars(t.windows),g=t.dot?c:u,y=t.dot?h:u,_=t.capture?"":"?:",D={negated:false,prefix:""},m=t.bash===true?".*?":f;t.capture&&(m=`(${m})`);let p=w=>w.noglobstar===true?m:`(${_}(?:(?!${d}${w.dot?l:a}).)*?)`,E=w=>{switch(w){case "*":return `${g}${o}${m}`;case ".*":return `${a}${o}${m}`;case "*.*":return `${g}${m}${a}${o}${m}`;case "*/*":return `${g}${m}${s}${o}${y}${m}`;case "**":return g+p(t);case "**/*":return `(?:${g}${p(t)}${s})?${y}${o}${m}`;case "**/*.*":return `(?:${g}${p(t)}${s})?${y}${m}${a}${o}${m}`;case "**/.*":return `(?:${g}${p(t)}${s})?${a}${o}${m}`;default:{let P=/^(.*?)\.(\w+)$/.exec(w);if(!P)return;let x=E(P[1]);return x?x+a+P[2]:void 0}}},C=Ke.removePrefix(i,D),S=E(C);return S&&t.strictSlashes!==true&&(S+=`${s}?`),S};kp.exports=wu;});var jp=T((yx,Wp)=>{var T0=Ip(),Ou=Lp(),Bp=Wi(),P0=Bi(),F0=i=>i&&typeof i=="object"&&!Array.isArray(i),Ce=(i,e,t=false)=>{if(Array.isArray(i)){let c=i.map(f=>Ce(f,e,t));return f=>{for(let d of c){let g=d(f);if(g)return g}return false}}let n=F0(i)&&i.tokens&&i.input;if(i===""||typeof i!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},a=r.windows,s=n?Ce.compileRe(i,e):Ce.makeRe(i,e,false,true),o=s.state;delete s.state;let l=()=>false;if(r.ignore){let c={...e,ignore:null,onMatch:null,onResult:null};l=Ce(r.ignore,c,t);}let u=(c,h=false)=>{let{isMatch:f,match:d,output:g}=Ce.test(c,s,e,{glob:i,posix:a}),y={glob:i,state:o,regex:s,posix:a,input:c,output:g,match:d,isMatch:f};return typeof r.onResult=="function"&&r.onResult(y),f===false?(y.isMatch=false,h?y:false):l(c)?(typeof r.onIgnore=="function"&&r.onIgnore(y),y.isMatch=false,h?y:false):(typeof r.onMatch=="function"&&r.onMatch(y),h?y:true)};return t&&(u.state=o),u};Ce.test=(i,e,t,{glob:n,posix:r}={})=>{if(typeof i!="string")throw new TypeError("Expected input to be a string");if(i==="")return {isMatch:false,output:""};let a=t||{},s=a.format||(r?Bp.toPosixSlashes:null),o=i===n,l=o&&s?s(i):i;return o===false&&(l=s?s(i):i,o=l===n),(o===false||a.capture===true)&&(a.matchBase===true||a.basename===true?o=Ce.matchBase(i,e,t,r):o=e.exec(l)),{isMatch:!!o,match:o,output:l}};Ce.matchBase=(i,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:Ce.makeRe(e,t)).test(Bp.basename(i,{windows:n}));Ce.isMatch=(i,e,t)=>Ce(e,t)(i);Ce.parse=(i,e)=>Array.isArray(i)?i.map(t=>Ce.parse(t,e)):Ou(i,{...e,fastpaths:false});Ce.scan=(i,e)=>T0(i,e);Ce.compileRe=(i,e,t=false,n=false)=>{if(t===true)return i.output;let r=e||{},a=r.contains?"":"^",s=r.contains?"":"$",o=`${a}(?:${i.output})${s}`;i&&i.negated===true&&(o=`^(?!${o}).*$`);let l=Ce.toRegex(o,e);return n===true&&(l.state=i),l};Ce.makeRe=(i,e={},t=false,n=false)=>{if(!i||typeof i!="string")throw new TypeError("Expected a non-empty string");let r={negated:false,fastpaths:true};return e.fastpaths!==false&&(i[0]==="."||i[0]==="*")&&(r.output=Ou.fastpaths(i,e)),r.output||(r=Ou(i,e)),Ce.compileRe(r,e,t,n)};Ce.toRegex=(i,e)=>{try{let t=e||{};return new RegExp(i,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===true)throw t;return /$^/}};Ce.constants=P0;Wp.exports=Ce;});var Gp=T((vx,$p)=>{var qp=jp(),N0=Wi();function Mp(i,e,t=false){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:N0.isWindows()}),qp(i,e,t)}Object.assign(Mp,qp);$p.exports=Mp;});var Un="/__pixi-vn-ink/hashtag-commands",Gi="/__pixi-vn-ink/text-replaces";var X;(r=>(r.log=(a,...s)=>console.log(`[Pixi\u2019VN Ink] ${a}`,...s),r.warn=(a,...s)=>console.warn(`[Pixi\u2019VN Ink] ${a}`,...s),r.error=(a,...s)=>console.error(`[Pixi\u2019VN Ink] ${a}`,...s),r.info=(a,...s)=>console.info(`[Pixi\u2019VN Ink] ${a}`,...s)))(X||={});var gf=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,mf=/[\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]/,Cf=/[\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]/,wa={Space_Separator:gf,ID_Start:mf,ID_Continue:Cf},me={isSpaceSeparator(i){return typeof i=="string"&&wa.Space_Separator.test(i)},isIdStartChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="$"||i==="_"||wa.ID_Start.test(i))},isIdContinueChar(i){return typeof i=="string"&&(i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="$"||i==="_"||i==="\u200C"||i==="\u200D"||wa.ID_Continue.test(i))},isDigit(i){return typeof i=="string"&&/[0-9]/.test(i)},isHexDigit(i){return typeof i=="string"&&/[0-9A-Fa-f]/.test(i)}},Ta,Re,Dt,Ji,Nt,rt,be,Na,Kn,yf=function(e,t){Ta=String(e),Re="start",Dt=[],Ji=0,Nt=1,rt=0,be=void 0,Na=void 0,Kn=void 0;do be=vf(),bf[Re]();while(be.type!=="eof");return typeof t=="function"?Pa({"":Kn},"",t):Kn};function Pa(i,e,t){let n=i[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let r=0;r<n.length;r++){let a=String(r),s=Pa(n,a,t);s===void 0?delete n[a]:Object.defineProperty(n,a,{value:s,writable:true,enumerable:true,configurable:true});}else for(let r in n){let a=Pa(n,r,t);a===void 0?delete n[r]:Object.defineProperty(n,r,{value:a,writable:true,enumerable:true,configurable:true});}return t.call(i,e,n)}var j,W,zn,At,J;function vf(){for(j="default",W="",zn=false,At=1;;){J=xt();let i=Lu[j]();if(i)return i}}function xt(){if(Ta[Ji])return String.fromCodePoint(Ta.codePointAt(Ji))}function O(){let i=xt();return i===`
45
+ `?(Nt++,rt=0):i?rt+=i.length:rt++,i&&(Ji+=i.length),i}var Lu={default(){switch(J){case " ":case "\v":case "\f":case " ":case "\xA0":case "\uFEFF":case `
46
+ `:case "\r":case "\u2028":case "\u2029":O();return;case "/":O(),j="comment";return;case void 0:return O(),le("eof")}if(me.isSpaceSeparator(J)){O();return}return Lu[Re]()},comment(){switch(J){case "*":O(),j="multiLineComment";return;case "/":O(),j="singleLineComment";return}throw ue(O())},multiLineComment(){switch(J){case "*":O(),j="multiLineCommentAsterisk";return;case void 0:throw ue(O())}O();},multiLineCommentAsterisk(){switch(J){case "*":O();return;case "/":O(),j="default";return;case void 0:throw ue(O())}O(),j="multiLineComment";},singleLineComment(){switch(J){case `
47
+ `:case "\r":case "\u2028":case "\u2029":O(),j="default";return;case void 0:return O(),le("eof")}O();},value(){switch(J){case "{":case "[":return le("punctuator",O());case "n":return O(),Xt("ull"),le("null",null);case "t":return O(),Xt("rue"),le("boolean",true);case "f":return O(),Xt("alse"),le("boolean",false);case "-":case "+":O()==="-"&&(At=-1),j="sign";return;case ".":W=O(),j="decimalPointLeading";return;case "0":W=O(),j="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":W=O(),j="decimalInteger";return;case "I":return O(),Xt("nfinity"),le("numeric",1/0);case "N":return O(),Xt("aN"),le("numeric",NaN);case '"':case "'":zn=O()==='"',W="",j="string";return}throw ue(O())},identifierNameStartEscape(){if(J!=="u")throw ue(O());O();let i=Fa();switch(i){case "$":case "_":break;default:if(!me.isIdStartChar(i))throw ku();break}W+=i,j="identifierName";},identifierName(){switch(J){case "$":case "_":case "\u200C":case "\u200D":W+=O();return;case "\\":O(),j="identifierNameEscape";return}if(me.isIdContinueChar(J)){W+=O();return}return le("identifier",W)},identifierNameEscape(){if(J!=="u")throw ue(O());O();let i=Fa();switch(i){case "$":case "_":case "\u200C":case "\u200D":break;default:if(!me.isIdContinueChar(i))throw ku();break}W+=i,j="identifierName";},sign(){switch(J){case ".":W=O(),j="decimalPointLeading";return;case "0":W=O(),j="zero";return;case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":W=O(),j="decimalInteger";return;case "I":return O(),Xt("nfinity"),le("numeric",At*(1/0));case "N":return O(),Xt("aN"),le("numeric",NaN)}throw ue(O())},zero(){switch(J){case ".":W+=O(),j="decimalPoint";return;case "e":case "E":W+=O(),j="decimalExponent";return;case "x":case "X":W+=O(),j="hexadecimal";return}return le("numeric",At*0)},decimalInteger(){switch(J){case ".":W+=O(),j="decimalPoint";return;case "e":case "E":W+=O(),j="decimalExponent";return}if(me.isDigit(J)){W+=O();return}return le("numeric",At*Number(W))},decimalPointLeading(){if(me.isDigit(J)){W+=O(),j="decimalFraction";return}throw ue(O())},decimalPoint(){switch(J){case "e":case "E":W+=O(),j="decimalExponent";return}if(me.isDigit(J)){W+=O(),j="decimalFraction";return}return le("numeric",At*Number(W))},decimalFraction(){switch(J){case "e":case "E":W+=O(),j="decimalExponent";return}if(me.isDigit(J)){W+=O();return}return le("numeric",At*Number(W))},decimalExponent(){switch(J){case "+":case "-":W+=O(),j="decimalExponentSign";return}if(me.isDigit(J)){W+=O(),j="decimalExponentInteger";return}throw ue(O())},decimalExponentSign(){if(me.isDigit(J)){W+=O(),j="decimalExponentInteger";return}throw ue(O())},decimalExponentInteger(){if(me.isDigit(J)){W+=O();return}return le("numeric",At*Number(W))},hexadecimal(){if(me.isHexDigit(J)){W+=O(),j="hexadecimalInteger";return}throw ue(O())},hexadecimalInteger(){if(me.isHexDigit(J)){W+=O();return}return le("numeric",At*Number(W))},string(){switch(J){case "\\":O(),W+=Sf();return;case '"':if(zn)return O(),le("string",W);W+=O();return;case "'":if(!zn)return O(),le("string",W);W+=O();return;case `
48
+ `:case "\r":throw ue(O());case "\u2028":case "\u2029":Af(J);break;case void 0:throw ue(O())}W+=O();},start(){switch(J){case "{":case "[":return le("punctuator",O())}j="value";},beforePropertyName(){switch(J){case "$":case "_":W=O(),j="identifierName";return;case "\\":O(),j="identifierNameStartEscape";return;case "}":return le("punctuator",O());case '"':case "'":zn=O()==='"',j="string";return}if(me.isIdStartChar(J)){W+=O(),j="identifierName";return}throw ue(O())},afterPropertyName(){if(J===":")return le("punctuator",O());throw ue(O())},beforePropertyValue(){j="value";},afterPropertyValue(){switch(J){case ",":case "}":return le("punctuator",O())}throw ue(O())},beforeArrayValue(){if(J==="]")return le("punctuator",O());j="value";},afterArrayValue(){switch(J){case ",":case "]":return le("punctuator",O())}throw ue(O())},end(){throw ue(O())}};function le(i,e){return {type:i,value:e,line:Nt,column:rt}}function Xt(i){for(let e of i){if(xt()!==e)throw ue(O());O();}}function Sf(){switch(xt()){case "b":return O(),"\b";case "f":return O(),"\f";case "n":return O(),`
49
+ `;case "r":return O(),"\r";case "t":return O()," ";case "v":return O(),"\v";case "0":if(O(),me.isDigit(xt()))throw ue(O());return "\0";case "x":return O(),Ef();case "u":return O(),Fa();case `
50
+ `:case "\u2028":case "\u2029":return O(),"";case "\r":return O(),xt()===`
51
+ `&&O(),"";case "1":case "2":case "3":case "4":case "5":case "6":case "7":case "8":case "9":throw ue(O());case void 0:throw ue(O())}return O()}function Ef(){let i="",e=xt();if(!me.isHexDigit(e)||(i+=O(),e=xt(),!me.isHexDigit(e)))throw ue(O());return i+=O(),String.fromCodePoint(parseInt(i,16))}function Fa(){let i="",e=4;for(;e-- >0;){let t=xt();if(!me.isHexDigit(t))throw ue(O());i+=O();}return String.fromCodePoint(parseInt(i,16))}var bf={start(){if(be.type==="eof")throw Yt();Oa();},beforePropertyName(){switch(be.type){case "identifier":case "string":Na=be.value,Re="afterPropertyName";return;case "punctuator":Hi();return;case "eof":throw Yt()}},afterPropertyName(){if(be.type==="eof")throw Yt();Re="beforePropertyValue";},beforePropertyValue(){if(be.type==="eof")throw Yt();Oa();},beforeArrayValue(){if(be.type==="eof")throw Yt();if(be.type==="punctuator"&&be.value==="]"){Hi();return}Oa();},afterPropertyValue(){if(be.type==="eof")throw Yt();switch(be.value){case ",":Re="beforePropertyName";return;case "}":Hi();}},afterArrayValue(){if(be.type==="eof")throw Yt();switch(be.value){case ",":Re="beforeArrayValue";return;case "]":Hi();}},end(){}};function Oa(){let i;switch(be.type){case "punctuator":switch(be.value){case "{":i={};break;case "[":i=[];break}break;case "null":case "boolean":case "numeric":case "string":i=be.value;break}if(Kn===void 0)Kn=i;else {let e=Dt[Dt.length-1];Array.isArray(e)?e.push(i):Object.defineProperty(e,Na,{value:i,writable:true,enumerable:true,configurable:true});}if(i!==null&&typeof i=="object")Dt.push(i),Array.isArray(i)?Re="beforeArrayValue":Re="beforePropertyName";else {let e=Dt[Dt.length-1];e==null?Re="end":Array.isArray(e)?Re="afterArrayValue":Re="afterPropertyValue";}}function Hi(){Dt.pop();let i=Dt[Dt.length-1];i==null?Re="end":Array.isArray(i)?Re="afterArrayValue":Re="afterPropertyValue";}function ue(i){return Ui(i===void 0?`JSON5: invalid end of input at ${Nt}:${rt}`:`JSON5: invalid character '${Bu(i)}' at ${Nt}:${rt}`)}function Yt(){return Ui(`JSON5: invalid end of input at ${Nt}:${rt}`)}function ku(){return rt-=5,Ui(`JSON5: invalid identifier character at ${Nt}:${rt}`)}function Af(i){console.warn(`JSON5: '${Bu(i)}' in strings is not valid ECMAScript; consider escaping`);}function Bu(i){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[i])return e[i];if(i<" "){let t=i.charCodeAt(0).toString(16);return "\\x"+("00"+t).substring(t.length)}return i}function Ui(i){let e=new SyntaxError(i);return e.lineNumber=Nt,e.columnNumber=rt,e}var Df=function(e,t,n){let r=[],a="",s,o,l="",u;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,u=t.quote,t=t.replacer),typeof t=="function")o=t;else if(Array.isArray(t)){s=[];for(let y of t){let _;typeof y=="string"?_=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(_=String(y)),_!==void 0&&s.indexOf(_)<0&&s.push(_);}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):typeof n=="string"&&(l=n.substr(0,10)),c("",{"":e});function c(y,_){let D=_[y];switch(D!=null&&(typeof D.toJSON5=="function"?D=D.toJSON5(y):typeof D.toJSON=="function"&&(D=D.toJSON(y))),o&&(D=o.call(_,y,D)),D instanceof Number?D=Number(D):D instanceof String?D=String(D):D instanceof Boolean&&(D=D.valueOf()),D){case null:return "null";case true:return "true";case false:return "false"}if(typeof D=="string")return h(D);if(typeof D=="number")return String(D);if(typeof D=="object")return Array.isArray(D)?g(D):f(D)}function h(y){let _={"'":.1,'"':.2},D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},m="";for(let E=0;E<y.length;E++){let C=y[E];switch(C){case "'":case '"':_[C]++,m+=C;continue;case "\0":if(me.isDigit(y[E+1])){m+="\\x00";continue}}if(D[C]){m+=D[C];continue}if(C<" "){let S=C.charCodeAt(0).toString(16);m+="\\x"+("00"+S).substring(S.length);continue}m+=C;}let p=u||Object.keys(_).reduce((E,C)=>_[E]<_[C]?E:C);return m=m.replace(new RegExp(p,"g"),D[p]),p+m+p}function f(y){if(r.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");r.push(y);let _=a;a=a+l;let D=s||Object.keys(y),m=[];for(let E of D){let C=c(E,y);if(C!==void 0){let S=d(E)+":";l!==""&&(S+=" "),S+=C,m.push(S);}}let p;if(m.length===0)p="{}";else {let E;if(l==="")E=m.join(","),p="{"+E+"}";else {let C=`,
52
52
  `+a;E=m.join(C),p=`{
53
53
  `+a+E+`,
54
- `+_+"}";}}return r.pop(),a=_,p}function d(y){if(y.length===0)return h(y);let _=String.fromCodePoint(y.codePointAt(0));if(!ge.isIdStartChar(_))return h(y);for(let D=_.length;D<y.length;D++)if(!ge.isIdContinueChar(String.fromCodePoint(y.codePointAt(D))))return h(y);return y}function g(y){if(r.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");r.push(y);let _=a;a=a+l;let D=[];for(let p=0;p<y.length;p++){let E=c(String(p),y);D.push(E!==void 0?E:"null");}let m;if(D.length===0)m="[]";else if(l==="")m="["+D.join(",")+"]";else {let p=`,
54
+ `+_+"}";}}return r.pop(),a=_,p}function d(y){if(y.length===0)return h(y);let _=String.fromCodePoint(y.codePointAt(0));if(!me.isIdStartChar(_))return h(y);for(let D=_.length;D<y.length;D++)if(!me.isIdContinueChar(String.fromCodePoint(y.codePointAt(D))))return h(y);return y}function g(y){if(r.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");r.push(y);let _=a;a=a+l;let D=[];for(let p=0;p<y.length;p++){let E=c(String(p),y);D.push(E!==void 0?E:"null");}let m;if(D.length===0)m="[]";else if(l==="")m="["+D.join(",")+"]";else {let p=`,
55
55
  `+a,E=D.join(p);m=`[
56
56
  `+a+E+`,
57
- `+_+"]";}return r.pop(),a=_,m}},xf={parse:yf,stringify:Df},_f=xf,Xn=_f;var Wu="\xA7SPACE\xA7",ju="\xA7DOUBLE_QUOTES\xA7",qu="\xA7QUOTES\xA7",Mu="SPECIAL_\xA7QUOTES\xA7",$u="\xA7CURLY_BRACKETS1\xA7",wf="\xA7INK_VAR\xA7",Gu="\xA7CURLY_BRACKETS2\xA7",xt;(m=>{let i=[],e=[];async function t(p,E){for(let C=0;C<i.length;C++)try{let{validation:S}=i[C].opts;if(S instanceof RegExp){if(!S.test(p.join(" ")))continue}else if(S instanceof zod.ZodType&&!S.safeParse(p).success)continue;let w=await i[C].fn(p,E,h);if(w===!0||typeof w=="string")return w}catch{}return false}function n(p,E={name:"custom-command",validation:/^/}){i.unshift({fn:p,opts:E});}m.add=n;function r(){return [...e.map(p=>p.opts),...i.map(p=>p.opts)]}m.info=r;function a(p,E){e.unshift({fn:p,opts:E});}m.addMapper=a;function s(){i.length=0;}m.clear=s;function o(){e.length=0;}m.clearMappers=o;async function l(p,E,C){try{let S=u(p),w=await t(S,C);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await m.run(w,E,C)):c(S,E)}catch(S){throw z.error("Error parsing ink hashtag-command",p),S}}m.run=l;function u(p,E){if(p=p.replaceAll('\\"',ju),p=p.replaceAll("\\'",qu),p=p.replaceAll("\\`",Mu),p=p.replaceAll("\\{",$u),p=p.replaceAll("\\}",Gu),E?.mergeInkVariables){let b;do b=p,p=p.replace(/\{[^{}:]*\}/g,wf);while(p!==b)}p=p.replaceAll("{"," { "),p=p.replaceAll("}"," } "),p=p.replaceAll($u,"{"),p=p.replaceAll(Gu,"}");let C=[],S,w="";for(let b=0;b<p.length;b++){let O=p[b];O==='"'||O==="'"||O==="`"?S===void 0?(C.push(w),w="",S=O,w+=O):S===O?(S=void 0,w+=O,C.push(w),w=""):w+=O:w+=O;}return w!==""&&C.push(w),C.forEach((b,O)=>{O%2===1&&(C[O]=b.replaceAll(" ",Wu));}),p=C.join(""),C=p.split(" ").filter(b=>b!==""),C=C.map(b=>b.replaceAll(Wu," ").replaceAll(ju,'"').replaceAll(qu,"'").replaceAll(Mu,"`")),C=y(C),C=C.map(b=>b.startsWith('"')&&b.endsWith('"')||b.startsWith("'")&&b.endsWith("'")||b.startsWith("`")&&b.endsWith("`")?b.slice(1,-1):b),C}m.convertTagTolist=u;function c(p,E,C){for(let S of e){let{validation:w}=S.opts,b=false;if(w instanceof RegExp?b=w.test(p.join(" ")):w instanceof zod.ZodType&&(b=w.safeParse(p).success),b)return S.fn(p,E)}C?.silent||z.error("The operation is not valid",p);}m.convertOperation=c;function h(p){return f(p)}m.convertListStringToObj=h;function f(p){if(p.length===0)return {};if(p.length%2!==0)throw z.error("The props list must have a pair number of elements",p),new Error("The props list must have a pair number of elements");let E="{";p.forEach((C,S)=>{if(S%2===0)E+=`"${C}": `;else {switch(C){case "null":case "undefined":case "true":case "false":E+=`${C}`;break;default:g(C)?(C=d(C),E+=`"${C}"`):C.startsWith("{")&&C.endsWith("}")?E+=`${C}`:C.startsWith('"')&&C.endsWith('"')?E+=`${C}`:Number.isNaN(parseFloat(C))?E+=`"${C}"`:E+=`${C}`;}S<p.length-1&&(E+=", ");}}),E+="}";try{return Xn.parse(E)}catch(C){throw z.error("Error parsing ink json",E),C}}function d(p){return p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`")?p.substring(1,p.length-1):p}function g(p){return !!(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`"))}function y(p){return _(p).tokens}m.mergeJsonBlocks=y;function _(p){let E=[],C=false;for(let S=0;S<p.length;S++){let w=p[S];if(w!=="{"){E.push(w);continue}let b=D(p,S);if(b===-1){E.push(w);continue}let O=_(p.slice(S+1,b)),v=["{",...O.tokens,"}"],V=v.join(" ");if(!O.hasInvalidMatchedBlock)try{Xn.parse(V),E.push(V),S=b;continue}catch{}C=true,E.push(...v),S=b;}return {tokens:E,hasInvalidMatchedBlock:C}}function D(p,E){let C=0;for(let S=E;S<p.length;S++)if(p[S]==="{")C++;else if(p[S]==="}"&&(C--,C===0))return S;return -1}})(xt||={});var Ui="global decl",Qt="___external_value___",Hu=/\[([^\]]+)\]/;var Be;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Be||={});var U=class Z{static init(e){e.loadAssets&&(Z._loadAssets=e.loadAssets),e.soundOperation&&(Z._soundOperation=e.soundOperation),e.imageOperation&&(Z._imageOperation=e.imageOperation),e.videoOperation&&(Z._videoOperation=e.videoOperation),e.imageContainerOperation&&(Z._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Z._textOperation=e.textOperation),e.canvasElementOperation&&(Z._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Z._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Z._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Z._narrationOperation=e.narrationOperation),e.effectOperation&&(Z._effectOperation=e.effectOperation),e.animateOperation&&(Z._animateOperation=e.animateOperation),e.getLogichValue&&(Z._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Z._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Z._loadAssets}static _soundOperation=()=>{throw Be.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 Z._soundOperation}static _imageOperation=()=>{throw Be.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 Z._imageOperation}static _videoOperation=()=>{throw Be.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 Z._videoOperation}static _imageContainerOperation=()=>{throw Be.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 Z._imageContainerOperation}static _textOperation=()=>{throw Be.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 Z._textOperation}static _canvasElementOperation=()=>{throw Be.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 Z._canvasElementOperation}static _setStorageValue=()=>{throw Be.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 Z._setStorageValue}static _setInitialStorageValue=()=>{throw Be.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 Z._setInitialStorageValue}static _narrationOperation=()=>{throw Be.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 Z._narrationOperation}static _effectOperation=()=>{throw Be.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 Z._effectOperation}static _animateOperation=()=>{throw Be.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 Z._animateOperation}static _getLogichValue=()=>{throw Be.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 Z._getLogichValue}static _getConditionalStep=()=>{throw Be.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 Z._getConditionalStep}};var It;(i=>{i.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(u,c){e.unshift({fn:u,opts:c});}i.add=t;function n(u){let c=e.findIndex(h=>h.fn===u);c!==-1&&e.splice(c,1);}i.remove=n;function r(){return e.map(u=>u.opts)}i.info=r;function a(u,c){let h=e.filter(f=>(f.opts.type??"after-translation")===c.type);for(let f of h)u=l(u,f.fn,f.opts.validation);return u}i.replace=a;function s(u){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)u=o(u,h.fn,h.opts);return u}i.runI18nPreStep=s;function o(u,c,h){let{validation:f}=h,d=new RegExp(i.options.replaceRegex.source,"g"),g=[...u.matchAll(d)],y=new Set,_=[];for(let D of g)y.has(D[1])||(y.add(D[1]),_.push(D[1]));for(let D of _){if(f==="characterId"){if(!characters.RegisteredCharacters.has(D))continue}else if(f!=="all"){if(f instanceof RegExp){if(!f.test(D))continue}else if(f instanceof zod.ZodType&&!f.safeParse(D).success)continue}c(D)!==void 0&&(u.includes(`{{[${D}]}}`)||(u=u.replaceAll(`[${D}]`,`{{[${D}]}}`)));}return u}function l(u,c,h){let f=new RegExp(i.options.replaceRegex.source,"g"),d=[...u.matchAll(f)],g=new Set,y=[];for(let _ of d)g.has(_[1])||(g.add(_[1]),y.push(_[1]));for(let _ of y){if(h==="characterId"){if(!characters.RegisteredCharacters.has(_))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(_))continue}else if(h instanceof zod.ZodType&&!h.safeParse(_).success)continue}let D=c(_);D!==void 0&&(u=u.replaceAll(`[${_}]`,D));}return u}})(It||={});function Of(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=U.getLogichValue(n,e);t+=`${r}`;}}),t}var zu;(i=>{let e=l=>l;function t(l){return Array.isArray(l)?l.map(u=>n(`${u}`)):n(`${l}`)}i.t=t;function n(l){let u=l;return i.beforeToTranslate&&(u=(0, i.beforeToTranslate)(u)),u=It.replace(u,{type:"before-translation"}),u=e(u),i.afterToTranslate&&(u=(0, i.afterToTranslate)(u)),u=It.replace(u,{type:"after-translation"}),u}i.translate=n;function r(l){e=l;}i.setTranslate=r;function a(l,u,c){let{defaultValue:h="empty_string"}=c;typeof u=="string"&&(u=[u]),Array.isArray(u)&&u.forEach(f=>{let d=f;if(i.beforeToTranslate&&(d=(0, i.beforeToTranslate)(d)),h==="empty_string")l[d]===void 0&&(l[d]="");else if(h==="copy_key"){let g=f;i.beforeToTranslate&&(g=(0, i.beforeToTranslate)(g));let y=It.runI18nPreStep(g);y=It.replace(y,{type:"before-translation"}),l[d]=y;}});}function s(l,u=[]){if(typeof l=="object"&&l&&"type"in l)if(l.type==="ifelse")l.then&&s(l.then,u),l.else&&s(l.else,u);else if(l.type==="stepswitch"){if(l.elements)if(Array.isArray(l.elements))l.elements.forEach(c=>{s(c,u);});else if(l.elements.type==="ifelse"){let c=[];s(l.elements,c),c.forEach(h=>{u.push(...h);});}else if(l.elements.type==="stepswitch"){let c=[];s(l.elements,c),c.forEach(h=>{u.push(...h);});}else s(l.elements,u);}else l.type==="resulttocombine"?(l.firstItem&&s(l.firstItem,u),l.secondConditionalItem&&l.secondConditionalItem.forEach(c=>{s(c,u);})):u.push(l);else l&&u.push(l);return u}async function o(l,u={},c={}){let{defaultValue:h="copy_key",operationStringConvert:f}=c,d=l.map(async g=>{if(g.choices){let y=[];Array.isArray(g.choices)?y=[g.choices]:y=s(g.choices),y.forEach(_=>{_.forEach(D=>{if("type"in D){let m=[];D.type==="ifelse"||D.type==="stepswitch"?s(D,m):m=[D],m.map(p=>s(p.text)).forEach(p=>{Array.isArray(p)&&p.forEach(E=>{Array.isArray(E)?E.forEach(C=>{typeof C=="string"?a(u,C,{defaultValue:h}):s(C).forEach(S=>{Array.isArray(S)?S.forEach(w=>{typeof w=="string"&&a(u,w,{defaultValue:h});}):typeof S=="string"&&a(u,S,{defaultValue:h});});}):typeof E=="string"&&a(u,E,{defaultValue:h});});});}});});}if(g.dialogue){let y=[];Array.isArray(g.dialogue)?y=[g.dialogue]:y=s(g.dialogue),y.forEach(_=>{if(typeof _=="string")a(u,_,{defaultValue:h});else if("text"in _){let D=s(_.text);typeof D=="string"&&(D=[D]),D.forEach(m=>{typeof m=="string"?a(u,m,{defaultValue:h}):s(m).forEach(p=>{typeof p=="string"?a(u,p,{defaultValue:h}):Array.isArray(p)&&p.forEach(E=>{typeof E=="string"?a(u,E,{defaultValue:h}):s(E).forEach(C=>{typeof C=="string"&&a(u,C,{defaultValue:h});});});});});}});}if(g.operations)for(let y of g.operations){if(y.type==="operationtoconvert"&&f){let _=Of(y),D=await f(_,g,{});if(!D)return;y=D;}y.type==="text"&&y.operationType==="show"&&a(u,y.text,{defaultValue:h});}g.conditionalStep&&s(g.conditionalStep).forEach(y=>{Array.isArray(y)?o(y,u,c):o([y],u,c);});});return await Promise.all(d),u}i.generateJsonTranslation=o;})(zu||={});var Yn=zu;var pe;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(pe||={});var Pf="___param___",Ff=class ee{static init(e){e.loadAssets&&(ee._loadAssets=e.loadAssets),e.soundOperation&&(ee._soundOperation=e.soundOperation),e.imageOperation&&(ee._imageOperation=e.imageOperation),e.videoOperation&&(ee._videoOperation=e.videoOperation),e.imageContainerOperation&&(ee._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(ee._textOperation=e.textOperation),e.canvasElementOperation&&(ee._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(ee._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(ee._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(ee._narrationOperation=e.narrationOperation),e.effectOperation&&(ee._effectOperation=e.effectOperation),e.animateOperation&&(ee._animateOperation=e.animateOperation),e.getLogichValue&&(ee._getLogichValue=e.getLogichValue),e.getConditionalStep&&(ee._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._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 ee._animateOperation}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 ee._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 ee._getConditionalStep}};function Nf(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>Ff.getLogichValue(r,e));return t(...n)}else pe.warn(`getLogichValue function ${i.functionName} not found in props`);}}function Ku(i,e={}){let t=Xu(i,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return Rf(t,e);case "arithmetic":case "arithmeticsingle":return If(t,e);case "compare":case "union":return Vf(t,e);case "function":return Nf(t,e)}return t}function If(i,e){let t=U.getLogichValue(i.leftValue,e);switch(i.type){case "arithmetic":{let n=U.getLogichValue(i.rightValue,e);switch(i.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>!n.includes(r));if(Array.isArray(t))return t.filter(r=>r!==n);if(Array.isArray(n)){pe.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>n.includes(r));pe.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:pe.warn("getValueFromArithmeticOperations unknown operator",i);return}}case "arithmeticsingle":switch(i.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function Rf(i,e){if(i&&typeof i=="object"&&"type"in i&&i.type==="value"&&i.storageOperationType==="get")switch(i.storageType){case "storage":case "tempstorage":return i.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(i.key);case "flagStorage":return storage.storage.getFlag(i.key);case "label":return narration.narration.getTimesLabelOpened(i.label);case "choice":return narration.narration.getTimesChoiceMade(i.index);case "logic":return U.getLogichValue(i.operation,e);case "params":{let t=storage.storage.get(`${Pf}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>i.key)return t[i.key];pe.warn("getValue params not found");return}}return i}function Vf(i,e){if(!i)return false;if(typeof i!="object"||!("type"in i))return !!i;switch(i.type){case "compare":{let t=U.getLogichValue(i.leftValue,e),n=U.getLogichValue(i.rightValue,e);switch(i.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(r=>n.includes(r)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(r=>n.includes(r)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(r=>t.includes(r)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=U.getLogichValue(i,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return kf(i,e)}return !!i}function kf(i,e){if(i.unionType==="not"){let n=Ku(i.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>U.getLogichValue(n,e)||false;return i.unionType==="and"?i.conditions.every(t):i.conditions.some(t)}function Lf(i,e){return Math.floor(Math.random()*(e-i+1)+i)}function Xu(i,e={}){if(Array.isArray(i)||!i)return i;if(i&&typeof i=="object"&&"type"in i)switch(i.type){case "resulttocombine":return Bf(i,e);case "ifelse":return U.getLogichValue(i.condition,e)?U.getLogichValue(i.then,e):U.getLogichValue(i.else,e);case "stepswitch":{let t=U.getLogichValue(i.elements,e)||[];if(t.length===0){pe.error("getValueFromConditionalStatements elements.length === 0");return}switch(i.choiceType){case "random":{let n=Lf(0,t.length-1);return U.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return n>t.length-1?(n=n%t.length,U.getLogichValue(t[n],e)):U.getLogichValue(t[n],e)}case "sequential":{let n,r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return i.end==="lastItem"&&(n=U.getLogichValue(t[t.length-1],e)),r>t.length-1?n:U.getLogichValue(t[r],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:i.nestedId,onceOnly:true});if(n===void 0&&i.end==="lastItem"){let r=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(i.nestedId);if(!r?.usedRandomNumbers){pe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=r.usedRandomNumbers[`0-${t.length-1}`];return U.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){pe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return U.getLogichValue(t[n],e)}}}}return i}function Na(i,e={}){if(i.conditionalStep){let t=pixiVn.createExportableElement(U.getLogichValue(i.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 n={...i,conditionalStep:void 0,...t};return Na(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return i}function Bf(i,e){let t=i.firstItem,n=(i.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>U.getLogichValue(s,e)):[U.getLogichValue(a,e)]),r=t?[t,...n]:n;if(r.length===0){pe.warn("combinateResult toCheck.length === 0");return}if(typeof r[0]=="string")return Yn.t(r);if(typeof r[0]=="object"){let a=r,s,o=false,l=a.map((m,p)=>{m=Na(m,e);let E=U.getLogichValue(m.dialogue,e)||"";return p===0?(s=U.getLogichValue(m.glueEnabled,e)||false,E):(typeof E=="object"&&"text"in E&&(E=`${E.character}: ${E.text}`),s===false&&o&&(E=`
57
+ `+_+"]";}return r.pop(),a=_,m}},xf={parse:yf,stringify:Df},_f=xf,Xn=_f;var ju="\xA7SPACE\xA7",qu="\xA7DOUBLE_QUOTES\xA7",Mu="\xA7QUOTES\xA7",$u="SPECIAL_\xA7QUOTES\xA7",Gu="\xA7CURLY_BRACKETS1\xA7",wf="\xA7INK_VAR\xA7",Hu="\xA7CURLY_BRACKETS2\xA7",_t;(m=>{let i=[],e=[];async function t(p,E){for(let C=0;C<i.length;C++)try{let{validation:S}=i[C].opts;if(S instanceof RegExp){if(!S.test(p.join(" ")))continue}else if(S instanceof zod.ZodType&&!S.safeParse(p).success)continue;let w=await i[C].fn(p,E,h);if(w===!0||typeof w=="string")return w}catch{}return false}function n(p,E={name:"custom-command",validation:/^/}){i.unshift({fn:p,opts:E});}m.add=n;function r(){return [...e.map(p=>p.opts),...i.map(p=>p.opts)]}m.info=r;function a(p,E){e.unshift({fn:p,opts:E});}m.addMapper=a;function s(){i.length=0;}m.clear=s;function o(){e.length=0;}m.clearMappers=o;async function l(p,E,C){try{let S=u(p),w=await t(S,C);return w===!0?void 0:typeof w=="string"?(w.startsWith("#")&&(w=w.substring(1)),await m.run(w,E,C)):c(S,E)}catch(S){throw X.error("Error parsing ink hashtag-command",p),S}}m.run=l;function u(p,E){if(p=p.replaceAll('\\"',qu),p=p.replaceAll("\\'",Mu),p=p.replaceAll("\\`",$u),p=p.replaceAll("\\{",Gu),p=p.replaceAll("\\}",Hu),E?.mergeInkVariables){let P;do P=p,p=p.replace(/\{[^{}:]*\}/g,wf);while(p!==P)}p=p.replaceAll("{"," { "),p=p.replaceAll("}"," } "),p=p.replaceAll(Gu,"{"),p=p.replaceAll(Hu,"}");let C=[],S,w="";for(let P=0;P<p.length;P++){let x=p[P];x==='"'||x==="'"||x==="`"?S===void 0?(C.push(w),w="",S=x,w+=x):S===x?(S=void 0,w+=x,C.push(w),w=""):w+=x:w+=x;}return w!==""&&C.push(w),C.forEach((P,x)=>{x%2===1&&(C[x]=P.replaceAll(" ",ju));}),p=C.join(""),C=p.split(" ").filter(P=>P!==""),C=C.map(P=>P.replaceAll(ju," ").replaceAll(qu,'"').replaceAll(Mu,"'").replaceAll($u,"`")),C=y(C),C=C.map(P=>P.startsWith('"')&&P.endsWith('"')||P.startsWith("'")&&P.endsWith("'")||P.startsWith("`")&&P.endsWith("`")?P.slice(1,-1):P),C}m.convertTagTolist=u;function c(p,E,C){for(let S of e){let{validation:w}=S.opts,P=false;if(w instanceof RegExp?P=w.test(p.join(" ")):w instanceof zod.ZodType&&(P=w.safeParse(p).success),P)return S.fn(p,E)}C?.silent||X.error("The operation is not valid",p);}m.convertOperation=c;function h(p){return f(p)}m.convertListStringToObj=h;function f(p){if(p.length===0)return {};if(p.length%2!==0)throw X.error("The props list must have a pair number of elements",p),new Error("The props list must have a pair number of elements");let E="{";p.forEach((C,S)=>{if(S%2===0)E+=`"${C}": `;else {switch(C){case "null":case "undefined":case "true":case "false":E+=`${C}`;break;default:g(C)?(C=d(C),E+=`"${C}"`):C.startsWith("{")&&C.endsWith("}")?E+=`${C}`:C.startsWith('"')&&C.endsWith('"')?E+=`${C}`:Number.isNaN(parseFloat(C))?E+=`"${C}"`:E+=`${C}`;}S<p.length-1&&(E+=", ");}}),E+="}";try{return Xn.parse(E)}catch(C){throw X.error("Error parsing ink json",E),C}}function d(p){return p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`")?p.substring(1,p.length-1):p}function g(p){return !!(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'")||p.startsWith("`")&&p.endsWith("`"))}function y(p){return _(p).tokens}m.mergeJsonBlocks=y;function _(p){let E=[],C=false;for(let S=0;S<p.length;S++){let w=p[S];if(w!=="{"){E.push(w);continue}let P=D(p,S);if(P===-1){E.push(w);continue}let x=_(p.slice(S+1,P)),v=["{",...x.tokens,"}"],I=v.join(" ");if(!x.hasInvalidMatchedBlock)try{Xn.parse(I),E.push(I),S=P;continue}catch{}C=true,E.push(...v),S=P;}return {tokens:E,hasInvalidMatchedBlock:C}}function D(p,E){let C=0;for(let S=E;S<p.length;S++)if(p[S]==="{")C++;else if(p[S]==="}"&&(C--,C===0))return S;return -1}})(_t||={});var zi="global decl",Qt="___external_value___",Ju=/\[([^\]]+)\]/;var Be;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(Be||={});var K=class Z{static init(e){e.loadAssets&&(Z._loadAssets=e.loadAssets),e.soundOperation&&(Z._soundOperation=e.soundOperation),e.imageOperation&&(Z._imageOperation=e.imageOperation),e.videoOperation&&(Z._videoOperation=e.videoOperation),e.imageContainerOperation&&(Z._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(Z._textOperation=e.textOperation),e.canvasElementOperation&&(Z._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(Z._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(Z._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(Z._narrationOperation=e.narrationOperation),e.effectOperation&&(Z._effectOperation=e.effectOperation),e.animateOperation&&(Z._animateOperation=e.animateOperation),e.getLogichValue&&(Z._getLogichValue=e.getLogichValue),e.getConditionalStep&&(Z._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return Z._loadAssets}static _soundOperation=()=>{throw Be.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 Z._soundOperation}static _imageOperation=()=>{throw Be.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 Z._imageOperation}static _videoOperation=()=>{throw Be.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 Z._videoOperation}static _imageContainerOperation=()=>{throw Be.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 Z._imageContainerOperation}static _textOperation=()=>{throw Be.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 Z._textOperation}static _canvasElementOperation=()=>{throw Be.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 Z._canvasElementOperation}static _setStorageValue=()=>{throw Be.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 Z._setStorageValue}static _setInitialStorageValue=()=>{throw Be.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 Z._setInitialStorageValue}static _narrationOperation=()=>{throw Be.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 Z._narrationOperation}static _effectOperation=()=>{throw Be.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 Z._effectOperation}static _animateOperation=()=>{throw Be.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 Z._animateOperation}static _getLogichValue=()=>{throw Be.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 Z._getLogichValue}static _getConditionalStep=()=>{throw Be.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 Z._getConditionalStep}};var It;(i=>{i.options={replaceRegex:/\[([^\]]+)\]/};let e=[];function t(u,c){e.unshift({fn:u,opts:c});}i.add=t;function n(u){let c=e.findIndex(h=>h.fn===u);c!==-1&&e.splice(c,1);}i.remove=n;function r(){return e.map(u=>u.opts)}i.info=r;function a(u,c){let h=e.filter(f=>(f.opts.type??"after-translation")===c.type);for(let f of h)u=l(u,f.fn,f.opts.validation);return u}i.replace=a;function s(u){let c=e.filter(h=>h.opts.i18nInterpolation);for(let h of c)u=o(u,h.fn,h.opts);return u}i.runI18nPreStep=s;function o(u,c,h){let{validation:f}=h,d=new RegExp(i.options.replaceRegex.source,"g"),g=[...u.matchAll(d)],y=new Set,_=[];for(let D of g)y.has(D[1])||(y.add(D[1]),_.push(D[1]));for(let D of _){if(f==="characterId"){if(!characters.RegisteredCharacters.has(D))continue}else if(f!=="all"){if(f instanceof RegExp){if(!f.test(D))continue}else if(f instanceof zod.ZodType&&!f.safeParse(D).success)continue}c(D)!==void 0&&(u.includes(`{{[${D}]}}`)||(u=u.replaceAll(`[${D}]`,`{{[${D}]}}`)));}return u}function l(u,c,h){let f=new RegExp(i.options.replaceRegex.source,"g"),d=[...u.matchAll(f)],g=new Set,y=[];for(let _ of d)g.has(_[1])||(g.add(_[1]),y.push(_[1]));for(let _ of y){if(h==="characterId"){if(!characters.RegisteredCharacters.has(_))continue}else if(h!=="all"){if(h instanceof RegExp){if(!h.test(_))continue}else if(h instanceof zod.ZodType&&!h.safeParse(_).success)continue}let D=c(_);D!==void 0&&(u=u.replaceAll(`[${_}]`,D));}return u}})(It||={});function Of(i,e={}){let t="";return i.values.forEach(n=>{if(typeof n=="string")t+=n;else {let r=K.getLogichValue(n,e);t+=`${r}`;}}),t}var Ku;(i=>{let e=l=>l;function t(l){return Array.isArray(l)?l.map(u=>n(`${u}`)):n(`${l}`)}i.t=t;function n(l){let u=l;return i.beforeToTranslate&&(u=(0, i.beforeToTranslate)(u)),u=It.replace(u,{type:"before-translation"}),u=e(u),i.afterToTranslate&&(u=(0, i.afterToTranslate)(u)),u=It.replace(u,{type:"after-translation"}),u}i.translate=n;function r(l){e=l;}i.setTranslate=r;function a(l,u,c){let{defaultValue:h="empty_string"}=c;typeof u=="string"&&(u=[u]),Array.isArray(u)&&u.forEach(f=>{let d=f;if(i.beforeToTranslate&&(d=(0, i.beforeToTranslate)(d)),h==="empty_string")l[d]===void 0&&(l[d]="");else if(h==="copy_key"){let g=f;i.beforeToTranslate&&(g=(0, i.beforeToTranslate)(g));let y=It.runI18nPreStep(g);y=It.replace(y,{type:"before-translation"}),l[d]=y;}});}function s(l,u=[]){if(typeof l=="object"&&l&&"type"in l)if(l.type==="ifelse")l.then&&s(l.then,u),l.else&&s(l.else,u);else if(l.type==="stepswitch"){if(l.elements)if(Array.isArray(l.elements))l.elements.forEach(c=>{s(c,u);});else if(l.elements.type==="ifelse"){let c=[];s(l.elements,c),c.forEach(h=>{u.push(...h);});}else if(l.elements.type==="stepswitch"){let c=[];s(l.elements,c),c.forEach(h=>{u.push(...h);});}else s(l.elements,u);}else l.type==="resulttocombine"?(l.firstItem&&s(l.firstItem,u),l.secondConditionalItem&&l.secondConditionalItem.forEach(c=>{s(c,u);})):u.push(l);else l&&u.push(l);return u}async function o(l,u={},c={}){let{defaultValue:h="copy_key",operationStringConvert:f}=c,d=l.map(async g=>{if(g.choices){let y=[];Array.isArray(g.choices)?y=[g.choices]:y=s(g.choices),y.forEach(_=>{_.forEach(D=>{if("type"in D){let m=[];D.type==="ifelse"||D.type==="stepswitch"?s(D,m):m=[D],m.map(p=>s(p.text)).forEach(p=>{Array.isArray(p)&&p.forEach(E=>{Array.isArray(E)?E.forEach(C=>{typeof C=="string"?a(u,C,{defaultValue:h}):s(C).forEach(S=>{Array.isArray(S)?S.forEach(w=>{typeof w=="string"&&a(u,w,{defaultValue:h});}):typeof S=="string"&&a(u,S,{defaultValue:h});});}):typeof E=="string"&&a(u,E,{defaultValue:h});});});}});});}if(g.dialogue){let y=[];Array.isArray(g.dialogue)?y=[g.dialogue]:y=s(g.dialogue),y.forEach(_=>{if(typeof _=="string")a(u,_,{defaultValue:h});else if("text"in _){let D=s(_.text);typeof D=="string"&&(D=[D]),D.forEach(m=>{typeof m=="string"?a(u,m,{defaultValue:h}):s(m).forEach(p=>{typeof p=="string"?a(u,p,{defaultValue:h}):Array.isArray(p)&&p.forEach(E=>{typeof E=="string"?a(u,E,{defaultValue:h}):s(E).forEach(C=>{typeof C=="string"&&a(u,C,{defaultValue:h});});});});});}});}if(g.operations)for(let y of g.operations){if(y.type==="operationtoconvert"&&f){let _=Of(y),D=await f(_,g,{});if(!D)return;y=D;}y.type==="text"&&y.operationType==="show"&&a(u,y.text,{defaultValue:h});}g.conditionalStep&&s(g.conditionalStep).forEach(y=>{Array.isArray(y)?o(y,u,c):o([y],u,c);});});return await Promise.all(d),u}i.generateJsonTranslation=o;})(Ku||={});var Yn=Ku;var fe;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(fe||={});var Pf="___param___",Ff=class ee{static init(e){e.loadAssets&&(ee._loadAssets=e.loadAssets),e.soundOperation&&(ee._soundOperation=e.soundOperation),e.imageOperation&&(ee._imageOperation=e.imageOperation),e.videoOperation&&(ee._videoOperation=e.videoOperation),e.imageContainerOperation&&(ee._imageContainerOperation=e.imageContainerOperation),e.textOperation&&(ee._textOperation=e.textOperation),e.canvasElementOperation&&(ee._canvasElementOperation=e.canvasElementOperation),e.setStorageValue&&(ee._setStorageValue=e.setStorageValue),e.setInitialStorageValue&&(ee._setInitialStorageValue=e.setInitialStorageValue),e.narrationOperation&&(ee._narrationOperation=e.narrationOperation),e.effectOperation&&(ee._effectOperation=e.effectOperation),e.animateOperation&&(ee._animateOperation=e.animateOperation),e.getLogichValue&&(ee._getLogichValue=e.getLogichValue),e.getConditionalStep&&(ee._getConditionalStep=e.getConditionalStep);}static _loadAssets=()=>{};static get loadAssets(){return ee._loadAssets}static _soundOperation=()=>{throw fe.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 ee._soundOperation}static _imageOperation=()=>{throw fe.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 ee._imageOperation}static _videoOperation=()=>{throw fe.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 ee._videoOperation}static _imageContainerOperation=()=>{throw fe.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 ee._imageContainerOperation}static _textOperation=()=>{throw fe.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 ee._textOperation}static _canvasElementOperation=()=>{throw fe.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 ee._canvasElementOperation}static _setStorageValue=()=>{throw fe.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 ee._setStorageValue}static _setInitialStorageValue=()=>{throw fe.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 ee._setInitialStorageValue}static _narrationOperation=()=>{throw fe.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 ee._narrationOperation}static _effectOperation=()=>{throw fe.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 ee._effectOperation}static _animateOperation=()=>{throw fe.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 ee._animateOperation}static _getLogichValue=()=>{throw fe.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 ee._getLogichValue}static _getConditionalStep=()=>{throw fe.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 ee._getConditionalStep}};function Nf(i,e){if(e&&typeof e=="object"&&typeof i.functionName=="string"&&i.functionName in e){let t=e[i.functionName];if(typeof t=="function"){let n=i.args.map(r=>Ff.getLogichValue(r,e));return t(...n)}else fe.warn(`getLogichValue function ${i.functionName} not found in props`);}}function Xu(i,e={}){let t=Yu(i,e);if(t&&typeof t=="object"&&"type"in t)switch(t.type){case "value":return Rf(t,e);case "arithmetic":case "arithmeticsingle":return If(t,e);case "compare":case "union":return Vf(t,e);case "function":return Nf(t,e)}return t}function If(i,e){let t=K.getLogichValue(i.leftValue,e);switch(i.type){case "arithmetic":{let n=K.getLogichValue(i.rightValue,e);switch(i.operator){case "*":return t*n;case "/":return t/n;case "+":return typeof t=="string"||typeof n=="string"?`${t}${n}`:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:Array.isArray(t)?[...t,n]:Array.isArray(n)?[t,...n]:t+n;case "-":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>!n.includes(r));if(Array.isArray(t))return t.filter(r=>r!==n);if(Array.isArray(n)){fe.warn("getValueFromArithmeticOperations cannot subtract array from non-array");return}return t-n;case "%":return t%n;case "POW":return t**n;case "RANDOM":return narration.narration.getRandomNumber(t,n);case "INTERSECTION":if(Array.isArray(t)&&Array.isArray(n))return t.filter(r=>n.includes(r));fe.warn("getValueFromArithmeticOperations cannot intersect non-array values");return;default:fe.warn("getValueFromArithmeticOperations unknown operator",i);return}}case "arithmeticsingle":switch(i.operator){case "INT":return Number(t);case "FLOOR":return Math.floor(t)}break}}function Rf(i,e){if(i&&typeof i=="object"&&"type"in i&&i.type==="value"&&i.storageOperationType==="get")switch(i.storageType){case "storage":case "tempstorage":return i.key==="_input_value_"?narration.narration.inputValue:storage.storage.get(i.key);case "flagStorage":return storage.storage.getFlag(i.key);case "label":return narration.narration.getTimesLabelOpened(i.label);case "choice":return narration.narration.getTimesChoiceMade(i.index);case "logic":return K.getLogichValue(i.operation,e);case "params":{let t=storage.storage.get(`${Pf}${narration.narration.openedLabels.length-1}`)||[];if(t&&t.length>i.key)return t[i.key];fe.warn("getValue params not found");return}}return i}function Vf(i,e){if(!i)return false;if(typeof i!="object"||!("type"in i))return !!i;switch(i.type){case "compare":{let t=K.getLogichValue(i.leftValue,e),n=K.getLogichValue(i.rightValue,e);switch(i.operator){case "==":return Array.isArray(t)&&Array.isArray(n)?t.length===n.length&&t.every(r=>n.includes(r)):t===n;case "!=":return Array.isArray(t)&&Array.isArray(n)?t.length!==n.length||!t.every(r=>n.includes(r)):t!==n;case "<":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<0:Array.isArray(t)&&Array.isArray(n)?t.length<n.length:t<n;case "<=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)<=0:Array.isArray(t)&&Array.isArray(n)?t.length<=n.length:t<=n;case ">":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>0:Array.isArray(t)&&Array.isArray(n)?t.length>n.length:t>n;case ">=":return typeof t=="string"&&typeof n=="string"?t.localeCompare(n)>=0:Array.isArray(t)&&Array.isArray(n)?t.length>=n.length:t>=n;case "CONTAINS":return Array.isArray(t)&&Array.isArray(n)?n.every(r=>t.includes(r)):Array.isArray(t)?t.includes(n):t.toString().includes(n.toString())}break}case "value":{let t=K.getLogichValue(i,e);return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!!t}case "union":return kf(i,e)}return !!i}function kf(i,e){if(i.unionType==="not"){let n=Xu(i.condition,e);return Array.isArray(n)?n.length===0:n&&typeof n=="object"?Object.keys(n).length===0:!n}let t=n=>K.getLogichValue(n,e)||false;return i.unionType==="and"?i.conditions.every(t):i.conditions.some(t)}function Lf(i,e){return Math.floor(Math.random()*(e-i+1)+i)}function Yu(i,e={}){if(Array.isArray(i)||!i)return i;if(i&&typeof i=="object"&&"type"in i)switch(i.type){case "resulttocombine":return Bf(i,e);case "ifelse":return K.getLogichValue(i.condition,e)?K.getLogichValue(i.then,e):K.getLogichValue(i.else,e);case "stepswitch":{let t=K.getLogichValue(i.elements,e)||[];if(t.length===0){fe.error("getValueFromConditionalStatements elements.length === 0");return}switch(i.choiceType){case "random":{let n=Lf(0,t.length-1);return K.getLogichValue(t[n],e)}case "loop":{let n=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return n>t.length-1?(n=n%t.length,K.getLogichValue(t[n],e)):K.getLogichValue(t[n],e)}case "sequential":{let n,r=narration.NarrationManagerStatic.getCurrentStepTimesCounter(i.nestedId)-1;return i.end==="lastItem"&&(n=K.getLogichValue(t[t.length-1],e)),r>t.length-1?n:K.getLogichValue(t[r],e)}case "sequentialrandom":{let n=narration.NarrationManagerStatic.getRandomNumber(0,t.length-1,{nestedId:i.nestedId,onceOnly:true});if(n===void 0&&i.end==="lastItem"){let r=narration.NarrationManagerStatic.getCurrentStepTimesCounterData(i.nestedId);if(!r?.usedRandomNumbers){fe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}let a=r.usedRandomNumbers[`0-${t.length-1}`];return K.getLogichValue(t[a[a.length-1]],e)}if(n===void 0){fe.warn("getValueFromConditionalStatements randomIndexWhitExclude == undefined");return}return K.getLogichValue(t[n],e)}}}}return i}function Ra(i,e={}){if(i.conditionalStep){let t=pixiVn.createExportableElement(K.getLogichValue(i.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 n={...i,conditionalStep:void 0,...t};return Ra(n,e)}else narration.narration.dialogGlue&&(narration.narration.dialogGlue=false);}return i}function Bf(i,e){let t=i.firstItem,n=(i.secondConditionalItem??[]).flatMap(a=>Array.isArray(a)?a.map(s=>K.getLogichValue(s,e)):[K.getLogichValue(a,e)]),r=t?[t,...n]:n;if(r.length===0){fe.warn("combinateResult toCheck.length === 0");return}if(typeof r[0]=="string")return Yn.t(r);if(typeof r[0]=="object"){let a=r,s,o=false,l=a.map((m,p)=>{m=Ra(m,e);let E=K.getLogichValue(m.dialogue,e)||"";return p===0?(s=K.getLogichValue(m.glueEnabled,e)||false,E):(typeof E=="object"&&"text"in E&&(E=`${E.character}: ${E.text}`),s===false&&o&&(E=`
58
58
 
59
- ${E}`),E&&(o=true),s=U.getLogichValue(m.glueEnabled,e)||false,E)}),u=U.getLogichValue(l[0],e),c=typeof u=="object"&&"character"in u?u.character:void 0,h=l.flatMap(m=>{let p;m&&typeof m=="object"&&"text"in m?p=m.text:p=m;let E;return Array.isArray(p)?E=p.map(C=>{let S=U.getLogichValue(C,e);return Yn.t(`${S}`)}):E=U.getLogichValue(p,e)||"",Yn.t(E)}),f=a.find(m=>m.end),d=a.find(m=>m.choices),g=false,y=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),g=a[a.length-1].glueEnabled,y=a.reverse().find(m=>!(m.operations&&(!m.dialogue||!m.choices)))?.goNextStep);let _=a.find(m=>m.labelToOpen),D=[];return a.forEach(m=>{m.operations&&(D=[...D,...m.operations]);}),{dialogue:c?{character:c,text:h}:h,end:f?.end,choices:d?.choices,glueEnabled:g,goNextStep:y,labelToOpen:_?.labelToOpen,operations:D}}}var Ia;(i=>{let e=new Set;function t(a){e.add(a);}i.add=t;function n(){e.clear();}i.clear=n;function r(a,s={}){let o=c=>Ku(c,s)??void 0,l=Xu(a,s);if(e.size===0)return o(l);let u=o;for(let c of e){let h=u;u=f=>c(f,h)??void 0;}return u(l)}i.getLogichValue=r;})(Ia||={});var Wf=Object.create,Qu=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,qf=Object.getOwnPropertyNames,Mf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty,Yu=(i=>typeof Kt<"u"?Kt:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof Kt<"u"?Kt:e)[t]}):i)(function(i){if(typeof Kt<"u")return Kt.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),Zu=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Gf=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qf(e))!$f.call(i,r)&&r!==t&&Qu(i,r,{get:()=>e[r],enumerable:!(n=jf(e,r))||n.enumerable});return i},Hf=(i,e,t)=>(t=i!=null?Wf(Mf(i)):{},Gf(Qu(t,"default",{value:i,enumerable:true}),i)),Jf=Zu((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(i,function(){var t=t||(function(n,r){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 Yu=="function")try{a=Yu("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 m(){}return function(p){var E;return m.prototype=p,E=new m,m.prototype=null,E}})(),l={},u=l.lib={},c=u.Base=(function(){return {extend:function(m){var p=o(this);return m&&p.mixIn(m),(!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 m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var p in m)m.hasOwnProperty(p)&&(this[p]=m[p]);m.hasOwnProperty("toString")&&(this.toString=m.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=u.WordArray=c.extend({init:function(m,p){m=this.words=m||[],p!=r?this.sigBytes=p:this.sigBytes=m.length*4;},toString:function(m){return (m||d).stringify(this)},concat:function(m){var p=this.words,E=m.words,C=this.sigBytes,S=m.sigBytes;if(this.clamp(),C%4)for(var w=0;w<S;w++){var b=E[w>>>2]>>>24-w%4*8&255;p[C+w>>>2]|=b<<24-(C+w)%4*8;}else for(var O=0;O<S;O+=4)p[C+O>>>2]=E[O>>>2];return this.sigBytes+=S,this},clamp:function(){var m=this.words,p=this.sigBytes;m[p>>>2]&=4294967295<<32-p%4*8,m.length=n.ceil(p/4);},clone:function(){var m=c.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var p=[],E=0;E<m;E+=4)p.push(s());return new h.init(p,m)}}),f=l.enc={},d=f.Hex={stringify:function(m){for(var p=m.words,E=m.sigBytes,C=[],S=0;S<E;S++){var w=p[S>>>2]>>>24-S%4*8&255;C.push((w>>>4).toString(16)),C.push((w&15).toString(16));}return C.join("")},parse:function(m){for(var p=m.length,E=[],C=0;C<p;C+=2)E[C>>>3]|=parseInt(m.substr(C,2),16)<<24-C%8*4;return new h.init(E,p/2)}},g=f.Latin1={stringify:function(m){for(var p=m.words,E=m.sigBytes,C=[],S=0;S<E;S++){var w=p[S>>>2]>>>24-S%4*8&255;C.push(String.fromCharCode(w));}return C.join("")},parse:function(m){for(var p=m.length,E=[],C=0;C<p;C++)E[C>>>2]|=(m.charCodeAt(C)&255)<<24-C%4*8;return new h.init(E,p)}},y=f.Utf8={stringify:function(m){try{return decodeURIComponent(escape(g.stringify(m)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(m){return g.parse(unescape(encodeURIComponent(m)))}},_=u.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(m){typeof m=="string"&&(m=y.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes;},_process:function(m){var p,E=this._data,C=E.words,S=E.sigBytes,w=this.blockSize,b=w*4,O=S/b;m?O=n.ceil(O):O=n.max((O|0)-this._minBufferSize,0);var v=O*w,V=n.min(v*4,S);if(v){for(var I=0;I<v;I+=w)this._doProcessBlock(C,I);p=C.splice(0,v),E.sigBytes-=V;}return new h.init(p,V)},clone:function(){var m=c.clone.call(this);return m._data=this._data.clone(),m},_minBufferSize:0});u.Hasher=_.extend({cfg:c.extend(),init:function(m){this.cfg=this.cfg.extend(m),this.reset();},reset:function(){_.reset.call(this),this._doReset();},update:function(m){return this._append(m),this._process(),this},finalize:function(m){m&&this._append(m);var p=this._doFinalize();return p},blockSize:16,_createHelper:function(m){return function(p,E){return new m.init(E).finalize(p)}},_createHmacHelper:function(m){return function(p,E){return new D.HMAC.init(m,E).finalize(p)}}});var D=l.algo={};return l})(Math);return t});}),Uf=Zu((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n(Jf()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(i,function(t){return (function(){var n=t,r=n.lib,a=r.WordArray,s=r.Hasher,o=n.algo,l=[],u=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,d=f[0],g=f[1],y=f[2],_=f[3],D=f[4],m=0;m<80;m++){if(m<16)l[m]=c[h+m]|0;else {var p=l[m-3]^l[m-8]^l[m-14]^l[m-16];l[m]=p<<1|p>>>31;}var E=(d<<5|d>>>27)+D+l[m];m<20?E+=(g&y|~g&_)+1518500249:m<40?E+=(g^y^_)+1859775393:m<60?E+=(g&y|g&_|y&_)-1894007588:E+=(g^y^_)-899497514,D=_,_=y,y=g<<30|g>>>2,g=d,d=E;}f[0]=f[0]+d|0,f[1]=f[1]+g|0,f[2]=f[2]+y|0,f[3]=f[3]+_|0,f[4]=f[4]+D|0;},_doFinalize:function(){var c=this._data,h=c.words,f=this._nDataBytes*8,d=c.sigBytes*8;return h[d>>>5]|=128<<24-d%32,h[(d+64>>>9<<4)+14]=Math.floor(f/4294967296),h[(d+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}});n.SHA1=s._createHelper(u),n.HmacSHA1=s._createHmacHelper(u);})(),t.SHA1});});var zf;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(zf||={});Hf(Uf());var Kf={version:"1.13.12"};var ec=`https://pixi-vn.com/schemas/${Kf.version}/schema.json`,tc=["==","!=","<","<=",">",">=","CONTAINS"];var nc=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],ic=["+","-","/","*","%","POW","RANDOM","L^"],rc=["INT","FLOOR","FLOAT"];function Cn(i,e){if(i.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(i)&&(i=i.split(".").filter(r=>!r.match(/^[0-9]+$/)).join("."),!i.startsWith(".")))return i.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(i)&&i.includes("g-")){let n=i.split("g-");return Ra(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(i);)t++,i=i.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(i)&&e){let n=i.substring(1);return Ra(e,t)+"_|_"+n.replaceAll(".","_|_")}return i.replaceAll(".","_|_")||Ra(e,t).replaceAll(".","_|_")}function Ra(i,e=0){let t=i.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var sc="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function ht(i){return i.startsWith("^")&&(i=i.substring(1)),i=i.replaceAll("\\\\",sc),i=i.replaceAll("\\n",`
60
- `),i=i.replaceAll("\\t"," "),i=i.replaceAll(" "," "),i=i.replaceAll(sc,"\\\\"),i}function Vt(i,e,t,n){let{functions:r}=n;i=i.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return i.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)z.error("Error parsing ink file: Conditional statement is not valid",i);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 z.error("Error parsing ink file: Conditional statement is not valid",i);break;default:if(tc.includes(s))if(a.length<2)z.error("Error parsing ink file: Conditional statement is not valid",i);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(ic.includes(s))if(a.length<2)z.error("Error parsing ink file: Conditional statement is not valid",i);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(rc.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(ht(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),l=o.pop(),u=o.pop();if(u===void 0||l===void 0){z.error("Error parsing ink file: Conditional statement is not valid",i);return}let c=Number(u),h=o.join(".");if(h.includes("^.")){let d=h.split("."),g=d[d.length-1].replaceAll(".","_|_");d.pop(),h=`${d.join(".")}.${g}`,l.includes("c-")&&(h=h+"_|_"+l);}else h=h.replaceAll(".","_|_");let f=Cn(h,e);if(!f)return;a.push({type:"compare",leftValue:Va(f),operator:">=",rightValue:{type:"value",value:c}});}else {let o=Cn(s["CNT?"],e);if(!o)return;a.push(Va(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Zt({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],l=r.find(c=>c.name===o);if(!l){z.error(`Error parsing ink file: Function ${o} is not defined`,i);return}let u=[];for(let c=0;c<l.args;c++)a.length!==0&&u.push(a.pop());a.push({type:"function",functionName:o,args:u.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(l=>l);a.push(o);}else a.push(s);}),a}function ka(i,e,t,n){return Vt(i,e,t,n)}function Zt(i,e,t){let{key:n,defaultType:r}=i,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:r,key:n}}function Qn(i,e,t){let{key:n,value:r,defaultType:a,artmeticValue:s}=i,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:r}];if(s){if(typeof r=="object"&&"list"in r){let l=Object.values(r.list).map(u=>u);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:l}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}else if(typeof r=="object"){if("list"in r&&typeof r.list=="object"){if("origins"in r&&Array.isArray(r.origins)&&r.origins.length>0)return r.origins.reduce(l=>(l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([u,c])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${u}`,value:c});}),l),[]);{let l=new Set,u=Object.entries(r.list).reduce((c,[h,f])=>{let[d,g]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:g,value:f}),l.add(d),c},[]);return l.forEach(c=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([c,h])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${c}`,value:h});}):u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(r.list)}),u}}else if(typeof r=="object"&&"VAR?"in r){if(typeof r["VAR?"]=="string"&&r["VAR?"].includes(".")){let[l,u]=r["VAR?"].split(".");if(l in t.enums&&u in t.enums[l])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[l][u]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:Zt({key:r["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}function Va(i){return {type:"value",storageType:"label",storageOperationType:"get",label:i}}function La(i,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(i)?"call":"jump"}function Ki(i,e){if(e){if(typeof e=="string")e.startsWith("^")&&i.push(ht(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:i.push(e);}}}function Ba(i,e,t,n,r,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:l=false}=a;return Yf(i,e,t,n,r,{isNewLine:s,isHashtagScript:o,isThreads:l})}function Yf(i,e,t,n,r,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:l}=a;if(o){if(Array.isArray(e)&&e.length>0){let u={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"&&!e[0].match(Hu)){let h=e[0],f=xt.convertTagTolist(h),d=xt.convertOperation(f,u,{silent:!0});d&&(d.$origin=h,c.push(d));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),i.push({...u,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&!u.labelToOpen&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}typeof e=="string"?i.push(Qf(ht(e),n.characterIds)):i.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")i.push({end:"game_end"});else if(e==="done")i.push({end:"label_end",goNextStep:true});else if(e==="<>")if(i.length>0){let u=i[i.length-1];u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true),i[i.length-1]=u;}else i.push({glueEnabled:true,goNextStep:false});}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=ht(e.value)),i.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":i.push({goNextStep:true,operations:[e]});break;default:if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}i.push({conditionalStep:e});}else if("->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let c=i[i.length-1];c.labelToOpen||(c.goNextStep=true),i[i.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)i.push({labelToOpen:{label:Zt({key:e["->"],defaultType:"storage"},r),type:l?"call":"jump",params:e.params},glueEnabled:u});else {let c=Cn(e["->"],t);if(!c)return;i.push({labelToOpen:{label:c,type:La(c,l),params:e.params},glueEnabled:u});}}else if("->t->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let h=i[i.length-1];h.labelToOpen||(h.goNextStep=true),i[i.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=Cn(e["->t->"],t);if(!c)return;i.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:u});}}}function Qf(i,e){let t;if(i.includes(": ")){let n=i.split(": "),r=n[0],a=n.slice(1).join(": ");(e?.has(r)||characters.RegisteredCharacters.has(r))&&(t=r,i=a);}return t?{dialogue:{character:t,text:i}}:{dialogue:i}}function Wa(i,e,t,n=true,r=false){return Zf(i,e,t,n,r)}function Zf(i,e,t,n,r=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?i.push(ht(e)):i.push(e):typeof e=="object"&&"type"in e&&i.push(e));}function Xi(i,e,t,n){if(i.length===0){z.error("Error parsing ink file: Arithmetic statement is not valid",i);return}let r=Vt(i,e,t,n);if(r.length===1){let a=r[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function yn(i,e,t,n="",r,a,s=void 0){let o=[],l="sequential",u=false,c=true;i.forEach(d=>{d==="%"&&(l="loop"),d==="seq"&&(l="random"),d==="MIN"&&(u=true);});let h=i[i.length-1];return Object.keys(h).forEach(d=>{let g=h[d];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let y=[];kt(g,n,r,y,e,e,t,vn,s,true,a),y.length===1?o.push(y[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:y});}else Array.isArray(g)&&g.length===3&&(c=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:c?"lastItem":void 0,nestedId:s}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:l}}function kt(i,e,t,n=[],r,a,s,o,l=void 0,u=true,c=[]){let h=false,f=[],d=false,g=false,y=false,_=[],D=[];if(t.preDialog[e]&&(u=false,r(n,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),t.preDialog[e].glue&&r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),delete t.preDialog[e]),i.includes("visit")){let p=yn(i,a,s,e,t,c,l);p&&(!u&&n.length>0&&r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}));return}let m=i[0];if(m&&typeof m=="object"&&"temp="in m){for(;i[0]&&typeof i[0]=="object"&&"temp="in i[0];)c.push(i[0]["temp="]),i.shift();c=c.reverse();}if(i.forEach((p,E)=>{if(g){if(typeof p=="string"&&p==="/#"){let C=[];kt(D,e,t,C,Wa,Wa,s,o,l,u),r(n,C,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),g=false,D=[];}else D.push(p);return}else if(h)if(Array.isArray(p))f.push(p);else if(p&&typeof p=="object")"CNT?"in p?E>0&&i[E-1]==="ev"?(d=true,_.push(p)):d?_.push(p):(f.push(p),u=false):"VAR="in p||"temp="in p?Qn({key:"VAR="in p?p["VAR="]:p["temp="],value:i[E-1],defaultType:"VAR="in p?"storage":"tempstorage"},c,t).forEach(S=>{if(S.value&&typeof S.value=="string"&&S.value==="/str"&&(S.value=i[E-2]),S.value&&typeof S.value=="object"&&"^->"in S.value&&(S.value=S.value["^->"]),f.length>1){let w=Xi(f,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(S.value=w.operation);}(typeof S.key!="string"||!S.key.includes("$r"))&&(r(n,S,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=true);}):"VAR?"in p?f.push(p):"^->"in p?p["^->"].includes("$r")||f.push(p):("f()"in p||"list"in p&&typeof p.list=="object")&&f.push(p);else switch(p){case "/ev":d&&_.push(p),h=false,f.push(p);break;case "out":if(f.length>0){let C=f[f.length-1];if(C&&typeof C=="object"&&"VAR?"in C){f.pop();let S=Zt({key:C["VAR?"],defaultType:"storage"},c);r(n,S,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y});}else {let S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)S.push(f.pop());S=S.reverse();let w=Xi(S,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?r(n,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}):(r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),w=`^${w}`,r(n,w,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}));}u=false;}break;case "pop":{let C=f[f.length-1];if(C&&typeof C=="object"&&"f()"in C){let S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)S.push(f.pop());S=S.reverse();let w=Vt(S,e,c,t);f=[],w.forEach(b=>{b&&typeof b=="object"&&"type"in b&&b.type==="function"?r(n,b,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}):z.warn("Unhandled case: value is not a function",b);}),u=false;}else f.push(p);return}default:f.push(p);}else if(typeof p=="string")if(p.startsWith("^"))r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="ev")h=true;else if(p===`
61
- `)u=true;else if(p==="done"||p==="end")r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="<>")r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="nop"&&d){let C=ac(_,a,s,e,t,c,l);C&&r(n,C,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),d=false,_=[];}else p==="#"?g=true:p==="thread"&&(y=true);else if(Array.isArray(p))if(d)_.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]){f.pop();let C=[],S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)C.push(f.pop());_=[..._,...C.reverse()],d=true,S.push(p.pop()),S.push(p.pop()),_=[..._,...p],_.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){z.error("Error parsing ink file: el is undefined");return}let S=C["#n"];delete C["#n"],p.push(C),r(n,{"->":e?e+"_|_"+S:S},e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),s({[S]:p},e,t);}else kt(p,e,t,n,r,a,s,o,l,u,c);else if(p&&typeof p=="object")if("->"in p&&typeof p["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->"])){let C=[];f.length>0&&(C=ka(["ev",...f],e,c,t)),p.params=C,r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;}else if("->t->"in p&&typeof p["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->t->"])){let C=[];f.length>0&&(C=ka(["ev",...f],e,c,t)),p.params=C,r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;}else if("*"in p&&typeof p["*"]=="string")p["*"].includes("c")&&(f.push(p),u=false);else if("s"in p&&Array.isArray(p.s))f.push(p),u=false;else if("CNT?"in p)f.push(p),u=false;else if("VAR="in p||"temp="in p){let C="VAR="in p?p["VAR="]:p["temp="],S,w=[];if(C!=="$r"){for(f.pop(),f[f.length-1]==="/ev"&&f.pop();f.length>0&&f[f.length-1]!=="/ev";)w.push(f.pop());w=w.reverse(),S=Xi(w,e,c,t),f=[],Qn({key:C,value:S,defaultType:"VAR="in p?"storage":"tempstorage",artmeticValue:true},c,t).forEach(O=>{(O.value!==void 0||O.value!==null)&&r(n,O,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y});}),u=false;}}else s(p,e,t);}),o(f,n,e,t,c),e.includes("_|_")&&n.length===2){let p=n[0],E=n[1];p&&E&&typeof p=="object"&&"dialogue"in p&&typeof E=="object"&&"labelToOpen"in E&&p.dialogue===" "&&E.labelToOpen&&(n.shift(),delete E.glueEnabled,n[0]=E);}}function qa(i,e,t,n,r,a){if(e.length===0)return;let s=Vt(e,n,t,r);if(s.length===1){let o={type:"ifelse",condition:s[0],then:i,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:i,else:a};return o.else||delete o.else,o}}function ac(i,e,t,n,r,a,s=void 0){if(i.length===0){z.error("Error parsing ink file: Conditional statement is not valid",i);return}let o=[],l=[];if(i.forEach(h=>{Array.isArray(h)?l.push(h):typeof h=="string"&&h==="du"?r.du?o.push(r.du):r.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),l.length===0){z.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=ja(l[0],e,t,`${n}${"_|_"}then`,r,a,`${s||""}then`),c;return l.length===2?c=ja(l[1],e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`):l.length>2?(l.shift(),l.push("nop"),l=[{b:l}],c=ja(l,e,t,n,r,a,`${s||""}else`)):c=void 0,r.du=void 0,qa(u,o,a,n,r,c)}function ja(i,e,t,n,r,a,s=void 0){let o=[];for(let u of i)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),kt(u.b,n,r,o,e,e,t,vn,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Ma(i="",e=""){let t=Array.isArray(i)?i:[i],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function vn(i,e,t,n,r){if(i.length>0){let a={};oc(i,a,r,n);for(let[s,o]of Object.entries(a)){let l=t+"_|_"+s,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:La(l,false),oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let c=qa(u,o.conditions,r,t,n)||u,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):z.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),h.choices=f.sort((d,g)=>{try{let y=d.label.split("."),_=y[y.length-1].replaceAll(".","_|_"),D=g.label.split("."),m=D[D.length-1].replaceAll(".","_|_");if(_.includes("c-")&&m.includes("c-")){let p=_.split("c-")[1],E=Number(p),C=m.split("c-")[1],S=Number(C);return E-S}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function oc(i,e,t,n,r){let a=[],s="",o="",l=false,u=[];for(let c=0;c<i.length;c++){let h=i[c];if(typeof h=="string")h.startsWith("^")?a.push(ht(h)):nc.includes(h)&&u.push(h);else if(Array.isArray(h)&&h.includes("visit")){let f=yn(h,Ki,(d,g,y)=>{},r,n,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&&(l=true));else if("s"in h&&Array.isArray(h.s)){let f=lc(h.s),d=h.s.includes("<>");f&&(r&&e[r]?(e[r].preDialog={text:f,glue:d},e[r].text=Ma(f,e[r].text)):(a.push(f),o=f));}else ("CNT?"in h||"VAR?"in h)&&u.push(h);else u.push(h);if(s){e[s]?e[s].text=Ma(a,e[s].text):e[s]={text:a,onetime:l,conditions:u},o&&(e[s].preDialog={text:o,glue:false});let f=i.slice(c+1);oc(f,e,t,n,s);return}}}function lc(i){for(let e of i)if(typeof e=="string"){if(e.startsWith("^"))return ht(e)}else if(Array.isArray(e)){let t=lc(e);if(t)return t}}var $a;(r=>{function i(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:l=[],enums:u={},functions:c=[],preDialog:h={},characterIds:f}=s,d={$schema:ec};if(d.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:l,enums:u,functions:c,preDialog:h,characterIds:f}),d.labels&&Ui in d.labels){let g=d.labels[Ui];delete d.labels[Ui],g.forEach(y=>{y.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...y.operations]:[...y.operations]);});}if(d.labels&&Qt in d.labels){let g=d.labels[Qt];delete d.labels[Qt],g.forEach(y=>{y.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...y.operations]:[...y.operations]);});}return o.forEach(g=>{d.labels&&g in d.labels&&delete d.labels[g];}),l.forEach(g=>{d.initialOperations&&(d.initialOperations=d.initialOperations.filter(y=>!(y.type==="value"&&y.key===g)));}),d}r.inkToJson=i;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){z.error("Error parsing ink file",o);}}function t(a,s,o){for(let l of a)if(l)if(Array.isArray(l))if(l.includes("visit")){let u=yn(l,Ki,(c,h,f)=>{},"",o,[]);u&&(o.externalSwitch=u);}else t(l,s,o);else typeof l=="object"&&(l&&"VAR="in l&&o.externalSwitch&&(s[Qt]||(s[Qt]=[]),s[Qt].push({operations:Qn({defaultType:"storage",key:l["VAR="],value:o.externalSwitch},[],o)})),n(l,s,"",o));}function n(a,s,o="",l){if(a!==null){for(let[u,c]of Object.entries(a))if(Array.isArray(c)){let h=[],f={},d=(o?o+"_|_":"")+u;kt(c,d,l,h,Ba,Ba,(g,y,_)=>{n(g,f,y,_);},vn);for(let[g,y]of Object.entries(f))s[g]=y;h.length>0&&(s[d]=h);}}}})($a||={});var ip=mn(tp()),rp=mn(en()),$y=/(?:^|<>)\s*#\s*([^\r\n]+)/g,Gy=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,Hy=new Set(["DONE","END"]),Jy="_|_",np=new Map;function sp(i,e){let t=JSON.stringify([e,i]),n=np.get(t);if(n)return n;let r=new RegExp(i,e);return np.set(t,r),r}function Li(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>Li(i,s));let r=t.oneOf;if(Array.isArray(r))return r.some(s=>Li(i,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Li(i,s));if(typeof t.const=="string")return i===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===i);if(t.type!=="string"||typeof t.minLength=="number"&&i.length<t.minLength||typeof t.maxLength=="number"&&i.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!sp(t.pattern,"").test(i))return !1}catch{return false}return true}function va(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>va(i,o));let r=t.oneOf;if(Array.isArray(r))return r.some(o=>va(i,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>va(i,o));if(t.type!=="array"||typeof t.minItems=="number"&&i.length<t.minItems||typeof t.maxItems=="number"&&i.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(i.length<s.length)return false;for(let o=0;o<s.length;o++)if(!Li(i[o],s[o]))return false;return i.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:i.slice(s.length).every(o=>Li(o,t.items))}function Uy(i,e){if(e.type==="regexp")try{let t=sp(e.source,e.flags);return t.lastIndex=0,t.test(i.join(" "))}catch{return false}return e.type==="literal"?i.join(" ")===e.value:va(i,e.schema)}function zy(i){let e=i.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let r=e[n];for(let a of r.matchAll($y)){let s=(a[1]??"").trim();if(!s)continue;let o=xt.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}var Ut;(r=>{function i(a,s={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let o=[];try{return {json:new ip.Compiler(a,{errorHandler:(h,f)=>{let d=h.replace(/^[A-Z]+: line \d+: ?/,""),g=h.match(/line (\d+)/);o.push({message:d,type:f,line:g?Number(g[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:h=>h,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:o}}catch{let u=false,c={...s,textSource:a};return e(o,()=>{u=true;},c),u?i(c.textSource,s):{issues:o}}}r.compile=i;function e(a,s,o){let{functions:l,initialVarsToRemove:u,labelToRemove:c}=o,h=a.find(f=>f.type===rp.ErrorType.Error);if(h){if(h.message.includes("Divert target not found")){let f=h.message.match(/Divert target not found: '-> (\w+)'/);if(f?.[1]){let d=f[1],g=`
59
+ ${E}`),E&&(o=true),s=K.getLogichValue(m.glueEnabled,e)||false,E)}),u=K.getLogichValue(l[0],e),c=typeof u=="object"&&"character"in u?u.character:void 0,h=l.flatMap(m=>{let p;m&&typeof m=="object"&&"text"in m?p=m.text:p=m;let E;return Array.isArray(p)?E=p.map(C=>{let S=K.getLogichValue(C,e);return Yn.t(`${S}`)}):E=K.getLogichValue(p,e)||"",Yn.t(E)}),f=a.find(m=>m.end),d=a.find(m=>m.choices),g=false,y=false;a.length>0&&(a[0].glueEnabled&&a[0].goNextStep&&a[0].dialogue===void 0&&(narration.narration.dialogGlue=true),g=a[a.length-1].glueEnabled,y=a.reverse().find(m=>!(m.operations&&(!m.dialogue||!m.choices)))?.goNextStep);let _=a.find(m=>m.labelToOpen),D=[];return a.forEach(m=>{m.operations&&(D=[...D,...m.operations]);}),{dialogue:c?{character:c,text:h}:h,end:f?.end,choices:d?.choices,glueEnabled:g,goNextStep:y,labelToOpen:_?.labelToOpen,operations:D}}}var Va;(i=>{let e=new Set;function t(a){e.add(a);}i.add=t;function n(){e.clear();}i.clear=n;function r(a,s={}){let o=c=>Xu(c,s)??void 0,l=Yu(a,s);if(e.size===0)return o(l);let u=o;for(let c of e){let h=u;u=f=>c(f,h)??void 0;}return u(l)}i.getLogichValue=r;})(Va||={});var Wf=Object.create,Zu=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,qf=Object.getOwnPropertyNames,Mf=Object.getPrototypeOf,$f=Object.prototype.hasOwnProperty,Qu=(i=>typeof Kt<"u"?Kt:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof Kt<"u"?Kt:e)[t]}):i)(function(i){if(typeof Kt<"u")return Kt.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),ec=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Gf=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qf(e))!$f.call(i,r)&&r!==t&&Zu(i,r,{get:()=>e[r],enumerable:!(n=jf(e,r))||n.enumerable});return i},Hf=(i,e,t)=>(t=i!=null?Wf(Mf(i)):{},Gf(Zu(t,"default",{value:i,enumerable:true}),i)),Jf=ec((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n():typeof define=="function"&&define.amd?define([],n):t.CryptoJS=n();})(i,function(){var t=t||(function(n,r){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 Qu=="function")try{a=Qu("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 m(){}return function(p){var E;return m.prototype=p,E=new m,m.prototype=null,E}})(),l={},u=l.lib={},c=u.Base=(function(){return {extend:function(m){var p=o(this);return m&&p.mixIn(m),(!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 m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var p in m)m.hasOwnProperty(p)&&(this[p]=m[p]);m.hasOwnProperty("toString")&&(this.toString=m.toString);},clone:function(){return this.init.prototype.extend(this)}}})(),h=u.WordArray=c.extend({init:function(m,p){m=this.words=m||[],p!=r?this.sigBytes=p:this.sigBytes=m.length*4;},toString:function(m){return (m||d).stringify(this)},concat:function(m){var p=this.words,E=m.words,C=this.sigBytes,S=m.sigBytes;if(this.clamp(),C%4)for(var w=0;w<S;w++){var P=E[w>>>2]>>>24-w%4*8&255;p[C+w>>>2]|=P<<24-(C+w)%4*8;}else for(var x=0;x<S;x+=4)p[C+x>>>2]=E[x>>>2];return this.sigBytes+=S,this},clamp:function(){var m=this.words,p=this.sigBytes;m[p>>>2]&=4294967295<<32-p%4*8,m.length=n.ceil(p/4);},clone:function(){var m=c.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var p=[],E=0;E<m;E+=4)p.push(s());return new h.init(p,m)}}),f=l.enc={},d=f.Hex={stringify:function(m){for(var p=m.words,E=m.sigBytes,C=[],S=0;S<E;S++){var w=p[S>>>2]>>>24-S%4*8&255;C.push((w>>>4).toString(16)),C.push((w&15).toString(16));}return C.join("")},parse:function(m){for(var p=m.length,E=[],C=0;C<p;C+=2)E[C>>>3]|=parseInt(m.substr(C,2),16)<<24-C%8*4;return new h.init(E,p/2)}},g=f.Latin1={stringify:function(m){for(var p=m.words,E=m.sigBytes,C=[],S=0;S<E;S++){var w=p[S>>>2]>>>24-S%4*8&255;C.push(String.fromCharCode(w));}return C.join("")},parse:function(m){for(var p=m.length,E=[],C=0;C<p;C++)E[C>>>2]|=(m.charCodeAt(C)&255)<<24-C%4*8;return new h.init(E,p)}},y=f.Utf8={stringify:function(m){try{return decodeURIComponent(escape(g.stringify(m)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(m){return g.parse(unescape(encodeURIComponent(m)))}},_=u.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new h.init,this._nDataBytes=0;},_append:function(m){typeof m=="string"&&(m=y.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes;},_process:function(m){var p,E=this._data,C=E.words,S=E.sigBytes,w=this.blockSize,P=w*4,x=S/P;m?x=n.ceil(x):x=n.max((x|0)-this._minBufferSize,0);var v=x*w,I=n.min(v*4,S);if(v){for(var V=0;V<v;V+=w)this._doProcessBlock(C,V);p=C.splice(0,v),E.sigBytes-=I;}return new h.init(p,I)},clone:function(){var m=c.clone.call(this);return m._data=this._data.clone(),m},_minBufferSize:0});u.Hasher=_.extend({cfg:c.extend(),init:function(m){this.cfg=this.cfg.extend(m),this.reset();},reset:function(){_.reset.call(this),this._doReset();},update:function(m){return this._append(m),this._process(),this},finalize:function(m){m&&this._append(m);var p=this._doFinalize();return p},blockSize:16,_createHelper:function(m){return function(p,E){return new m.init(E).finalize(p)}},_createHmacHelper:function(m){return function(p,E){return new D.HMAC.init(m,E).finalize(p)}}});var D=l.algo={};return l})(Math);return t});}),Uf=ec((i,e)=>{(function(t,n){typeof i=="object"?e.exports=i=n(Jf()):typeof define=="function"&&define.amd?define(["./core"],n):n(t.CryptoJS);})(i,function(t){return (function(){var n=t,r=n.lib,a=r.WordArray,s=r.Hasher,o=n.algo,l=[],u=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,d=f[0],g=f[1],y=f[2],_=f[3],D=f[4],m=0;m<80;m++){if(m<16)l[m]=c[h+m]|0;else {var p=l[m-3]^l[m-8]^l[m-14]^l[m-16];l[m]=p<<1|p>>>31;}var E=(d<<5|d>>>27)+D+l[m];m<20?E+=(g&y|~g&_)+1518500249:m<40?E+=(g^y^_)+1859775393:m<60?E+=(g&y|g&_|y&_)-1894007588:E+=(g^y^_)-899497514,D=_,_=y,y=g<<30|g>>>2,g=d,d=E;}f[0]=f[0]+d|0,f[1]=f[1]+g|0,f[2]=f[2]+y|0,f[3]=f[3]+_|0,f[4]=f[4]+D|0;},_doFinalize:function(){var c=this._data,h=c.words,f=this._nDataBytes*8,d=c.sigBytes*8;return h[d>>>5]|=128<<24-d%32,h[(d+64>>>9<<4)+14]=Math.floor(f/4294967296),h[(d+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}});n.SHA1=s._createHelper(u),n.HmacSHA1=s._createHmacHelper(u);})(),t.SHA1});});var zf;(i=>(i.log=(e,...t)=>console.log(`[Pixi\u2019VN Json] ${e}`,...t),i.warn=(e,...t)=>console.warn(`[Pixi\u2019VN Json] ${e}`,...t),i.error=(e,...t)=>console.error(`[Pixi\u2019VN Json] ${e}`,...t),i.info=(e,...t)=>console.info(`[Pixi\u2019VN Json] ${e}`,...t)))(zf||={});Hf(Uf());var Kf={version:"1.13.12"};var tc=`https://pixi-vn.com/schemas/${Kf.version}/schema.json`,nc=["==","!=","<","<=",">",">=","CONTAINS"];var ic=["+","-","/","*","%","_","==",">","<",">=","<=","!=","!","&&","||","MIN","MAX"],rc=["+","-","/","*","%","POW","RANDOM","L^"],sc=["INT","FLOOR","FLOAT"];function Cn(i,e){if(i.endsWith(".s"))return;if(new RegExp(/.*\.[0-9]+\..*$/).test(i)&&(i=i.split(".").filter(r=>!r.match(/^[0-9]+$/)).join("."),!i.startsWith(".")))return i.replaceAll(".","_|_");if(!new RegExp(/^\.\^.*$/).test(i)&&i.includes("g-")){let n=i.split("g-");return ka(e)+"_|_"+"g-"+n[n.length-1]}let t=0;for(;new RegExp(/^\.\^.*$/).test(i);)t++,i=i.substring(2);if(t=t-1,new RegExp(/^\..*$/).test(i)&&e){let n=i.substring(1);return ka(e,t)+"_|_"+n.replaceAll(".","_|_")}return i.replaceAll(".","_|_")||ka(e,t).replaceAll(".","_|_")}function ka(i,e=0){let t=i.split("_|_");for(;t.length>1&&e>0;)t.pop()?.includes("g-")&&e--,e--;return t.join("_|_")}var ac="\xA7DOUBLE_SLASH_CONVERTOR\xA7";function ht(i){return i.startsWith("^")&&(i=i.substring(1)),i=i.replaceAll("\\\\",ac),i=i.replaceAll("\\n",`
60
+ `),i=i.replaceAll("\\t"," "),i=i.replaceAll(" "," "),i=i.replaceAll(ac,"\\\\"),i}function Vt(i,e,t,n){let{functions:r}=n;i=i.map(s=>{if(typeof s=="string")switch(s){case "rnd":return "RANDOM";case "?":return "CONTAINS"}return s});let a=[];return i.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)X.error("Error parsing ink file: Conditional statement is not valid",i);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 X.error("Error parsing ink file: Conditional statement is not valid",i);break;default:if(nc.includes(s))if(a.length<2)X.error("Error parsing ink file: Conditional statement is not valid",i);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(rc.includes(s))if(a.length<2)X.error("Error parsing ink file: Conditional statement is not valid",i);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(sc.includes(s)){let o={type:"arithmeticsingle",operator:s,leftValue:a[a.length-1]};a.pop(),a.push(o);}else s.startsWith("^")&&a.push(ht(s));}else if(typeof s=="object"&&"CNT?"in s)if(new RegExp(/.*\.[0-9]\..*/).test(s["CNT?"])){let o=s["CNT?"].split("."),l=o.pop(),u=o.pop();if(u===void 0||l===void 0){X.error("Error parsing ink file: Conditional statement is not valid",i);return}let c=Number(u),h=o.join(".");if(h.includes("^.")){let d=h.split("."),g=d[d.length-1].replaceAll(".","_|_");d.pop(),h=`${d.join(".")}.${g}`,l.includes("c-")&&(h=h+"_|_"+l);}else h=h.replaceAll(".","_|_");let f=Cn(h,e);if(!f)return;a.push({type:"compare",leftValue:La(f),operator:">=",rightValue:{type:"value",value:c}});}else {let o=Cn(s["CNT?"],e);if(!o)return;a.push(La(o));}else if(typeof s=="object"&&"VAR?"in s)a.push(Zt({key:s["VAR?"],defaultType:"storage"},t));else if(typeof s=="object"&&"f()"in s){let o=s["f()"],l=r.find(c=>c.name===o);if(!l){X.error(`Error parsing ink file: Function ${o} is not defined`,i);return}let u=[];for(let c=0;c<l.args;c++)a.length!==0&&u.push(a.pop());a.push({type:"function",functionName:o,args:u.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(l=>l);a.push(o);}else a.push(s);}),a}function Ba(i,e,t,n){return Vt(i,e,t,n)}function Zt(i,e,t){let{key:n,defaultType:r}=i,a=e.indexOf(n);return a>=0?{type:"value",storageType:"params",storageOperationType:"get",key:a}:{type:"value",storageOperationType:"get",storageType:r,key:n}}function Qn(i,e,t){let{key:n,value:r,defaultType:a,artmeticValue:s}=i,o=e.indexOf(n);if(o>=0)return [{type:"value",storageType:"params",storageOperationType:"set",key:o,value:r}];if(s){if(typeof r=="object"&&"list"in r){let l=Object.values(r.list).map(u=>u);return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:l}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}else if(typeof r=="object"){if("list"in r&&typeof r.list=="object"){if("origins"in r&&Array.isArray(r.origins)&&r.origins.length>0)return r.origins.reduce(l=>(l.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(t.enums[n])}),Object.entries(t.enums[n]).forEach(([u,c])=>{l.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${u}`,value:c});}),l),[]);{let l=new Set,u=Object.entries(r.list).reduce((c,[h,f])=>{let[d,g]=h.split(".");return c.push({type:"value",storageOperationType:"set",storageType:a,key:g,value:f}),l.add(d),c},[]);return l.forEach(c=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:c,value:Object.values(t.enums[c])});}),n in t.enums?Object.entries(t.enums[n]).forEach(([c,h])=>{u.push({type:"value",storageOperationType:"set",storageType:a,key:`${n}.${c}`,value:h});}):u.push({type:"value",storageOperationType:"set",storageType:a,key:n,value:Object.values(r.list)}),u}}else if(typeof r=="object"&&"VAR?"in r){if(typeof r["VAR?"]=="string"&&r["VAR?"].includes(".")){let[l,u]=r["VAR?"].split(".");if(l in t.enums&&u in t.enums[l])return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:t.enums[l][u]}]}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:Zt({key:r["VAR?"],defaultType:"storage"},e)}]}}return [{type:"value",storageOperationType:"set",storageType:a,key:n,value:r}]}function La(i){return {type:"value",storageType:"label",storageOperationType:"get",label:i}}function Wa(i,e){return e||new RegExp(`${"_|_".replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}c-\\d+$`).test(i)?"call":"jump"}function Xi(i,e){if(e){if(typeof e=="string")e.startsWith("^")&&i.push(ht(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:i.push(e);}}}function ja(i,e,t,n,r,a={}){let{isNewLine:s=true,isHashtagScript:o=false,isThreads:l=false}=a;return Yf(i,e,t,n,r,{isNewLine:s,isHashtagScript:o,isThreads:l})}function Yf(i,e,t,n,r,a){if(!e)return;let{isNewLine:s,isHashtagScript:o=false,isThreads:l}=a;if(o){if(Array.isArray(e)&&e.length>0){let u={goNextStep:true},c=[];try{if(e.length===1&&typeof e[0]=="string"&&!e[0].match(Ju)){let h=e[0],f=_t.convertTagTolist(h),d=_t.convertOperation(f,u,{silent:!0});d&&(d.$origin=h,c.push(d));}}catch{}c.length===0&&c.push({type:"operationtoconvert",values:e}),i.push({...u,operations:c});}}else if(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"){if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&!u.labelToOpen&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}typeof e=="string"?i.push(Qf(ht(e),n.characterIds)):i.push({dialogue:e});}else if(typeof e=="string"){if(e==="end")i.push({end:"game_end"});else if(e==="done")i.push({end:"label_end",goNextStep:true});else if(e==="<>")if(i.length>0){let u=i[i.length-1];u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true),i[i.length-1]=u;}else i.push({glueEnabled:true,goNextStep:false});}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=ht(e.value)),i.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":i.push({goNextStep:true,operations:[e]});break;default:if(!s&&i.length>0){let u=i[i.length-1];!u.glueEnabled&&!u.operations&&(u.glueEnabled=true,u.labelToOpen||(u.goNextStep=true)),i[i.length-1]=u;}i.push({conditionalStep:e});}else if("->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let c=i[i.length-1];c.labelToOpen||(c.goNextStep=true),i[i.length-1]=c;}if(e.params&&e.params.length===0&&delete e.params,e.var)i.push({labelToOpen:{label:Zt({key:e["->"],defaultType:"storage"},r),type:l?"call":"jump",params:e.params},glueEnabled:u});else {let c=Cn(e["->"],t);if(!c)return;i.push({labelToOpen:{label:c,type:Wa(c,l),params:e.params},glueEnabled:u});}}else if("->t->"in e){let u=s?void 0:true;if(u&&t.includes("c-")&&i.length>0&&i[i.length-1]?.dialogue===void 0&&(u=void 0),!s&&i.length>0){let h=i[i.length-1];h.labelToOpen||(h.goNextStep=true),i[i.length-1]=h;}e.params&&e.params.length===0&&delete e.params;let c=Cn(e["->t->"],t);if(!c)return;i.push({labelToOpen:{label:c,type:"call",params:e.params},glueEnabled:u});}}}function Qf(i,e){let t;if(i.includes(": ")){let n=i.split(": "),r=n[0],a=n.slice(1).join(": ");(e?.has(r)||characters.RegisteredCharacters.has(r))&&(t=r,i=a);}return t?{dialogue:{character:t,text:i}}:{dialogue:i}}function qa(i,e,t,n=true,r=false){return Zf(i,e,t,n,r)}function Zf(i,e,t,n,r=false){e&&(typeof e=="string"&&e.startsWith("^")||e&&typeof e=="object"&&"type"in e&&e.type==="value"&&e.storageOperationType==="get"?typeof e=="string"?i.push(ht(e)):i.push(e):typeof e=="object"&&"type"in e&&i.push(e));}function Yi(i,e,t,n){if(i.length===0){X.error("Error parsing ink file: Arithmetic statement is not valid",i);return}let r=Vt(i,e,t,n);if(r.length===1){let a=r[0];return a&&typeof a=="object"&&"type"in a?{type:"value",storageType:"logic",storageOperationType:"get",operation:a}:a}}function yn(i,e,t,n="",r,a,s=void 0){let o=[],l="sequential",u=false,c=true;i.forEach(d=>{d==="%"&&(l="loop"),d==="seq"&&(l="random"),d==="MIN"&&(u=true);});let h=i[i.length-1];return Object.keys(h).forEach(d=>{let g=h[d];if(Array.isArray(g)&&g.length>3){g=g.slice(1,g.length-2);let y=[];kt(g,n,r,y,e,e,t,vn,s,true,a),y.length===1?o.push(y[0]):o.push({type:"resulttocombine",combine:"cross",secondConditionalItem:y});}else Array.isArray(g)&&g.length===3&&(c=false);}),l==="sequential"?{type:"stepswitch",elements:o,choiceType:l,end:c?"lastItem":void 0,nestedId:s}:u&&l==="random"?{type:"stepswitch",elements:o,choiceType:"sequentialrandom",end:c?"lastItem":void 0,nestedId:s}:{type:"stepswitch",elements:o,choiceType:l}}function kt(i,e,t,n=[],r,a,s,o,l=void 0,u=true,c=[]){let h=false,f=[],d=false,g=false,y=false,_=[],D=[];if(t.preDialog[e]&&(u=false,r(n,`^${t.preDialog[e].text}`,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),t.preDialog[e].glue&&r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),delete t.preDialog[e]),i.includes("visit")){let p=yn(i,a,s,e,t,c,l);p&&(!u&&n.length>0&&r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}));return}let m=i[0];if(m&&typeof m=="object"&&"temp="in m){for(;i[0]&&typeof i[0]=="object"&&"temp="in i[0];)c.push(i[0]["temp="]),i.shift();c=c.reverse();}if(i.forEach((p,E)=>{if(g){if(typeof p=="string"&&p==="/#"){let C=[];kt(D,e,t,C,qa,qa,s,o,l,u),r(n,C,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),g=false,D=[];}else D.push(p);return}else if(h)if(Array.isArray(p))f.push(p);else if(p&&typeof p=="object")"CNT?"in p?E>0&&i[E-1]==="ev"?(d=true,_.push(p)):d?_.push(p):(f.push(p),u=false):"VAR="in p||"temp="in p?Qn({key:"VAR="in p?p["VAR="]:p["temp="],value:i[E-1],defaultType:"VAR="in p?"storage":"tempstorage"},c,t).forEach(S=>{if(S.value&&typeof S.value=="string"&&S.value==="/str"&&(S.value=i[E-2]),S.value&&typeof S.value=="object"&&"^->"in S.value&&(S.value=S.value["^->"]),f.length>1){let w=Yi(f,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"&&(S.value=w.operation);}(typeof S.key!="string"||!S.key.includes("$r"))&&(r(n,S,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=true);}):"VAR?"in p?f.push(p):"^->"in p?p["^->"].includes("$r")||f.push(p):("f()"in p||"list"in p&&typeof p.list=="object")&&f.push(p);else switch(p){case "/ev":d&&_.push(p),h=false,f.push(p);break;case "out":if(f.length>0){let C=f[f.length-1];if(C&&typeof C=="object"&&"VAR?"in C){f.pop();let S=Zt({key:C["VAR?"],defaultType:"storage"},c);r(n,S,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y});}else {let S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)S.push(f.pop());S=S.reverse();let w=Yi(S,e,c,t);f=[],w&&typeof w=="object"&&"type"in w&&w.type==="value"&&"storageType"in w&&w.storageType==="logic"?r(n,{storageOperationType:"get",storageType:"logic",operation:w.operation,type:"value"},e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}):(r(n,"<>",e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),w=`^${w}`,r(n,w,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}));}u=false;}break;case "pop":{let C=f[f.length-1];if(C&&typeof C=="object"&&"f()"in C){let S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)S.push(f.pop());S=S.reverse();let w=Vt(S,e,c,t);f=[],w.forEach(P=>{P&&typeof P=="object"&&"type"in P&&P.type==="function"?r(n,P,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}):X.warn("Unhandled case: value is not a function",P);}),u=false;}else f.push(p);return}default:f.push(p);}else if(typeof p=="string")if(p.startsWith("^"))r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="ev")h=true;else if(p===`
61
+ `)u=true;else if(p==="done"||p==="end")r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="<>")r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;else if(p==="nop"&&d){let C=oc(_,a,s,e,t,c,l);C&&r(n,C,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),d=false,_=[];}else p==="#"?g=true:p==="thread"&&(y=true);else if(Array.isArray(p))if(d)_.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]){f.pop();let C=[],S=[];for(;f.length>0&&f[f.length-1]!=="/ev";)C.push(f.pop());_=[..._,...C.reverse()],d=true,S.push(p.pop()),S.push(p.pop()),_=[..._,...p],_.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){X.error("Error parsing ink file: el is undefined");return}let S=C["#n"];delete C["#n"],p.push(C),r(n,{"->":e?e+"_|_"+S:S},e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),s({[S]:p},e,t);}else kt(p,e,t,n,r,a,s,o,l,u,c);else if(p&&typeof p=="object")if("->"in p&&typeof p["->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->"])){let C=[];f.length>0&&(C=Ba(["ev",...f],e,c,t)),p.params=C,r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;}else if("->t->"in p&&typeof p["->t->"]=="string"&&!new RegExp(/^\.\^\.\^\.\d\.s$/).test(p["->t->"])){let C=[];f.length>0&&(C=Ba(["ev",...f],e,c,t)),p.params=C,r(n,p,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y}),u=false;}else if("*"in p&&typeof p["*"]=="string")p["*"].includes("c")&&(f.push(p),u=false);else if("s"in p&&Array.isArray(p.s))f.push(p),u=false;else if("CNT?"in p)f.push(p),u=false;else if("VAR="in p||"temp="in p){let C="VAR="in p?p["VAR="]:p["temp="],S,w=[];if(C!=="$r"){for(f.pop(),f[f.length-1]==="/ev"&&f.pop();f.length>0&&f[f.length-1]!=="/ev";)w.push(f.pop());w=w.reverse(),S=Yi(w,e,c,t),f=[],Qn({key:C,value:S,defaultType:"VAR="in p?"storage":"tempstorage",artmeticValue:true},c,t).forEach(x=>{(x.value!==void 0||x.value!==null)&&r(n,x,e,t,c,{isNewLine:u,isHashtagScript:g,isThreads:y});}),u=false;}}else s(p,e,t);}),o(f,n,e,t,c),e.includes("_|_")&&n.length===2){let p=n[0],E=n[1];p&&E&&typeof p=="object"&&"dialogue"in p&&typeof E=="object"&&"labelToOpen"in E&&p.dialogue===" "&&E.labelToOpen&&(n.shift(),delete E.glueEnabled,n[0]=E);}}function $a(i,e,t,n,r,a){if(e.length===0)return;let s=Vt(e,n,t,r);if(s.length===1){let o={type:"ifelse",condition:s[0],then:i,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:i,else:a};return o.else||delete o.else,o}}function oc(i,e,t,n,r,a,s=void 0){if(i.length===0){X.error("Error parsing ink file: Conditional statement is not valid",i);return}let o=[],l=[];if(i.forEach(h=>{Array.isArray(h)?l.push(h):typeof h=="string"&&h==="du"?r.du?o.push(r.du):r.du=o[o.length-1]:(typeof h!="string"||h!=="/ev")&&o.push(h);}),l.length===0){X.error("Error parsing ink file: Conditional statement is not valid",l);return}let u=Ma(l[0],e,t,`${n}${"_|_"}then`,r,a,`${s||""}then`),c;return l.length===2?c=Ma(l[1],e,t,`${n}${"_|_"}else`,r,a,`${s||""}else`):l.length>2?(l.shift(),l.push("nop"),l=[{b:l}],c=Ma(l,e,t,n,r,a,`${s||""}else`)):c=void 0,r.du=void 0,$a(u,o,a,n,r,c)}function Ma(i,e,t,n,r,a,s=void 0){let o=[];for(let u of i)typeof u=="object"&&"b"in u&&(u.b=u.b.filter(c=>c!==null&&!(typeof c=="object"&&"->"in c&&new RegExp(/.*\.[0-9]/).test(c["->"]))),kt(u.b,n,r,o,e,e,t,vn,s,true,a));return o.length===1?o[0]:{type:"resulttocombine",combine:"cross",secondConditionalItem:o}}function Ga(i="",e=""){let t=Array.isArray(i)?i:[i],n=Array.isArray(e)?e:[e];return [...new Set([...t,...n])]}function vn(i,e,t,n,r){if(i.length>0){let a={};lc(i,a,r,n);for(let[s,o]of Object.entries(a)){let l=t+"_|_"+s,u={text:o.text.length===1?o.text[0]:o.text,label:l,props:{},type:Wa(l,false),oneTime:o.onetime};o.text.length===0&&(u.onlyHaveNoChoice=true,u.autoSelect=true),u.oneTime===false&&delete u.oneTime;let c=$a(u,o.conditions,r,t,n)||u,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):X.error("Unhandled case: choices is PixiVNJsonConditionalStatements<PixiVNJsonChoices> | undefined",o,f),h.choices=f.sort((d,g)=>{try{let y=d.label.split("."),_=y[y.length-1].replaceAll(".","_|_"),D=g.label.split("."),m=D[D.length-1].replaceAll(".","_|_");if(_.includes("c-")&&m.includes("c-")){let p=_.split("c-")[1],E=Number(p),C=m.split("c-")[1],S=Number(C);return E-S}}catch{}return 0});}else e.push({choices:[c]});o.preDialog&&(n.preDialog[l]={...o.preDialog});}}}function lc(i,e,t,n,r){let a=[],s="",o="",l=false,u=[];for(let c=0;c<i.length;c++){let h=i[c];if(typeof h=="string")h.startsWith("^")?a.push(ht(h)):ic.includes(h)&&u.push(h);else if(Array.isArray(h)&&h.includes("visit")){let f=yn(h,Xi,(d,g,y)=>{},r,n,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&&(l=true));else if("s"in h&&Array.isArray(h.s)){let f=uc(h.s),d=h.s.includes("<>");f&&(r&&e[r]?(e[r].preDialog={text:f,glue:d},e[r].text=Ga(f,e[r].text)):(a.push(f),o=f));}else ("CNT?"in h||"VAR?"in h)&&u.push(h);else u.push(h);if(s){e[s]?e[s].text=Ga(a,e[s].text):e[s]={text:a,onetime:l,conditions:u},o&&(e[s].preDialog={text:o,glue:false});let f=i.slice(c+1);lc(f,e,t,n,s);return}}}function uc(i){for(let e of i)if(typeof e=="string"){if(e.startsWith("^"))return ht(e)}else if(Array.isArray(e)){let t=uc(e);if(t)return t}}var Ha;(r=>{function i(a,s={}){let{labelToRemove:o=[],initialVarsToRemove:l=[],enums:u={},functions:c=[],preDialog:h={},characterIds:f}=s,d={$schema:tc};if(d.labels=e(a.root,{labelToRemove:o,initialVarsToRemove:l,enums:u,functions:c,preDialog:h,characterIds:f}),d.labels&&zi in d.labels){let g=d.labels[zi];delete d.labels[zi],g.forEach(y=>{y.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...y.operations]:[...y.operations]);});}if(d.labels&&Qt in d.labels){let g=d.labels[Qt];delete d.labels[Qt],g.forEach(y=>{y.operations&&(d.initialOperations=d.initialOperations?[...d.initialOperations,...y.operations]:[...y.operations]);});}return o.forEach(g=>{d.labels&&g in d.labels&&delete d.labels[g];}),l.forEach(g=>{d.initialOperations&&(d.initialOperations=d.initialOperations.filter(y=>!(y.type==="value"&&y.key===g)));}),d}r.inkToJson=i;function e(a,s){try{let o={};return t(a,o,s),o}catch(o){X.error("Error parsing ink file",o);}}function t(a,s,o){for(let l of a)if(l)if(Array.isArray(l))if(l.includes("visit")){let u=yn(l,Xi,(c,h,f)=>{},"",o,[]);u&&(o.externalSwitch=u);}else t(l,s,o);else typeof l=="object"&&(l&&"VAR="in l&&o.externalSwitch&&(s[Qt]||(s[Qt]=[]),s[Qt].push({operations:Qn({defaultType:"storage",key:l["VAR="],value:o.externalSwitch},[],o)})),n(l,s,"",o));}function n(a,s,o="",l){if(a!==null){for(let[u,c]of Object.entries(a))if(Array.isArray(c)){let h=[],f={},d=(o?o+"_|_":"")+u;kt(c,d,l,h,ja,ja,(g,y,_)=>{n(g,f,y,_);},vn);for(let[g,y]of Object.entries(f))s[g]=y;h.length>0&&(s[d]=h);}}}})(Ha||={});var rp=mn(np()),sp=mn(en()),$y=/(?:^|<>)\s*#\s*([^\r\n]+)/g,Gy=/^=+[ \t]+(?:function[ \t]+)?(\w+)/gm,Hy=new Set(["DONE","END"]),Jy="_|_",ip=new Map;function ap(i,e){let t=JSON.stringify([e,i]),n=ip.get(t);if(n)return n;let r=new RegExp(i,e);return ip.set(t,r),r}function Li(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(s=>Li(i,s));let r=t.oneOf;if(Array.isArray(r))return r.some(s=>Li(i,s));let a=t.allOf;if(Array.isArray(a))return a.every(s=>Li(i,s));if(typeof t.const=="string")return i===t.const;if(Array.isArray(t.enum))return t.enum.some(s=>typeof s=="string"&&s===i);if(t.type!=="string"||typeof t.minLength=="number"&&i.length<t.minLength||typeof t.maxLength=="number"&&i.length>t.maxLength)return false;if(typeof t.pattern=="string")try{if(!ap(t.pattern,"").test(i))return !1}catch{return false}return true}function Sa(i,e){if(!e||typeof e!="object")return false;let t=e,n=t.anyOf;if(Array.isArray(n))return n.some(o=>Sa(i,o));let r=t.oneOf;if(Array.isArray(r))return r.some(o=>Sa(i,o));let a=t.allOf;if(Array.isArray(a))return a.every(o=>Sa(i,o));if(t.type!=="array"||typeof t.minItems=="number"&&i.length<t.minItems||typeof t.maxItems=="number"&&i.length>t.maxItems)return false;let s=Array.isArray(t.prefixItems)?t.prefixItems:[];if(i.length<s.length)return false;for(let o=0;o<s.length;o++)if(!Li(i[o],s[o]))return false;return i.length===s.length?true:t.items===false||typeof t.items>"u"?false:t.items===true?true:i.slice(s.length).every(o=>Li(o,t.items))}function Uy(i,e){if(e.type==="regexp")try{let t=ap(e.source,e.flags);return t.lastIndex=0,t.test(i.join(" "))}catch{return false}return e.type==="literal"?i.join(" ")===e.value:Sa(i,e.schema)}function zy(i){let e=i.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let r=e[n];for(let a of r.matchAll($y)){let s=(a[1]??"").trim();if(!s)continue;let o=_t.convertTagTolist(s,{mergeInkVariables:true});o.length!==0&&t.push({line:n+1,command:s,tokens:o});}}return t}var Ut;(r=>{function i(a,s={labelToRemove:[],initialVarsToRemove:[],functions:[],enums:{}}){let o=[];try{return {json:new rp.Compiler(a,{errorHandler:(h,f)=>{let d=h.replace(/^[A-Z]+: line \d+: ?/,""),g=h.match(/line (\d+)/);o.push({message:d,type:f,line:g?Number(g[1]):-1});},countAllVisits:!0,fileHandler:{ResolveInkFilename:h=>h,LoadInkFileContents:()=>""},pluginNames:[],sourceFilename:null}).Compile().ToJson()||"",issues:o}}catch{let u=false,c={...s,textSource:a};return e(o,()=>{u=true;},c),u?i(c.textSource,s):{issues:o}}}r.compile=i;function e(a,s,o){let{functions:l,initialVarsToRemove:u,labelToRemove:c}=o,h=a.find(f=>f.type===sp.ErrorType.Error);if(h){if(h.message.includes("Divert target not found")){let f=h.message.match(/Divert target not found: '-> (\w+)'/);if(f?.[1]){let d=f[1],g=`
62
62
 
63
63
  === ${d} ===
64
64
 
@@ -92,8 +92,8 @@ LIST ${g} = ${y}
92
92
 
93
93
  `;return o.textSource=o.textSource.concat(_),o.initialVarsToRemove.push(g),o.initialVarsToRemove.push(`${g}.${y}`),s()}}if(h.message.includes("variable for increment could not be found")){let f=h.message.match(/variable for increment could not be found: '(\w+)' after searching:/);if(f?.[1]){let d=f[1],g=`VAR ${d} = 0
94
94
 
95
- `;return o.textSource=g.concat(o.textSource),o.initialVarsToRemove.push(d),s()}}return a.forEach(f=>{let d=f.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);d?.[1]&&(f.message=`The function '${d[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:a}}return {issues:a}}r.getErrors=e;function t(a,s){return zy(a).filter(({tokens:o})=>!s.some(({validation:l})=>Uy(o,l)))}r.getUnknownHashtagCommands=t;function n(a,s){let o=new Set;for(let f of a.matchAll(Gy))f[1]&&o.add(f[1]);let l=new Set(s),u=new Set,c=a.split(/\r?\n/),h=[];for(let f=0;f<c.length;f++){let d=(c[f]??"").replace(/\/\/.*$/,"");for(let g of d.matchAll(/->[ \t]+(\w[\w.]*)/g)){let y=g[1];if(!y)continue;let _=y.split(".")[0]??y;Hy.has(_)||o.has(_)||l.has(y)||l.has(y.replaceAll(".",Jy))||l.has(_)||u.has(y)||(u.add(y),h.push({line:f+1,target:y}));}}return h}r.getUnknownDivertTargets=n;})(Ut||={});var hu=mn(en());function Ky(i){if(!i||i.length===0)return;let e=new Set;for(let t of i){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function ap(i,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:i},{json:n,issues:r}=Ut.compile(i,t);if(r.forEach(({message:s,type:o})=>{o===hu.ErrorType.Error?z.error(`Ink compilation error: ${s}`):o===hu.ErrorType.Warning?z.warn(`Ink compilation warning: ${s}`):z.info(`Ink compilation info: ${s}`);}),!n){z.error("No JSON generated from ink file");return}let a;try{a=Xn.parse(n);}catch{z.error("Error parsing ink file");return}return t.enums=a.listDefs||{},$a.inkToJson(a,{...t,characterIds:Ky(e.characters)})}var Nu=mn(en()),Iu=mn(up());var cp=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 sv(i){let e=X.normalize(i);return e.length>1&&e[e.length-1]===X.sep&&(e=e.substring(0,e.length-1)),e}var av=/[\\/]/g;function fp(i,e){return i.replace(av,e)}var ov=/^[a-z]:[\\/]$/i;function lv(i){return i==="/"||ov.test(i)}function fu(i,e){let{resolvePaths:t,normalizePath:n,pathSeparator:r}=e,a=process.platform==="win32"&&i.includes("/")||i.startsWith(".");if(t&&(i=X.resolve(i)),(n||a)&&(i=sv(i)),i===".")return "";let s=i[i.length-1]!==r;return fp(s?i+r:i,r)}function dp(i,e){return e+i}function uv(i,e){return function(t,n){return n.startsWith(i)?n.slice(i.length)+t:fp(X.relative(i,n),e.pathSeparator)+e.pathSeparator+t}}function cv(i){return i}function hv(i,e,t){return e+i+t}function pv(i,e){let{relativePaths:t,includeBasePath:n}=e;return t&&i?uv(i,e):n?dp:cv}function fv(i){return function(e,t){t.push(e.substring(i.length)||".");}}function dv(i){return function(e,t,n){let r=e.substring(i.length)||".";n.every(a=>a(r,true))&&t.push(r);}}var gv=(i,e)=>{e.push(i||".");},mv=(i,e,t)=>{let n=i||".";t.every(r=>r(n,true))&&e.push(n);},Cv=()=>{};function yv(i,e){let{includeDirs:t,filters:n,relativePaths:r}=e;return t?r?n&&n.length?dv(i):fv(i):n&&n.length?mv:gv:Cv}var vv=(i,e,t,n)=>{n.every(r=>r(i,false))&&t.files++;},Sv=(i,e,t,n)=>{n.every(r=>r(i,false))&&e.push(i);},Ev=(i,e,t,n)=>{t.files++;},bv=(i,e)=>{e.push(i);},Av=()=>{};function Dv(i){let{excludeFiles:e,filters:t,onlyCounts:n}=i;return e?Av:t&&t.length?n?vv:Sv:n?Ev:bv}var xv=i=>i,_v=()=>[""].slice(0,0);function wv(i){return i.group?_v:xv}var Ov=(i,e,t)=>{i.push({directory:e,files:t,dir:e});},Tv=()=>{};function Pv(i){return i.group?Ov:Tv}var Fv=function(i,e,t){let{queue:n,fs:r,options:{suppressErrors:a}}=e;n.enqueue(),r.realpath(i,(s,o)=>{if(s)return n.dequeue(a?null:s,e);r.stat(o,(l,u)=>{if(l)return n.dequeue(a?null:l,e);if(u.isDirectory()&&gp(i,o,e))return n.dequeue(null,e);t(u,o),n.dequeue(null,e);});});},Nv=function(i,e,t){let{queue:n,fs:r,options:{suppressErrors:a}}=e;n.enqueue();try{let s=r.realpathSync(i),o=r.statSync(s);if(o.isDirectory()&&gp(i,s,e))return;t(o,s);}catch(s){if(!a)throw s}};function Iv(i,e){return !i.resolveSymlinks||i.excludeSymlinks?null:e?Nv:Fv}function gp(i,e,t){if(t.options.useRealPaths)return Rv(e,t);let n=X.dirname(i),r=1;for(;n!==t.root&&r<2;){let a=t.symlinks.get(n);!!a&&(a===e||a.startsWith(e)||e.startsWith(a))?r++:n=X.dirname(n);}return t.symlinks.set(i,e),r>1}function Rv(i,e){return e.visited.includes(i+e.options.pathSeparator)}var Vv=i=>i.counts,kv=i=>i.groups,Lv=i=>i.paths,Bv=i=>i.paths.slice(0,i.options.maxFiles),Wv=(i,e,t)=>(ba(e,t,i.counts,i.options.suppressErrors),null),jv=(i,e,t)=>(ba(e,t,i.paths,i.options.suppressErrors),null),qv=(i,e,t)=>(ba(e,t,i.paths.slice(0,i.options.maxFiles),i.options.suppressErrors),null),Mv=(i,e,t)=>(ba(e,t,i.groups,i.options.suppressErrors),null);function ba(i,e,t,n){e(i&&!n?i:null,t);}function $v(i,e){let{onlyCounts:t,group:n,maxFiles:r}=i;return t?e?Vv:Wv:n?e?kv:Mv:r?e?Bv:qv:e?Lv:jv}var mp={withFileTypes:true},Gv=(i,e,t,n,r)=>{if(i.queue.enqueue(),n<0)return i.queue.dequeue(null,i);let{fs:a}=i;i.visited.push(e),i.counts.directories++,a.readdir(e||".",mp,(s,o=[])=>{r(o,t,n),i.queue.dequeue(i.options.suppressErrors?null:s,i);});},Hv=(i,e,t,n,r)=>{let{fs:a}=i;if(n<0)return;i.visited.push(e),i.counts.directories++;let s=[];try{s=a.readdirSync(e||".",mp);}catch(o){if(!i.options.suppressErrors)throw o}r(s,t,n);};function Jv(i){return i?Hv:Gv}var Uv=class{count=0;constructor(i){this.onQueueEmpty=i;}enqueue(){return this.count++,this.count}dequeue(i,e){this.onQueueEmpty&&(--this.count<=0||i)&&(this.onQueueEmpty(i,e),i&&(e.controller.abort(),this.onQueueEmpty=void 0));}},zv=class{_files=0;_directories=0;set files(i){this._files=i;}get files(){return this._files}set directories(i){this._directories=i;}get directories(){return this._directories}get dirs(){return this._directories}},Kv=class{aborted=false;abort(){this.aborted=true;}},Cp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(i,e,t){this.isSynchronous=!t,this.callbackInvoker=$v(e,this.isSynchronous),this.root=fu(i,e),this.state={root:lv(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new zv,options:e,queue:new Uv((n,r)=>this.callbackInvoker(r,n,t)),symlinks:new Map,visited:[""].slice(0,0),controller:new Kv,fs:e.fs||rv__namespace},this.joinPath=pv(this.root,e),this.pushDirectory=yv(this.root,e),this.pushFile=Dv(e),this.getArray=wv(e),this.groupFiles=Pv(e),this.resolveSymlink=Iv(e,this.isSynchronous),this.walkDirectory=Jv(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=(i,e,t)=>{let{paths:n,options:{filters:r,resolveSymlinks:a,excludeSymlinks:s,exclude:o,maxFiles:l,signal:u,useRealPaths:c,pathSeparator:h},controller:f}=this.state;if(f.aborted||u&&u.aborted||l&&n.length>l)return;let d=this.getArray(this.state.paths);for(let g=0;g<i.length;++g){let y=i[g];if(y.isFile()||y.isSymbolicLink()&&!a&&!s){let _=this.joinPath(y.name,e);this.pushFile(_,d,this.state.counts,r);}else if(y.isDirectory()){let _=hv(y.name,e,this.state.options.pathSeparator);if(o&&o(y.name,_))continue;this.pushDirectory(_,n,r),this.walkDirectory(this.state,_,_,t-1,this.walk);}else if(this.resolveSymlink&&y.isSymbolicLink()){let _=dp(y.name,e);this.resolveSymlink(_,this.state,(D,m)=>{if(D.isDirectory()){if(m=fu(m,this.state.options),o&&o(y.name,c?m:_+h))return;this.walkDirectory(this.state,m,c?m:_+h,t-1,this.walk);}else {m=c?m:_;let p=X.basename(m),E=fu(X.dirname(m),this.state.options);m=this.joinPath(p,E),this.pushFile(m,d,this.state.counts,r);}});}}this.groupFiles(this.state.groups,e,d);}};function Xv(i,e){return new Promise((t,n)=>{yp(i,e,(r,a)=>{if(r)return n(r);t(a);});})}function yp(i,e,t){new Cp(i,e,t).start();}function Yv(i,e){return new Cp(i,e).start()}var hp=class{constructor(i,e){this.root=i,this.options=e;}withPromise(){return Xv(this.root,this.options)}withCallback(i){yp(this.root,this.options,i);}sync(){return Yv(this.root,this.options)}},vp=null;try{cp.resolve("picomatch"),vp=cp("picomatch");}catch{}var Sp=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:X.sep,filters:[]};globFunction;constructor(i){this.options={...this.options,...i},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(i){return this.options.pathSeparator=i,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(i){return this.options.maxDepth=i,this}withMaxFiles(i){return this.options.maxFiles=i,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:i=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=i,this.withFullPaths()}withAbortSignal(i){return this.options.signal=i,this}normalize(){return this.options.normalizePath=true,this}filter(i){return this.options.filters.push(i),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(i){return this.options.exclude=i,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(i){return new hp(i||".",this.options)}withGlobFunction(i){return this.globFunction=i,this}crawlWithOptions(i,e){return this.options={...this.options,...e},new hp(i||".",this.options)}glob(...i){return this.globFunction?this.globWithOptions(i):this.globWithOptions(i,{dot:true})}globWithOptions(i,...e){let t=this.globFunction||vp;if(!t)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[i.join("\0")];return n||(n=t(i,...e),this.globCache[i.join("\0")]=n),this.options.filters.push(r=>n(r)),this}};var Hn=mn(Gp()),M0=Array.isArray,zp=/\\/g,$0=/^[A-Za-z]:$/,Kp=process.platform==="win32",G0=/^(\/?\.\.)+$/;function H0(i,e={}){let t=i.length,n=Array(t),r=Array(t),a,s;for(a=0;a<t;a++){let o=Xp(i[a]);n[a]=o;let l=o.length,u=Array(l);for(s=0;s<l;s++)u[s]=(0, Hn.default)(o[s],e);r[a]=u;}return o=>{let l=o.split("/");if(l[0]===".."&&G0.test(o))return true;for(a=0;a<t;a++){let u=n[a],c=r[a],h=l.length,f=Math.min(h,u.length);for(s=0;s<f;){let d=u[s];if(d.includes("/"))return true;if(!c[s](l[s]))break;if(!e.noglobstar&&d==="**")return true;s++;}if(s===h)return true}return false}}var J0=/^[A-Z]:\/$/i,U0=Kp?i=>J0.test(i):i=>i==="/";function Hp(i,e,t){if(i===e||e.startsWith(`${i}/`)){if(t){let r=i.length+ +!U0(i);return (a,s)=>a.slice(r,s?-1:void 0)||"."}let n=e.slice(i.length+1);return n?(r,a)=>{if(r===".")return n;let s=`${n}/${r}`;return a?s.slice(0,-1):s}:(r,a)=>a&&r!=="."?r.slice(0,-1):r}return t?n=>X.posix.relative(i,n)||".":n=>X.posix.relative(i,`${e}/${n}`)||"."}function z0(i,e){if(e.startsWith(`${i}/`)){let t=e.slice(i.length+1);return n=>`${t}/${n}`}return t=>{let n=X.posix.relative(i,`${e}/${t}`);return t[t.length-1]==="/"&&n!==""?`${n}/`:n||"."}}function Jp(i){return i.replace($0,e=>`${e}/`)}var K0={parts:true};function Xp(i){var e;let t=Hn.default.scan(i,K0);return !((e=t.parts)===null||e===void 0)&&e.length?t.parts:[i]}var X0=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Y0=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Q0=i=>i.replace(X0,"\\$&"),Z0=i=>i.replace(Y0,"\\$&"),eS=Kp?Z0:Q0;function tS(i,e){let t=Hn.default.scan(i);return t.isGlob||t.negated}function Mi(...i){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...i);}function Yp(i){return typeof i=="string"?[i]:i??[]}var nS=/^(\/?\.\.)+/,iS=/\\(?=[()[\]{}!*+?@|])/g;function _u(i,e,t,n){var r;let a=e.cwd,s=i;i[i.length-1]==="/"&&(s=i.slice(0,-1)),s[s.length-1]!=="*"&&e.expandDirectories&&(s+="/**");let o=eS(a);s=X.isAbsolute(s.replace(iS,""))?X.posix.relative(o,s):X.posix.normalize(s);let l=(r=nS.exec(s))===null||r===void 0?void 0:r[0],u=Xp(s);if(l){let h=(l.length+1)/3,f=0,d=o.split("/");for(;f<h&&u[f+h]===d[d.length+f-h];)s=s.slice(0,(h-f-1)*3)+s.slice((h-f)*3+u[f+h].length+1)||".",f++;let g=X.posix.join(a,l.slice(f*3));g[0]!=="."&&t.root.length>g.length&&(t.root=Jp(g),t.depthOffset=-h+f);}if(!n&&t.depthOffset>=0){var c;(c=t.commonPath)!==null&&c!==void 0||(t.commonPath=u);let h=[],f=Math.min(t.commonPath.length,u.length);for(let d=0;d<f;d++){let g=u[d];if(g==="**"&&!u[d+1]){h.pop();break}if(d===u.length-1||g!==t.commonPath[d]||tS(g))break;h.push(g);}t.depthOffset=h.length,t.commonPath=h,t.root=Jp(h.length>0?X.posix.join(a,...h):a);}return s}function rS(i,e,t){let n=[],r=[];for(let a of i.ignore)a&&(a[0]!=="!"||a[1]==="(")&&r.push(_u(a,i,t,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?n.push(_u(a,i,t,false)):(a[1]!=="!"||a[2]==="(")&&r.push(_u(a.slice(1),i,t,true)));return {match:n,ignore:r}}function sS(i,e){let t=i.cwd,n={root:t,depthOffset:0},r=rS(i,e,n);i.debug&&Mi("internal processing patterns:",r);let{absolute:a,caseSensitiveMatch:s,debug:o,dot:l,followSymbolicLinks:u,onlyDirectories:c}=i,h=n.root.replace(zp,""),f={dot:l,nobrace:i.braceExpansion===false,nocase:!s,noextglob:i.extglob===false,noglobstar:i.globstar===false,posix:true},d=(0, Hn.default)(r.match,f),g=(0, Hn.default)(r.ignore,f),y=H0(r.match,f),_=Hp(t,h,a),D=a?_:Hp(t,h,true),m=(C,S)=>{let w=D(S,true);return w!=="."&&!y(w)||g(w)},p;i.deep!==void 0&&(p=Math.round(i.deep-n.depthOffset));let E=new Sp({filters:[o?(C,S)=>{let w=_(C,S),b=d(w)&&!g(w);return b&&Mi(`matched ${w}`),b}:(C,S)=>{let w=_(C,S);return d(w)&&!g(w)}],exclude:o?(C,S)=>{let w=m(C,S);return Mi(`${w?"skipped":"crawling"} ${S}`),w}:m,fs:i.fs,pathSeparator:"/",relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:u,excludeSymlinks:!u,excludeFiles:c,includeDirs:c||!i.onlyFiles,maxDepth:p,signal:i.signal}).crawl(h);return i.debug&&Mi("internal properties:",{...n,root:h}),[E,t!==h&&!a&&z0(t,h)]}function aS(i,e){if(e)for(let t=i.length-1;t>=0;t--)i[t]=e(i[t]);return i}var Up={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function oS(i){let e=Object.assign({},i);for(let t in Up)e[t]===void 0&&Object.assign(e,{[t]:Up[t]});return e.cwd=(e.cwd instanceof URL?url.fileURLToPath(e.cwd):X.resolve(e.cwd||process.cwd())).replace(zp,"/"),e.ignore=Yp(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||rv.readdir,readdirSync:e.fs.readdirSync||rv.readdirSync,realpath:e.fs.realpath||rv.realpath,realpathSync:e.fs.realpathSync||rv.realpathSync,stat:e.fs.stat||rv.stat,statSync:e.fs.statSync||rv.statSync}),e.debug&&Mi("globbing with options:",e),e}function lS(i,e={}){var t;if(i&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=M0(i)||typeof i=="string",r=Yp((t=n?i:i.patterns)!==null&&t!==void 0?t:"**/*"),a=oS(n?e:i);return r.length>0?sS(a,r):[]}async function wu(i,e){let[t,n]=lS(i,e);return t?aS(await t.withPromise(),n):[]}var Ft=Iu.default.cyan("(pixi-vn-ink)"),af="virtual:pixi-vn-ink",Ou=`\0${af}`,hS="manifest.json",of=/\[(name|ext|extname|file|path|dir)\]/g,Qp="ink";function Zp(i){if(typeof i=="string")return {type:"literal",value:i};if(i instanceof RegExp)return {type:"regexp",source:i.source,flags:i.flags};try{return {type:"zod",schema:zod.toJSONSchema(i)}}catch{return {type:"literal",value:""}}}function zt(i){return i.replaceAll("\\","/")}function Tu(i){let e=zt(i.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 ef(i,e){let t=zt(e).split("/"),n=[];for(let r of t)if(!(r==="."||r==="")){if(/[*!?[\]{}()]/.test(r))break;n.push(r);}return X__default.default.resolve(i,...n)}function tf(i,e){if(!e)return;let t=e.trim();if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must not be empty.");return X__default.default.isAbsolute(t)?X__default.default.normalize(t):X__default.default.resolve(i,t)}function nf(i,e,t){if(!t)return X__default.default.join(e,hS);let n=t.trim();if(!n)throw new Error("vitePluginInk option `inkJsonManifestPath` must not be empty.");return X__default.default.isAbsolute(n)?X__default.default.normalize(n):X__default.default.resolve(i,n)}function rf(i){let e=i.search(of);if(e===-1)return X__default.default.dirname(i);let t=i.slice(0,e).replace(/[\\/]+$/g,"");if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must start with a static directory before placeholders.");return X__default.default.normalize(t)}function Jn(i,e){let t=X__default.default.relative(i,e);return !t.startsWith("..")&&!X__default.default.isAbsolute(t)}function pS(i,e,t,n){let r=zt(X__default.default.relative(t,n)),a=X__default.default.posix.parse(r),s=zt(X__default.default.relative(e,n)),o=X__default.default.posix.dirname(s),l=X__default.default.posix.dirname(r),u={name:a.name,ext:a.ext.startsWith(".")?a.ext.slice(1):a.ext,extname:a.ext,file:r,path:l==="."?"":`${l}/`,dir:o==="."?"":`${o}/`},c=zt(i).replace(of,(h,f)=>u[f]??"");return X__default.default.normalize(c)}function fS(i,e,t){return Jn(t,i)?`/${zt(X__default.default.relative(t,i))}`:Jn(e,i)?zt(X__default.default.relative(e,i)):zt(i)}function Pu(i,e,t){let n=Ut.getUnknownHashtagCommands(i,e);n.forEach(({command:r,line:a})=>{t(`Unknown hashtag command "# ${r}": no registered handler matched this command.`,a);}),n.length>0&&t(`Hashtag command metadata is available via ${Un}.`);}function Fu(i,e,t){if(e.length===0)return;Ut.getUnknownDivertTargets(i,e).forEach(({target:r,line:a})=>{t(`Divert target "${r}" not found in any known label source.`,a);});}async function dS(i,e,t){let n=e.get(i);return n||(n=(async()=>{try{let r=await fetch(i);if(!r.ok)throw new Error(`HTTP ${r.status} ${r.statusText}`);let a=await r.json();return new uS__default.default({strict:!1,allErrors:!0}).compile(a)}catch(r){t(`Could not load/compile JSON schema from "${i}" (${r instanceof Error?r.message:String(r)}). Skipping schema validation.`);return}})(),e.set(i,n)),n}function gS(i,e){let t=e.split("/").filter(Boolean).map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),n=i,r,a=s=>{s&&typeof s=="object"&&typeof s.$origin=="string"&&(r=s.$origin);};a(n);for(let s of t){if(n===null||typeof n!="object")break;n=n[s],a(n);}return r}function mS(i){let e=i.map(o=>o.instancePath),t=o=>e.some(l=>l!==o&&l.startsWith(`${o}/`)),n=i.filter(o=>!t(o.instancePath)),r=new Map;for(let o of n){let l=r.get(o.instancePath)??[];l.push(o),r.set(o.instancePath,l);}let a=[];for(let o of r.values()){let l=o.filter(u=>u.keyword!=="anyOf"&&u.keyword!=="oneOf");a.push(...l.length>0?l:o);}let s=new Set;return a.filter(o=>{let u=`${o.instancePath.split("/").pop()??o.instancePath}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}async function CS(i,e,t,n){let r=i.$schema;if(!r)return;let a=await dS(r,t,n);if(!(!a||a(i)))for(let o of mS(a.errors??[])){let l=gS(i,o.instancePath),u=o.instancePath||"(root)",c=l?` \u2014 from ink source: "${l}"`:"";n(`${e}: schema validation failed at "${u}": ${o.message??"invalid value"}${c}`);}}function sf(i){return new Promise((e,t)=>{let n="";i.on("data",r=>{n+=r.toString();}),i.on("end",()=>e(n)),i.on("error",t);})}function lf(i){let{inkGlob:e,inkJsonOutputPattern:t,inkJsonManifestPath:n,characters:r}=i??{},a=!!t,s,o=[],l=[],u,c,h,f=[],d,g,y,_=new Map,D=async()=>{let b=xt.info(),O=It.info();o=b.map(({name:v,description:V,validation:I})=>({name:v,description:V,validation:Zp(I)})),l=O.map(({name:v,description:V,validation:I,type:B})=>({name:v,description:V,validation:Zp(I),type:B}));},m=b=>b?.find(O=>O.name==="vite-plugin-pixi-vn"),p=b=>{let O=b?.find(v=>v.name==="vite-plugin-nqtr");return [m(b)?.api?.contentLoaded,O?.api?.contentLoaded].filter(v=>!!v)},E=async b=>{let O=b?.api;if(!O)return;let v=f,V=JSON.stringify(v);if(V!==d)try{if(v.length===0&&O.clearExternalLabels)await O.clearExternalLabels(Qp);else if(O.setExternalLabels)await O.setExternalLabels(Qp,v);else return;d=V;}catch(I){let B=I instanceof Error?I:new Error(String(I));s?.logger.error(`${Ft} Failed to sync Ink labels with vite-plugin-pixi-vn.`,{error:B,timestamp:true});}},C=b=>{if(!a||!c)return false;let O=X__default.default.resolve(b);return h&&O===h?true:Jn(c,O)},S=()=>{y!==void 0&&clearTimeout(y),y=setTimeout(()=>{y=void 0,w().then(async()=>{await E(m(g?.config.plugins));let b=g?.moduleGraph.getModuleById(Ou);b&&g?.moduleGraph.invalidateModule(b),g?.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?u??[]:void 0}});}).catch(b=>{let O=b instanceof Error?b:new Error(String(b));s?.logger.error(`${Ft} Failed to re-export Ink JSON files after characters update.`,{error:O,timestamp:true});});},150);},w=async()=>{if(!s||!e){u=void 0,f=[];return}let b=tf(s.root,t);if(!b){u=void 0,f=[],c=void 0,h=void 0;return}let O=Tu(e),v=rf(b);c=X__default.default.resolve(v);let V=ef(s.root,O);if(!Jn(s.root,V))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");let I=await wu(O,{absolute:true,cwd:s.root,onlyFiles:true}),B=[],A=[],x=new Set,Q=m(s.plugins)?.api?.characters??[],j=[...r??[],...Q];await Pt__default.default.mkdir(v,{recursive:true});let ne=new Map;for(let R of I){let Le=await Pt__default.default.readFile(R,"utf-8");ne.set(R,Le);let rt;try{rt=ap(Le,{characters:j});}catch(Y){let N=Y instanceof Error?Y:new Error(String(Y));s.logger.error(`${Ft} Failed to convert "${R}" to JSON.`,{error:N,timestamp:true});continue}let F=pS(b,s.root,V,R);if(!Jn(v,F)){s.logger.error(`${Ft} Output path "${F}" escapes managed directory "${v}".`,{timestamp:true});continue}if(x.add(F),!rt){await Pt__default.default.rm(F,{force:true});continue}A.push(rt),await Pt__default.default.mkdir(X__default.default.dirname(F),{recursive:true}),await Pt__default.default.writeFile(F,`${JSON.stringify(rt,null,2)}
96
- `,"utf-8"),B.push(fS(F,s.root,s.publicDir)),await CS(rt,R,_,Y=>s.logger.warn(`${Ft} ${Y}`,{timestamp:true}));}let Ve=nf(s.root,v,n);h=X__default.default.resolve(Ve);let ke=await wu("**/*.json",{absolute:true,cwd:v,onlyFiles:true});for(let R of ke)X__default.default.resolve(R)!==X__default.default.resolve(Ve)&&!x.has(R)&&await Pt__default.default.rm(R,{force:true});B.sort((R,Le)=>R.localeCompare(Le)),u=A;let it=A.flatMap(R=>Object.keys(R.labels??{}));f=Array.from(new Set(it)).sort((R,Le)=>R.localeCompare(Le));let Da=it.length,gn=m(s.plugins)?.api?.labels??[],lt=[...f,...gn];for(let[R,Le]of ne)Pu(Le,o,(rt,F)=>s.logger.warn(`${F!==void 0?`${R}:${F}`:R}: ${rt}`,{timestamp:true})),Fu(Le,lt,(rt,F)=>s.logger.warn(`${F!==void 0?`${R}:${F}`:R}: ${rt}`,{timestamp:true}));s.logger.info(`${Ft} ${Iu.default.dim(`${I.length} file(s) exported: ${Da} label(s), ${o.length} hashtag-command(s), ${l.length} text-replace(s)`)}`,{timestamp:true}),await Pt__default.default.mkdir(X__default.default.dirname(Ve),{recursive:true}),await Pt__default.default.writeFile(Ve,`${JSON.stringify(B,null,2)}
97
- `,"utf-8");};return {name:"vite-plugin-ink",enforce:"pre",configResolved(b){s=b,c=void 0,h=void 0;let O=e?Tu(e):void 0;if(O){let v=ef(b.root,O);if(!Jn(b.root,v))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 v=tf(b.root,t);if(!v)return;let V=rf(v);if(c=X__default.default.resolve(V),h=X__default.default.resolve(nf(b.root,V,n)),X__default.default.resolve(V)===X__default.default.resolve(b.root))throw new Error("vitePluginInk option `inkJsonOutputPattern` must target a directory different from Vite `root`.")}},async buildStart(){let b=m(s?.plugins);await Promise.all(p(s?.plugins)),await D(),await w(),await E(b);},configureServer(b){g=b,b.middlewares.use(async(V,I,B)=>{let A=V.url,x=V.method;if(A===Un){if(x==="GET"){I.setHeader("Content-Type","application/json"),I.end(JSON.stringify(o));return}if(x==="POST"){try{let Q=await sf(V);o=JSON.parse(Q),I.statusCode=204,I.end();}catch(Q){s?.logger.warn(`${Ft} Invalid JSON body for POST ${Un}: ${String(Q)}`,{timestamp:true}),I.statusCode=400,I.end();}return}}if(A===$i){if(x==="GET"){I.setHeader("Content-Type","application/json"),I.end(JSON.stringify(l));return}if(x==="POST"){try{let Q=await sf(V);l=JSON.parse(Q),I.statusCode=204,I.end();}catch(Q){s?.logger.warn(`${Ft} Invalid JSON body for POST ${$i}: ${String(Q)}`,{timestamp:true}),I.statusCode=400,I.end();}return}}B();});let O=m(b.config.plugins);Promise.all(p(b.config.plugins)).then(async()=>{await D(),await w(),await E(O);}).catch(V=>{let I=V instanceof Error?V:new Error(String(V));s?.logger.error(`${Ft} Failed to export Ink JSON files during server initialization or restart.`,{error:I,timestamp:true});});let v=O?.api?.onReload;v&&v(()=>{D().then(()=>S());});},resolveId(b){if(b===af)return Ou},load(b){if(b===Ou){if(!e)return ["export const inkJsons = undefined;","export default [];"].join(`
98
- `);let O=Tu(e);return [`const modules = import.meta.glob(${JSON.stringify(`/${O}`)}, { eager: true, import: 'default' });`,`export const inkJsons = ${JSON.stringify(a?u??[]:void 0)};`,"export default Object.values(modules);"].join(`
99
- `)}},hotUpdate:{order:"post",async handler({type:b,file:O,server:v,read:V}){if(O.endsWith(".ink")){if(b!=="delete"){let I=await V(),{issues:B}=Ut.compile(I),A;B.forEach(({line:Q,message:j,type:ne})=>{ne===Nu.ErrorType.Warning?v.config.logger.warn(`${O}:${Q} ${j}`,{timestamp:true}):(v.config.logger.error(`${O}:${Q} ${j}`,{timestamp:true}),A=j);}),Pu(I,o,(Q,j)=>v.config.logger.warn(`${j!==void 0?`${O}:${j}`:O}: ${Q}`,{timestamp:true}));let x=m(v.config.plugins)?.api?.labels??[];Fu(I,[...f,...x],(Q,j)=>v.config.logger.warn(`${j!==void 0?`${O}:${j}`:O}: ${Q}`,{timestamp:true})),await w(),await E(m(v.config.plugins)),A?v.ws.send({type:"error",err:{message:A,stack:O,plugin:"vite-plugin-ink"}}):(v.ws.send({type:"custom",event:"ink-error-cleared",data:{}}),v.ws.send({type:"custom",event:"ink-updated",data:{inkText:I,inkJson:a?u??[]:void 0}}));}else await w(),await E(m(v.config.plugins)),v.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?u??[]:void 0}});return []}if(O.endsWith(".json")&&C(O))return await E(m(v.config.plugins)),v.ws.send({type:"custom",event:"ink-updated",data:{inkJson:u??[]}}),[]}},async transform(b,O){if(!O.endsWith(".ink"))return null;let v=await Pt__default.default.readFile(O,"utf-8"),{issues:V}=Ut.compile(v);V.forEach(({line:B,message:A,type:x})=>{x===Nu.ErrorType.Warning?this.warn(`${O}:${B} ${A}`):this.error(`${O}:${B} ${A}`);}),Pu(v,o,(B,A)=>this.warn({message:B,loc:A!==void 0?{line:A,column:0}:void 0}));let I=m(s?.plugins)?.api?.labels??[];return Fu(v,[...f,...I],(B,A)=>this.warn({message:B,loc:A!==void 0?{line:A,column:0}:void 0})),{code:`export default ${JSON.stringify(v)};`,map:null}}}}exports.INK_DEV_API_HASHTAG_COMMANDS=Un;exports.INK_DEV_API_TEXT_REPLACES=$i;exports.noHmrInkPlugin=lf;exports.vitePluginInk=lf;
95
+ `;return o.textSource=g.concat(o.textSource),o.initialVarsToRemove.push(d),s()}}return a.forEach(f=>{let d=f.message.match(/Function call to '(\w+)' requires (\d+) arguments, but got (\d+)/);d?.[1]&&(f.message=`The function '${d[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:a}}return {issues:a}}r.getErrors=e;function t(a,s){return zy(a).filter(({tokens:o})=>!s.some(({validation:l})=>Uy(o,l)))}r.getUnknownHashtagCommands=t;function n(a,s){let o=new Set;for(let f of a.matchAll(Gy))f[1]&&o.add(f[1]);let l=new Set(s),u=new Set,c=a.split(/\r?\n/),h=[];for(let f=0;f<c.length;f++){let d=(c[f]??"").replace(/\/\/.*$/,"");for(let g of d.matchAll(/->[ \t]+(\w[\w.]*)/g)){let y=g[1];if(!y)continue;let _=y.split(".")[0]??y;Hy.has(_)||o.has(_)||l.has(y)||l.has(y.replaceAll(".",Jy))||l.has(_)||u.has(y)||(u.add(y),h.push({line:f+1,target:y}));}}return h}r.getUnknownDivertTargets=n;})(Ut||={});var fu=mn(en());function Ky(i){if(!i||i.length===0)return;let e=new Set;for(let t of i){let n=typeof t=="string"?t:t?.id;typeof n=="string"&&n.length>0&&e.add(n);}return e.size>0?e:void 0}function du(i,e={}){let t={labelToRemove:[],initialVarsToRemove:[],functions:e.functions||[],enums:e.enums||{},textSource:i},{json:n,issues:r}=Ut.compile(i,t);if(r.forEach(({message:s,type:o})=>{o===fu.ErrorType.Error?X.error(`Ink compilation error: ${s}`):o===fu.ErrorType.Warning?X.warn(`Ink compilation warning: ${s}`):X.info(`Ink compilation info: ${s}`);}),!n){X.error("No JSON generated from ink file");return}let a;try{a=Xn.parse(n);}catch{X.error("Error parsing ink file");return}return t.enums=a.listDefs||{},Ha.inkToJson(a,{...t,characterIds:Ky(e.characters)})}var Iu=mn(en()),Ru=mn(up());var cp=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 sv(i){let e=Q.normalize(i);return e.length>1&&e[e.length-1]===Q.sep&&(e=e.substring(0,e.length-1)),e}var av=/[\\/]/g;function fp(i,e){return i.replace(av,e)}var ov=/^[a-z]:[\\/]$/i;function lv(i){return i==="/"||ov.test(i)}function mu(i,e){let{resolvePaths:t,normalizePath:n,pathSeparator:r}=e,a=process.platform==="win32"&&i.includes("/")||i.startsWith(".");if(t&&(i=Q.resolve(i)),(n||a)&&(i=sv(i)),i===".")return "";let s=i[i.length-1]!==r;return fp(s?i+r:i,r)}function dp(i,e){return e+i}function uv(i,e){return function(t,n){return n.startsWith(i)?n.slice(i.length)+t:fp(Q.relative(i,n),e.pathSeparator)+e.pathSeparator+t}}function cv(i){return i}function hv(i,e,t){return e+i+t}function pv(i,e){let{relativePaths:t,includeBasePath:n}=e;return t&&i?uv(i,e):n?dp:cv}function fv(i){return function(e,t){t.push(e.substring(i.length)||".");}}function dv(i){return function(e,t,n){let r=e.substring(i.length)||".";n.every(a=>a(r,true))&&t.push(r);}}var gv=(i,e)=>{e.push(i||".");},mv=(i,e,t)=>{let n=i||".";t.every(r=>r(n,true))&&e.push(n);},Cv=()=>{};function yv(i,e){let{includeDirs:t,filters:n,relativePaths:r}=e;return t?r?n&&n.length?dv(i):fv(i):n&&n.length?mv:gv:Cv}var vv=(i,e,t,n)=>{n.every(r=>r(i,false))&&t.files++;},Sv=(i,e,t,n)=>{n.every(r=>r(i,false))&&e.push(i);},Ev=(i,e,t,n)=>{t.files++;},bv=(i,e)=>{e.push(i);},Av=()=>{};function Dv(i){let{excludeFiles:e,filters:t,onlyCounts:n}=i;return e?Av:t&&t.length?n?vv:Sv:n?Ev:bv}var xv=i=>i,_v=()=>[""].slice(0,0);function wv(i){return i.group?_v:xv}var Ov=(i,e,t)=>{i.push({directory:e,files:t,dir:e});},Tv=()=>{};function Pv(i){return i.group?Ov:Tv}var Fv=function(i,e,t){let{queue:n,fs:r,options:{suppressErrors:a}}=e;n.enqueue(),r.realpath(i,(s,o)=>{if(s)return n.dequeue(a?null:s,e);r.stat(o,(l,u)=>{if(l)return n.dequeue(a?null:l,e);if(u.isDirectory()&&gp(i,o,e))return n.dequeue(null,e);t(u,o),n.dequeue(null,e);});});},Nv=function(i,e,t){let{queue:n,fs:r,options:{suppressErrors:a}}=e;n.enqueue();try{let s=r.realpathSync(i),o=r.statSync(s);if(o.isDirectory()&&gp(i,s,e))return;t(o,s);}catch(s){if(!a)throw s}};function Iv(i,e){return !i.resolveSymlinks||i.excludeSymlinks?null:e?Nv:Fv}function gp(i,e,t){if(t.options.useRealPaths)return Rv(e,t);let n=Q.dirname(i),r=1;for(;n!==t.root&&r<2;){let a=t.symlinks.get(n);!!a&&(a===e||a.startsWith(e)||e.startsWith(a))?r++:n=Q.dirname(n);}return t.symlinks.set(i,e),r>1}function Rv(i,e){return e.visited.includes(i+e.options.pathSeparator)}var Vv=i=>i.counts,kv=i=>i.groups,Lv=i=>i.paths,Bv=i=>i.paths.slice(0,i.options.maxFiles),Wv=(i,e,t)=>(Aa(e,t,i.counts,i.options.suppressErrors),null),jv=(i,e,t)=>(Aa(e,t,i.paths,i.options.suppressErrors),null),qv=(i,e,t)=>(Aa(e,t,i.paths.slice(0,i.options.maxFiles),i.options.suppressErrors),null),Mv=(i,e,t)=>(Aa(e,t,i.groups,i.options.suppressErrors),null);function Aa(i,e,t,n){e(i&&!n?i:null,t);}function $v(i,e){let{onlyCounts:t,group:n,maxFiles:r}=i;return t?e?Vv:Wv:n?e?kv:Mv:r?e?Bv:qv:e?Lv:jv}var mp={withFileTypes:true},Gv=(i,e,t,n,r)=>{if(i.queue.enqueue(),n<0)return i.queue.dequeue(null,i);let{fs:a}=i;i.visited.push(e),i.counts.directories++,a.readdir(e||".",mp,(s,o=[])=>{r(o,t,n),i.queue.dequeue(i.options.suppressErrors?null:s,i);});},Hv=(i,e,t,n,r)=>{let{fs:a}=i;if(n<0)return;i.visited.push(e),i.counts.directories++;let s=[];try{s=a.readdirSync(e||".",mp);}catch(o){if(!i.options.suppressErrors)throw o}r(s,t,n);};function Jv(i){return i?Hv:Gv}var Uv=class{count=0;constructor(i){this.onQueueEmpty=i;}enqueue(){return this.count++,this.count}dequeue(i,e){this.onQueueEmpty&&(--this.count<=0||i)&&(this.onQueueEmpty(i,e),i&&(e.controller.abort(),this.onQueueEmpty=void 0));}},zv=class{_files=0;_directories=0;set files(i){this._files=i;}get files(){return this._files}set directories(i){this._directories=i;}get directories(){return this._directories}get dirs(){return this._directories}},Kv=class{aborted=false;abort(){this.aborted=true;}},Cp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(i,e,t){this.isSynchronous=!t,this.callbackInvoker=$v(e,this.isSynchronous),this.root=mu(i,e),this.state={root:lv(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new zv,options:e,queue:new Uv((n,r)=>this.callbackInvoker(r,n,t)),symlinks:new Map,visited:[""].slice(0,0),controller:new Kv,fs:e.fs||rv__namespace},this.joinPath=pv(this.root,e),this.pushDirectory=yv(this.root,e),this.pushFile=Dv(e),this.getArray=wv(e),this.groupFiles=Pv(e),this.resolveSymlink=Iv(e,this.isSynchronous),this.walkDirectory=Jv(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=(i,e,t)=>{let{paths:n,options:{filters:r,resolveSymlinks:a,excludeSymlinks:s,exclude:o,maxFiles:l,signal:u,useRealPaths:c,pathSeparator:h},controller:f}=this.state;if(f.aborted||u&&u.aborted||l&&n.length>l)return;let d=this.getArray(this.state.paths);for(let g=0;g<i.length;++g){let y=i[g];if(y.isFile()||y.isSymbolicLink()&&!a&&!s){let _=this.joinPath(y.name,e);this.pushFile(_,d,this.state.counts,r);}else if(y.isDirectory()){let _=hv(y.name,e,this.state.options.pathSeparator);if(o&&o(y.name,_))continue;this.pushDirectory(_,n,r),this.walkDirectory(this.state,_,_,t-1,this.walk);}else if(this.resolveSymlink&&y.isSymbolicLink()){let _=dp(y.name,e);this.resolveSymlink(_,this.state,(D,m)=>{if(D.isDirectory()){if(m=mu(m,this.state.options),o&&o(y.name,c?m:_+h))return;this.walkDirectory(this.state,m,c?m:_+h,t-1,this.walk);}else {m=c?m:_;let p=Q.basename(m),E=mu(Q.dirname(m),this.state.options);m=this.joinPath(p,E),this.pushFile(m,d,this.state.counts,r);}});}}this.groupFiles(this.state.groups,e,d);}};function Xv(i,e){return new Promise((t,n)=>{yp(i,e,(r,a)=>{if(r)return n(r);t(a);});})}function yp(i,e,t){new Cp(i,e,t).start();}function Yv(i,e){return new Cp(i,e).start()}var hp=class{constructor(i,e){this.root=i,this.options=e;}withPromise(){return Xv(this.root,this.options)}withCallback(i){yp(this.root,this.options,i);}sync(){return Yv(this.root,this.options)}},vp=null;try{cp.resolve("picomatch"),vp=cp("picomatch");}catch{}var Sp=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:Q.sep,filters:[]};globFunction;constructor(i){this.options={...this.options,...i},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(i){return this.options.pathSeparator=i,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(i){return this.options.maxDepth=i,this}withMaxFiles(i){return this.options.maxFiles=i,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:i=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=i,this.withFullPaths()}withAbortSignal(i){return this.options.signal=i,this}normalize(){return this.options.normalizePath=true,this}filter(i){return this.options.filters.push(i),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(i){return this.options.exclude=i,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(i){return new hp(i||".",this.options)}withGlobFunction(i){return this.globFunction=i,this}crawlWithOptions(i,e){return this.options={...this.options,...e},new hp(i||".",this.options)}glob(...i){return this.globFunction?this.globWithOptions(i):this.globWithOptions(i,{dot:true})}globWithOptions(i,...e){let t=this.globFunction||vp;if(!t)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[i.join("\0")];return n||(n=t(i,...e),this.globCache[i.join("\0")]=n),this.options.filters.push(r=>n(r)),this}};var Hn=mn(Gp()),M0=Array.isArray,zp=/\\/g,$0=/^[A-Za-z]:$/,Kp=process.platform==="win32",G0=/^(\/?\.\.)+$/;function H0(i,e={}){let t=i.length,n=Array(t),r=Array(t),a,s;for(a=0;a<t;a++){let o=Xp(i[a]);n[a]=o;let l=o.length,u=Array(l);for(s=0;s<l;s++)u[s]=(0, Hn.default)(o[s],e);r[a]=u;}return o=>{let l=o.split("/");if(l[0]===".."&&G0.test(o))return true;for(a=0;a<t;a++){let u=n[a],c=r[a],h=l.length,f=Math.min(h,u.length);for(s=0;s<f;){let d=u[s];if(d.includes("/"))return true;if(!c[s](l[s]))break;if(!e.noglobstar&&d==="**")return true;s++;}if(s===h)return true}return false}}var J0=/^[A-Z]:\/$/i,U0=Kp?i=>J0.test(i):i=>i==="/";function Hp(i,e,t){if(i===e||e.startsWith(`${i}/`)){if(t){let r=i.length+ +!U0(i);return (a,s)=>a.slice(r,s?-1:void 0)||"."}let n=e.slice(i.length+1);return n?(r,a)=>{if(r===".")return n;let s=`${n}/${r}`;return a?s.slice(0,-1):s}:(r,a)=>a&&r!=="."?r.slice(0,-1):r}return t?n=>Q.posix.relative(i,n)||".":n=>Q.posix.relative(i,`${e}/${n}`)||"."}function z0(i,e){if(e.startsWith(`${i}/`)){let t=e.slice(i.length+1);return n=>`${t}/${n}`}return t=>{let n=Q.posix.relative(i,`${e}/${t}`);return t[t.length-1]==="/"&&n!==""?`${n}/`:n||"."}}function Jp(i){return i.replace($0,e=>`${e}/`)}var K0={parts:true};function Xp(i){var e;let t=Hn.default.scan(i,K0);return !((e=t.parts)===null||e===void 0)&&e.length?t.parts:[i]}var X0=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Y0=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Q0=i=>i.replace(X0,"\\$&"),Z0=i=>i.replace(Y0,"\\$&"),eS=Kp?Z0:Q0;function tS(i,e){let t=Hn.default.scan(i);return t.isGlob||t.negated}function Mi(...i){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...i);}function Yp(i){return typeof i=="string"?[i]:i??[]}var nS=/^(\/?\.\.)+/,iS=/\\(?=[()[\]{}!*+?@|])/g;function Tu(i,e,t,n){var r;let a=e.cwd,s=i;i[i.length-1]==="/"&&(s=i.slice(0,-1)),s[s.length-1]!=="*"&&e.expandDirectories&&(s+="/**");let o=eS(a);s=Q.isAbsolute(s.replace(iS,""))?Q.posix.relative(o,s):Q.posix.normalize(s);let l=(r=nS.exec(s))===null||r===void 0?void 0:r[0],u=Xp(s);if(l){let h=(l.length+1)/3,f=0,d=o.split("/");for(;f<h&&u[f+h]===d[d.length+f-h];)s=s.slice(0,(h-f-1)*3)+s.slice((h-f)*3+u[f+h].length+1)||".",f++;let g=Q.posix.join(a,l.slice(f*3));g[0]!=="."&&t.root.length>g.length&&(t.root=Jp(g),t.depthOffset=-h+f);}if(!n&&t.depthOffset>=0){var c;(c=t.commonPath)!==null&&c!==void 0||(t.commonPath=u);let h=[],f=Math.min(t.commonPath.length,u.length);for(let d=0;d<f;d++){let g=u[d];if(g==="**"&&!u[d+1]){h.pop();break}if(d===u.length-1||g!==t.commonPath[d]||tS(g))break;h.push(g);}t.depthOffset=h.length,t.commonPath=h,t.root=Jp(h.length>0?Q.posix.join(a,...h):a);}return s}function rS(i,e,t){let n=[],r=[];for(let a of i.ignore)a&&(a[0]!=="!"||a[1]==="(")&&r.push(Tu(a,i,t,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?n.push(Tu(a,i,t,false)):(a[1]!=="!"||a[2]==="(")&&r.push(Tu(a.slice(1),i,t,true)));return {match:n,ignore:r}}function sS(i,e){let t=i.cwd,n={root:t,depthOffset:0},r=rS(i,e,n);i.debug&&Mi("internal processing patterns:",r);let{absolute:a,caseSensitiveMatch:s,debug:o,dot:l,followSymbolicLinks:u,onlyDirectories:c}=i,h=n.root.replace(zp,""),f={dot:l,nobrace:i.braceExpansion===false,nocase:!s,noextglob:i.extglob===false,noglobstar:i.globstar===false,posix:true},d=(0, Hn.default)(r.match,f),g=(0, Hn.default)(r.ignore,f),y=H0(r.match,f),_=Hp(t,h,a),D=a?_:Hp(t,h,true),m=(C,S)=>{let w=D(S,true);return w!=="."&&!y(w)||g(w)},p;i.deep!==void 0&&(p=Math.round(i.deep-n.depthOffset));let E=new Sp({filters:[o?(C,S)=>{let w=_(C,S),P=d(w)&&!g(w);return P&&Mi(`matched ${w}`),P}:(C,S)=>{let w=_(C,S);return d(w)&&!g(w)}],exclude:o?(C,S)=>{let w=m(C,S);return Mi(`${w?"skipped":"crawling"} ${S}`),w}:m,fs:i.fs,pathSeparator:"/",relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:u,excludeSymlinks:!u,excludeFiles:c,includeDirs:c||!i.onlyFiles,maxDepth:p,signal:i.signal}).crawl(h);return i.debug&&Mi("internal properties:",{...n,root:h}),[E,t!==h&&!a&&z0(t,h)]}function aS(i,e){if(e)for(let t=i.length-1;t>=0;t--)i[t]=e(i[t]);return i}var Up={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function oS(i){let e=Object.assign({},i);for(let t in Up)e[t]===void 0&&Object.assign(e,{[t]:Up[t]});return e.cwd=(e.cwd instanceof URL?url.fileURLToPath(e.cwd):Q.resolve(e.cwd||process.cwd())).replace(zp,"/"),e.ignore=Yp(e.ignore),e.fs&&(e.fs={readdir:e.fs.readdir||rv.readdir,readdirSync:e.fs.readdirSync||rv.readdirSync,realpath:e.fs.realpath||rv.realpath,realpathSync:e.fs.realpathSync||rv.realpathSync,stat:e.fs.stat||rv.stat,statSync:e.fs.statSync||rv.statSync}),e.debug&&Mi("globbing with options:",e),e}function lS(i,e={}){var t;if(i&&e?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=M0(i)||typeof i=="string",r=Yp((t=n?i:i.patterns)!==null&&t!==void 0?t:"**/*"),a=oS(n?e:i);return r.length>0?sS(a,r):[]}async function xa(i,e){let[t,n]=lS(i,e);return t?aS(await t.withPromise(),n):[]}var Ft=Ru.default.cyan("(pixi-vn-ink)"),af="virtual:pixi-vn-ink",Pu=`\0${af}`,hS="manifest.json",of=/\[(name|ext|extname|file|path|dir)\]/g,Qp="ink";function Zp(i){if(typeof i=="string")return {type:"literal",value:i};if(i instanceof RegExp)return {type:"regexp",source:i.source,flags:i.flags};try{return {type:"zod",schema:zod.toJSONSchema(i)}}catch{return {type:"literal",value:""}}}function zt(i){return i.replaceAll("\\","/")}function _a(i){let e=zt(i.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 ef(i,e){let t=zt(e).split("/"),n=[];for(let r of t)if(!(r==="."||r==="")){if(/[*!?[\]{}()]/.test(r))break;n.push(r);}return Q__default.default.resolve(i,...n)}function tf(i,e){if(!e)return;let t=e.trim();if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must not be empty.");return Q__default.default.isAbsolute(t)?Q__default.default.normalize(t):Q__default.default.resolve(i,t)}function nf(i,e,t){if(!t)return Q__default.default.join(e,hS);let n=t.trim();if(!n)throw new Error("vitePluginInk option `inkJsonManifestPath` must not be empty.");return Q__default.default.isAbsolute(n)?Q__default.default.normalize(n):Q__default.default.resolve(i,n)}function rf(i){let e=i.search(of);if(e===-1)return Q__default.default.dirname(i);let t=i.slice(0,e).replace(/[\\/]+$/g,"");if(!t)throw new Error("vitePluginInk option `inkJsonOutputPattern` must start with a static directory before placeholders.");return Q__default.default.normalize(t)}function Jn(i,e){let t=Q__default.default.relative(i,e);return !t.startsWith("..")&&!Q__default.default.isAbsolute(t)}function pS(i,e,t,n){let r=zt(Q__default.default.relative(t,n)),a=Q__default.default.posix.parse(r),s=zt(Q__default.default.relative(e,n)),o=Q__default.default.posix.dirname(s),l=Q__default.default.posix.dirname(r),u={name:a.name,ext:a.ext.startsWith(".")?a.ext.slice(1):a.ext,extname:a.ext,file:r,path:l==="."?"":`${l}/`,dir:o==="."?"":`${o}/`},c=zt(i).replace(of,(h,f)=>u[f]??"");return Q__default.default.normalize(c)}function fS(i,e,t){return Jn(t,i)?`/${zt(Q__default.default.relative(t,i))}`:Jn(e,i)?zt(Q__default.default.relative(e,i)):zt(i)}function Fu(i,e,t){let n=Ut.getUnknownHashtagCommands(i,e);n.forEach(({command:r,line:a})=>{t(`Unknown hashtag command "# ${r}": no registered handler matched this command.`,a);}),n.length>0&&t(`Hashtag command metadata is available via ${Un}.`);}function Nu(i,e,t){if(e.length===0)return;Ut.getUnknownDivertTargets(i,e).forEach(({target:r,line:a})=>{t(`Divert target "${r}" not found in any known label source.`,a);});}async function dS(i,e,t){let n=e.get(i);return n||(n=(async()=>{try{let r=await fetch(i);if(!r.ok)throw new Error(`HTTP ${r.status} ${r.statusText}`);let a=await r.json();return new uS__default.default({strict:!1,allErrors:!0}).compile(a)}catch(r){t(`Could not load/compile JSON schema from "${i}" (${r instanceof Error?r.message:String(r)}). Skipping schema validation.`);return}})(),e.set(i,n)),n}function gS(i,e){let t=e.split("/").filter(Boolean).map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")),n=i,r,a=s=>{s&&typeof s=="object"&&typeof s.$origin=="string"&&(r=s.$origin);};a(n);for(let s of t){if(n===null||typeof n!="object")break;n=n[s],a(n);}return r}function mS(i){let e=i.map(o=>o.instancePath),t=o=>e.some(l=>l!==o&&l.startsWith(`${o}/`)),n=i.filter(o=>!t(o.instancePath)),r=new Map;for(let o of n){let l=r.get(o.instancePath)??[];l.push(o),r.set(o.instancePath,l);}let a=[];for(let o of r.values()){let l=o.filter(u=>u.keyword!=="anyOf"&&u.keyword!=="oneOf");a.push(...l.length>0?l:o);}let s=new Set;return a.filter(o=>{let u=`${o.instancePath.split("/").pop()??o.instancePath}|${o.message}`;return s.has(u)?false:(s.add(u),true)})}async function CS(i,e,t,n){let r=i.$schema;if(!r)return;let a=await dS(r,t,n);if(!(!a||a(i)))for(let o of mS(a.errors??[])){let l=gS(i,o.instancePath),u=o.instancePath||"(root)",c=l?` \u2014 from ink source: "${l}"`:"";n(`${e}: schema validation failed at "${u}": ${o.message??"invalid value"}${c}`);}}function sf(i){return new Promise((e,t)=>{let n="";i.on("data",r=>{n+=r.toString();}),i.on("end",()=>e(n)),i.on("error",t);})}function lf(i){let{inkGlob:e,inkJsonOutputPattern:t,inkJsonManifestPath:n,characters:r}=i??{},a=!!t,s,o=[],l=[],u,c,h,f=[],d,g,y,_=new Map,D=async()=>{let x=_t.info(),v=It.info();o=x.map(({name:I,description:V,validation:R})=>({name:I,description:V,validation:Zp(R)})),l=v.map(({name:I,description:V,validation:R,type:b})=>({name:I,description:V,validation:Zp(R),type:b}));},m=x=>x?.find(v=>v.name==="vite-plugin-pixi-vn"),p=x=>{let v=x?.find(I=>I.name==="vite-plugin-nqtr");return [m(x)?.api?.contentLoaded,v?.api?.contentLoaded].filter(I=>!!I)},E=async x=>{let v=x?.api;if(!v)return;let I=f,V=JSON.stringify(I);if(V!==d)try{if(I.length===0&&v.clearExternalLabels)await v.clearExternalLabels(Qp);else if(v.setExternalLabels)await v.setExternalLabels(Qp,I);else return;d=V;}catch(R){let b=R instanceof Error?R:new Error(String(R));s?.logger.error(`${Ft} Failed to sync Ink labels with vite-plugin-pixi-vn.`,{error:b,timestamp:true});}},C=x=>{if(!a||!c)return false;let v=Q__default.default.resolve(x);return h&&v===h?true:Jn(c,v)},S=()=>{y!==void 0&&clearTimeout(y),y=setTimeout(()=>{y=void 0,P().then(async()=>{await E(m(g?.config.plugins));let x=g?.moduleGraph.getModuleById(Pu);x&&g?.moduleGraph.invalidateModule(x),g?.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?u??[]:void 0}});}).catch(x=>{let v=x instanceof Error?x:new Error(String(x));s?.logger.error(`${Ft} Failed to re-export Ink JSON files after characters update.`,{error:v,timestamp:true});});},150);},w=async()=>{if(!s||!e)return [];let x=_a(e),v=await xa(x,{absolute:true,cwd:s.root,onlyFiles:true}),I=[];for(let V of v)try{let R=await bt__default.default.readFile(V,"utf-8"),b=du(R,{characters:r??[]});b&&I.push(...Object.keys(b.labels??{}));}catch{}return Array.from(new Set(I)).sort((V,R)=>V.localeCompare(R))},P=async()=>{if(!s||!e){u=void 0,f=[];return}let x=tf(s.root,t);if(!x){u=void 0,f=[],c=void 0,h=void 0;return}let v=_a(e),I=rf(x);c=Q__default.default.resolve(I);let V=ef(s.root,v);if(!Jn(s.root,V))throw new Error("vitePluginInk option `inkGlob` must be rooted in Vite `root` and cannot escape it.");let R=await xa(v,{absolute:true,cwd:s.root,onlyFiles:true}),b=[],A=[],he=new Set,B=m(s.plugins)?.api?.characters??[],U=[...r??[],...B];await bt__default.default.mkdir(I,{recursive:true});let Le=new Map;for(let ae of R){let it=await bt__default.default.readFile(ae,"utf-8");Le.set(ae,it);let F;try{F=du(it,{characters:U});}catch(N){let M=N instanceof Error?N:new Error(String(N));s.logger.error(`${Ft} Failed to convert "${ae}" to JSON.`,{error:M,timestamp:true});continue}let G=pS(x,s.root,V,ae);if(!Jn(I,G)){s.logger.error(`${Ft} Output path "${G}" escapes managed directory "${I}".`,{timestamp:true});continue}if(he.add(G),!F){await bt__default.default.rm(G,{force:true});continue}A.push(F),await bt__default.default.mkdir(Q__default.default.dirname(G),{recursive:true}),await bt__default.default.writeFile(G,`${JSON.stringify(F,null,2)}
96
+ `,"utf-8"),b.push(fS(G,s.root,s.publicDir)),await CS(F,ae,_,N=>s.logger.warn(`${Ft} ${N}`,{timestamp:true}));}let we=nf(s.root,I,n);h=Q__default.default.resolve(we);let ot=await xa("**/*.json",{absolute:true,cwd:I,onlyFiles:true});for(let ae of ot)Q__default.default.resolve(ae)!==Q__default.default.resolve(we)&&!he.has(ae)&&await bt__default.default.rm(ae,{force:true});b.sort((ae,it)=>ae.localeCompare(it)),u=A;let $i=A.flatMap(ae=>Object.keys(ae.labels??{}));f=Array.from(new Set($i)).sort((ae,it)=>ae.localeCompare(it));let gn=$i.length,lt=m(s.plugins)?.api?.labels??[],q=[...f,...lt];for(let[ae,it]of Le)Fu(it,o,(F,G)=>s.logger.warn(`${G!==void 0?`${ae}:${G}`:ae}: ${F}`,{timestamp:true})),Nu(it,q,(F,G)=>s.logger.warn(`${G!==void 0?`${ae}:${G}`:ae}: ${F}`,{timestamp:true}));s.logger.info(`${Ft} ${Ru.default.dim(`${R.length} file(s) exported: ${gn} label(s), ${o.length} hashtag-command(s), ${l.length} text-replace(s)`)}`,{timestamp:true}),await bt__default.default.mkdir(Q__default.default.dirname(we),{recursive:true}),await bt__default.default.writeFile(we,`${JSON.stringify(b,null,2)}
97
+ `,"utf-8");};return {name:"vite-plugin-ink",enforce:"pre",configResolved(x){s=x,c=void 0,h=void 0;let v=e?_a(e):void 0;if(v){let I=ef(x.root,v);if(!Jn(x.root,I))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 I=tf(x.root,t);if(!I)return;let V=rf(I);if(c=Q__default.default.resolve(V),h=Q__default.default.resolve(nf(x.root,V,n)),Q__default.default.resolve(V)===Q__default.default.resolve(x.root))throw new Error("vitePluginInk option `inkJsonOutputPattern` must target a directory different from Vite `root`.")}},async buildStart(){let x=m(s?.plugins);f=await w(),await E(x),await Promise.all(p(s?.plugins)),await D(),await P(),await E(x);},configureServer(x){g=x,x.middlewares.use(async(V,R,b)=>{let A=V.url,he=V.method;if(A===Un){if(he==="GET"){R.setHeader("Content-Type","application/json"),R.end(JSON.stringify(o));return}if(he==="POST"){try{let B=await sf(V);o=JSON.parse(B),R.statusCode=204,R.end();}catch(B){s?.logger.warn(`${Ft} Invalid JSON body for POST ${Un}: ${String(B)}`,{timestamp:true}),R.statusCode=400,R.end();}return}}if(A===Gi){if(he==="GET"){R.setHeader("Content-Type","application/json"),R.end(JSON.stringify(l));return}if(he==="POST"){try{let B=await sf(V);l=JSON.parse(B),R.statusCode=204,R.end();}catch(B){s?.logger.warn(`${Ft} Invalid JSON body for POST ${Gi}: ${String(B)}`,{timestamp:true}),R.statusCode=400,R.end();}return}}b();});let v=m(x.config.plugins);Promise.all(p(x.config.plugins)).then(async()=>{await D(),await P(),await E(v);}).catch(V=>{let R=V instanceof Error?V:new Error(String(V));s?.logger.error(`${Ft} Failed to export Ink JSON files during server initialization or restart.`,{error:R,timestamp:true});});let I=v?.api?.onReload;I&&I(()=>{D().then(()=>S());});},resolveId(x){if(x===af)return Pu},load(x){if(x===Pu){if(!e)return ["export const inkJsons = undefined;","export default [];"].join(`
98
+ `);let v=_a(e);return [`const modules = import.meta.glob(${JSON.stringify(`/${v}`)}, { eager: true, import: 'default' });`,`export const inkJsons = ${JSON.stringify(a?u??[]:void 0)};`,"export default Object.values(modules);"].join(`
99
+ `)}},hotUpdate:{order:"post",async handler({type:x,file:v,server:I,read:V}){if(v.endsWith(".ink")){if(x!=="delete"){let R=await V(),{issues:b}=Ut.compile(R),A;b.forEach(({line:B,message:U,type:Le})=>{Le===Iu.ErrorType.Warning?I.config.logger.warn(`${v}:${B} ${U}`,{timestamp:true}):(I.config.logger.error(`${v}:${B} ${U}`,{timestamp:true}),A=U);}),Fu(R,o,(B,U)=>I.config.logger.warn(`${U!==void 0?`${v}:${U}`:v}: ${B}`,{timestamp:true}));let he=m(I.config.plugins)?.api?.labels??[];Nu(R,[...f,...he],(B,U)=>I.config.logger.warn(`${U!==void 0?`${v}:${U}`:v}: ${B}`,{timestamp:true})),await P(),await E(m(I.config.plugins)),A?I.ws.send({type:"error",err:{message:A,stack:v,plugin:"vite-plugin-ink"}}):(I.ws.send({type:"custom",event:"ink-error-cleared",data:{}}),I.ws.send({type:"custom",event:"ink-updated",data:{inkText:R,inkJson:a?u??[]:void 0}}));}else await P(),await E(m(I.config.plugins)),I.ws.send({type:"custom",event:"ink-updated",data:{inkJson:a?u??[]:void 0}});return []}if(v.endsWith(".json")&&C(v))return await E(m(I.config.plugins)),I.ws.send({type:"custom",event:"ink-updated",data:{inkJson:u??[]}}),[]}},async transform(x,v){if(!v.endsWith(".ink"))return null;let I=await bt__default.default.readFile(v,"utf-8"),{issues:V}=Ut.compile(I);V.forEach(({line:b,message:A,type:he})=>{he===Iu.ErrorType.Warning?this.warn(`${v}:${b} ${A}`):this.error(`${v}:${b} ${A}`);}),Fu(I,o,(b,A)=>this.warn({message:b,loc:A!==void 0?{line:A,column:0}:void 0}));let R=m(s?.plugins)?.api?.labels??[];return Nu(I,[...f,...R],(b,A)=>this.warn({message:b,loc:A!==void 0?{line:A,column:0}:void 0})),{code:`export default ${JSON.stringify(I)};`,map:null}}}}exports.INK_DEV_API_HASHTAG_COMMANDS=Un;exports.INK_DEV_API_TEXT_REPLACES=Gi;exports.noHmrInkPlugin=lf;exports.vitePluginInk=lf;